Commit ba856927 authored by Jude Gao's avatar Jude Gao

[Plugin] Add experimental next-dev Claude Code plugin

Adds a new `next-dev` plugin to the Next.js Claude Code marketplace
that wires the dev server's MCP endpoint into Claude Code via two
skill-scoped hooks:

- UserPromptSubmit: pings the dev server and calls `pause_compilation`
  so intermediate edits don't trigger HMR.
- Stop: calls `compile_and_resume` (one batch compile) followed by
  `get_compilation_issues`, blocking the agent from finishing if
  compilation errors exist.

State files (`.claude/port`, `.claude/dismissed-issues.json`) are
project-local; hook scripts live under `${CLAUDE_PLUGIN_ROOT}`.

Marked experimental in the manifest, marketplace, and README — depends
on `pause_compilation`/`compile_and_resume` MCP tools that are still
landing in #92410. The activation script verifies the tools are
present and refuses to enable hooks otherwise.
parent d3cbd5ba
......@@ -13,6 +13,15 @@
"author": {
"name": "Next.js Team"
}
},
{
"name": "next-dev",
"source": "./plugins/next-dev",
"description": "Experimental: real-time Turbopack compilation feedback for agents. Pauses compilation during edits, batches one compile at turn-end, blocks on errors. Requires unreleased MCP tools (pause_compilation/compile_and_resume/get_compilation_issues).",
"version": "0.1.0",
"author": {
"name": "Next.js Team"
}
}
]
}
......@@ -24,6 +24,7 @@ The Next.js repository serves as a Claude Code plugin marketplace. Team members
| Plugin | Description |
|--------|-------------|
| `cache-components` | Expert guidance for Cache Components and PPR |
| `next-dev` | **Experimental.** Real-time Turbopack compilation feedback for agents (requires unreleased MCP tools) |
## For Team Members
......
{
"name": "next-dev",
"version": "0.1.0",
"description": "Experimental: Real-time Turbopack compilation feedback for agents editing Next.js code. Pauses compilation during edits, batches a single compile at turn-end, blocks on errors. Requires a Next.js dev server with the pause_compilation/compile_and_resume/get_compilation_issues MCP tools (Turbopack only).",
"author": {
"name": "Next.js Team",
"url": "https://nextjs.org"
},
"homepage": "https://github.com/vercel/next.js/tree/canary/.claude-plugin/plugins/next-dev",
"repository": "https://github.com/vercel/next.js",
"license": "MIT",
"keywords": [
"nextjs",
"turbopack",
"dev-server",
"mcp",
"agents",
"compilation",
"experimental"
]
}
# Next Dev Plugin for Claude Code
> ⚠️ **Experimental.** This plugin requires a Next.js dev server that exposes the `pause_compilation`, `compile_and_resume`, and `get_compilation_issues` MCP tools (Turbopack only). These tools are still landing in canary — see [Status](#status) below before installing.
Real-time Turbopack compilation feedback for agents editing Next.js code. The agent's edits no longer pile up errors silently across many tool calls — compilation is paused while editing, batched once at turn-end, and the agent is blocked from finishing if there are errors.
## Why
Agents editing Next.js code don't open a browser, so Turbopack's on-demand compilation never kicks in. Errors pile up silently and only surface at the final `pnpm build`. This plugin wires the dev server's MCP endpoint into Claude Code so that:
1. **Edits don't trigger HMR.** While the agent is working, the turbo-tasks scheduler is paused. File watchers still mark tasks dirty, but no compilation runs.
2. **One batch compile per turn.** When the agent finishes responding, the Stop hook drains buffered tasks in a single compile cycle and runs `get_compilation_issues` against the full module graph.
3. **The agent is blocked on errors.** If compilation produces errors, the Stop hook returns `decision: block` with the formatted errors, forcing the agent to fix them before stopping.
4. **Normal HMR resumes between turns.** Your browser still updates live when you're not in an agent turn.
For more architectural detail, see the design notes referenced from the Next.js Dev Agent Plugin Notion doc.
## Status
This plugin depends on MCP tools that are not yet in stable Next.js:
| MCP tool | PR | Status |
|----------|----|--------|
| `get_compilation_issues` | [vercel/next.js#92062](https://github.com/vercel/next.js/pull/92062) | Landed |
| `pause_compilation` / `compile_and_resume` | [vercel/next.js#92410](https://github.com/vercel/next.js/pull/92410) | Open |
The activation script verifies these tools are present and refuses to enable hooks otherwise. **Do not install this plugin against an unsupported Next.js version** — the activation will fail with a clear error.
## Installation
### Step 1: Add the Next.js Marketplace
```
/plugin marketplace add vercel/next.js
```
### Step 2: Install the Plugin
```
/plugin install next-dev@nextjs
```
## Usage
In your Next.js project, start the dev server with Turbopack (the default):
```bash
pnpm dev -p 3000
```
Then in Claude Code, activate the skill:
```
/next-dev 3000
```
The skill's activation script will:
1. Write the port to `.claude/port` in your project (state flag)
2. Connect to `localhost:3000/_next/mcp` and verify `get_compilation_issues` is available
3. Warm up Turbopack's module graph in the background (the first compile is the slow one)
4. Clear any stale dismissed-issues file from a previous session
If activation fails, the port file is deleted and the hooks become silent no-ops — normal editing is unaffected.
## Architecture
Two skill-scoped hooks fire while the skill is active:
- **`UserPromptSubmit`** → `hooks/enter-manual-compile.mjs`
Pings the dev server, then calls `pause_compilation`. Silent no-op if the port file is missing or the server is unreachable.
- **`Stop`** → `hooks/stop-compile-check.mjs`
Calls `compile_and_resume` (drains pending tasks in one batch), then `get_compilation_issues`. If issues are found, returns `decision: block` with the formatted errors. If `stop_hook_active` is `true`, exits 0 unconditionally to avoid infinite loops.
State files are project-local (`$CLAUDE_PROJECT_DIR/.claude/`):
- `.claude/port` — dev server port; existence is the activation flag
- `.claude/dismissed-issues.json` — issue keys the agent has dismissed as non-actionable
Hook scripts are plugin-local (`${CLAUDE_PLUGIN_ROOT}/hooks/`).
## Files
```
.claude-plugin/plugins/next-dev/
├── .claude-plugin/
│ └── plugin.json
├── hooks/
│ ├── enter-manual-compile.mjs # UserPromptSubmit: ping + pause_compilation
│ ├── stop-compile-check.mjs # Stop: compile_and_resume + get_compilation_issues
│ └── mcp-client.mjs # Shared MCP/SSE client
├── skills/
│ └── next-dev/
│ ├── SKILL.md # Skill definition + hook bindings
│ └── scripts/
│ ├── activate.mjs # /next-dev <port> entry point
│ ├── get-errors.mjs # On-demand error check
│ └── dismiss-errors.mjs # Classify + dismiss non-actionable errors
└── README.md
```
## Dismissing non-actionable errors
Large projects often have compilation errors the agent can't fix — `node_modules` resolving server-only builtins (`child_process`, `dns`, `net`, `tls`) in client context, Turbopack empty-module stubs, etc. The agent can dismiss these:
```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs"
```
Dismissals are keyed by `severity|filePath|title|startLine:startCol` (matches the server-side dedup key) and persist in `.claude/dismissed-issues.json` for the rest of the session. Activation clears them on the next session.
## Limitations
- **Turbopack only.** The MCP tools rely on the Turbopack hot-reloader; webpack is not supported.
- **Config file changes are not detected.** `get_compilation_issues` builds the module graph for all endpoints, but changes to `next.config.js`, `tsconfig.json`, etc. require a dev server restart.
- **Skill must stay active.** The hooks are scoped to the skill's lifetime. If the skill isn't loaded, normal editing works without compilation feedback.
#!/usr/bin/env node
/**
* UserPromptSubmit hook (skill-scoped). At the start of each agent turn:
* 1. Checks the dev server is reachable (precondition gate)
* 2. Pauses compilation so intermediate edits don't trigger HMR
*
* Silent no-op if the port file is missing or the server is unreachable.
* If the server goes down mid-session, the agent simply loses compilation
* feedback for that turn — the Stop hook exits 0 gracefully.
*/
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { getPort, ping, pauseCompilation } from './mcp-client.mjs'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd()
const portFile = join(projectDir, '.claude', 'port')
if (!existsSync(portFile)) {
process.exit(0)
}
try {
const port = getPort()
const reachable = await ping(port)
if (!reachable) {
process.exit(0)
}
await pauseCompilation(port)
} catch {
// Server unreachable — silent no-op. Stop hook handles gracefully.
}
/**
* Shared MCP client utilities for hooks.
* Handles the SSE-based JSON-RPC protocol used by Next.js MCP endpoint.
*/
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { join } from 'node:path'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd()
const dismissedFile = join(projectDir, '.claude', 'dismissed-issues.json')
export function getPort() {
return readFileSync(join(projectDir, '.claude', 'port'), 'utf8').trim()
}
/**
* Stable key for deduplicating/matching issues.
* Matches the server-side dedup format: severity|filePath|title|startLine:startCol
*/
export function issueKey(issue) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || ''
const line = issue.source?.range?.start?.line ?? '?'
const col = issue.source?.range?.start?.column ?? '?'
return `${severity}|${file}|${title}|${line}:${col}`
}
/**
* Write dismissed issue keys. Called by dismiss-errors.mjs.
*/
export function writeDismissed(keys) {
writeFileSync(dismissedFile, JSON.stringify({ keys }), 'utf8')
}
/**
* Read dismissed keys. Returns a Set, or null if no dismissals exist.
*/
export function readDismissedKeys() {
if (!existsSync(dismissedFile)) return null
try {
const { keys } = JSON.parse(readFileSync(dismissedFile, 'utf8'))
return new Set(keys)
} catch {
return null
}
}
/**
* Filter out dismissed issues. Returns { issues, dismissedCount }.
* If no dismissals exist, returns all issues with dismissedCount 0.
*/
export function filterDismissedIssues(issues) {
const dismissed = readDismissedKeys()
if (!dismissed) return { issues, dismissedCount: 0 }
const kept = issues.filter((i) => !dismissed.has(issueKey(i)))
return { issues: kept, dismissedCount: issues.length - kept.length }
}
export function getMcpUrl(port) {
return `http://localhost:${port}/_next/mcp`
}
const MCP_HEADERS = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
}
function parseSSE(text) {
for (const line of text.split('\n')) {
if (line.startsWith('data:')) {
return JSON.parse(line.slice(5))
}
}
return null
}
/**
* Ping the MCP endpoint. Returns true if reachable, false otherwise.
*/
export async function ping(port) {
const url = getMcpUrl(port)
try {
const res = await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agent-mode-hook', version: '1.0.0' },
},
}),
})
return res.ok
} catch {
return false
}
}
/**
* Call pause_compilation via the MCP protocol.
* Pauses compilation until compile_and_resume is called.
*/
export async function pauseCompilation(port) {
const url = getMcpUrl(port)
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agent-mode-hook', version: '1.0.0' },
},
}),
})
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
})
const res = await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: { name: 'pause_compilation', arguments: {} },
}),
})
const body = parseSSE(await res.text())
if (body?.error) {
throw new Error(body.error.message)
}
const text = body?.result?.content?.[0]?.text
if (!text) {
throw new Error('Unexpected MCP response shape')
}
return JSON.parse(text)
}
/**
* Call compile_and_resume via the MCP protocol.
* Compiles all pending changes, then resumes normal compilation.
*/
export async function compileAndResume(port) {
const url = getMcpUrl(port)
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agent-mode-hook', version: '1.0.0' },
},
}),
})
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
})
const res = await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: { name: 'compile_and_resume', arguments: {} },
}),
})
const body = parseSSE(await res.text())
if (body?.error) {
throw new Error(body.error.message)
}
const text = body?.result?.content?.[0]?.text
if (!text) {
throw new Error('Unexpected MCP response shape')
}
return JSON.parse(text)
}
/**
* Call get_compilation_issues via the MCP protocol.
* Returns the parsed result object { issues: [], diagnostics: [] }.
*/
export async function getCompilationIssues(port) {
const url = getMcpUrl(port)
// Initialize
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agent-mode-hook', version: '1.0.0' },
},
}),
})
// Initialized notification
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
})
// Call tool
const res = await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: { name: 'get_compilation_issues', arguments: {} },
}),
})
const body = parseSSE(await res.text())
if (body?.error) {
throw new Error(body.error.message)
}
// The result is a JSON string inside content[0].text
const text = body?.result?.content?.[0]?.text
if (!text) {
throw new Error('Unexpected MCP response shape')
}
return JSON.parse(text)
}
#!/usr/bin/env node
/**
* Stop hook (skill-scoped). Runs a compilation pass, then blocks if there
* are compilation errors. The agent must fix them or dismiss them to proceed.
*/
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import {
getPort,
getCompilationIssues,
compileAndResume,
filterDismissedIssues,
} from './mcp-client.mjs'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd()
const portFile = join(projectDir, '.claude', 'port')
// No port file = setup didn't complete or skill not fully active.
if (!existsSync(portFile)) {
process.exit(0)
}
try {
const port = getPort()
// Run a compilation pass before checking for errors.
// This processes all accumulated file changes in one batch.
try {
await compileAndResume(port)
} catch {
// If compile fails, continue with error check anyway.
}
const result = await getCompilationIssues(port)
const allIssues = result.issues || []
const { issues, dismissedCount } = filterDismissedIssues(allIssues)
if (issues.length === 0) {
process.exit(0)
}
const lines =
dismissedCount > 0
? [`Compilation errors found (${dismissedCount} dismissed hidden):`, '']
: ['Compilation errors found:', '']
for (const issue of issues) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || 'Unknown error'
let line = `[${severity}] ${file}: ${title}`
if (issue.description) line += ` — ${issue.description}`
if (issue.source?.range) {
const r = issue.source.range
line += ` (line ${r.start?.line ?? '?'}:${r.start?.column ?? '?'})`
}
lines.push(line)
if (issue.detail) {
lines.push(issue.detail.trim())
}
if (issue.codeFrame) {
lines.push(issue.codeFrame)
}
lines.push('')
}
lines.push(
`${issues.length} issue(s). Fix them or dismiss non-actionable ones with: node "./scripts/dismiss-errors.mjs"`
)
const output = {
decision: 'block',
reason: lines.join('\n'),
}
process.stdout.write(JSON.stringify(output))
process.exit(0)
} catch (err) {
// Server unreachable — don't block the agent from stopping.
process.exit(0)
}
---
name: next-dev
description: "Connect to Next.js dev server for real-time compilation feedback on every edit"
argument-hint: "[port]"
hooks:
UserPromptSubmit:
- hooks:
- type: command
command: 'node "${CLAUDE_PLUGIN_ROOT}/hooks/enter-manual-compile.mjs"'
timeout: 10
Stop:
- hooks:
- type: command
command: 'node "${CLAUDE_PLUGIN_ROOT}/hooks/stop-compile-check.mjs"'
timeout: 120
---
# Next Dev
> **Experimental.** Requires a Next.js dev server that exposes the `pause_compilation`, `compile_and_resume`, and `get_compilation_issues` MCP tools (Turbopack only). These are not yet available in stable Next.js — see the plugin README for status.
Connects to the Next.js dev server MCP endpoint for compilation feedback.
## Setup
```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/activate.mjs" $ARGUMENTS
```
If it fails (non-zero exit), tell the user the error from stderr and offer to retry. Do not edit files until activation succeeds.
**After activation, tell the user:**
> The dev server is now connected. During each of my turns, automatic recompilation is paused so intermediate edits don't cause errors. When I finish a response, I compile everything in one batch and normal HMR resumes — so between my turns, your browser updates live as usual. To fully disconnect, restart the dev server.
## How it works
Two hooks run while this skill is active:
- **UserPromptSubmit**: Checks the dev server is reachable, then pauses compilation for the turn. If the server is down, silently skips — you lose feedback for that turn but aren't blocked.
- **Stop**: Compiles all pending changes in one batch and exits manual mode (normal HMR resumes). **Blocks you from finishing if there are compilation errors.** Fix them before trying again.
## Noisy / non-actionable errors
If the stop hook blocks you with errors that aren't yours (node_modules, Turbopack stubs, etc.), dismiss them:
```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs"
```
Hides non-actionable errors from all future checks for the rest of the session. Dismissals reset on next activation. To clear manually:
```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs" --reset
```
## On-demand error check
Check compilation errors mid-task without waiting for the stop hook:
```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/get-errors.mjs"
```
Compiles pending changes and returns current errors (respects dismissals).
#!/usr/bin/env node
/**
* Activates agent-mode: writes the port file, then verifies the MCP endpoint
* has the get_compilation_issues tool. Cleans up the port file on failure
* so hooks know setup didn't complete.
*/
import { writeFileSync, unlinkSync, existsSync } from 'node:fs'
import { join } from 'node:path'
const port = process.argv[2] || '3000'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd()
const portFile = join(projectDir, '.claude', 'port')
const dismissedFile = join(projectDir, '.claude', 'dismissed-issues.json')
const url = `http://localhost:${port}/_next/mcp`
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
}
function parseSSE(text) {
for (const line of text.split('\n')) {
if (line.startsWith('data:')) {
return JSON.parse(line.slice(5))
}
}
return null
}
function fail(message) {
console.error(message)
try {
unlinkSync(portFile)
} catch {}
process.exit(1)
}
// Step 1: Write port, clear stale dismissals from previous session
writeFileSync(portFile, port, 'utf8')
try {
if (existsSync(dismissedFile)) unlinkSync(dismissedFile)
} catch {}
console.log(`Port ${port} written to ${portFile}`)
// Step 2: Verify MCP endpoint
try {
const initRes = await fetch(url, {
method: 'POST',
headers,
signal: AbortSignal.timeout(5000),
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agent-mode-activate', version: '1.0.0' },
},
}),
})
if (!initRes.ok) {
fail(
`MCP endpoint returned ${initRes.status}. Is the dev server running on port ${port}?`
)
}
// Send initialized notification
await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
})
// List tools
const listRes = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/list',
}),
})
const listBody = parseSSE(await listRes.text())
const tools = listBody?.result?.tools?.map((t) => t.name) || []
if (!tools.includes('get_compilation_issues')) {
fail(
`MCP endpoint is reachable but missing "get_compilation_issues" tool.\n` +
`Available tools: ${tools.join(', ')}\n` +
`This requires Turbopack. Start the dev server with: pnpm dev --turbopack`
)
}
console.log(`Verified. Available tools: ${tools.join(', ')}`)
// Step 3: Warm up by calling get_compilation_issues in the background.
// The first call builds module graphs for all routes and can take minutes
// on large projects. Fire-and-forget so the agent can start working
// immediately. Turbo-tasks deduplicates — the stop hook's first call
// will join the same in-flight computation rather than starting a new one.
console.log(
'Warming up Turbopack cache in the background (first stop hook may be slow if not ready)...'
)
fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({
jsonrpc: '2.0',
id: 3,
method: 'tools/call',
params: { name: 'get_compilation_issues', arguments: {} },
}),
})
.then(async (res) => {
const body = parseSSE(await res.text())
const issuesText = body?.result?.content?.[0]?.text
if (issuesText) {
const { issues } = JSON.parse(issuesText)
if (issues?.length) {
console.log(
`Background warm-up done: ${issues.length} issue(s) found.`
)
} else {
console.log('Background warm-up done: no issues found.')
}
}
})
.catch(() => {
// Warm-up failed silently — stop hook will handle it.
})
// Manual compile mode is entered per-turn by the UserPromptSubmit hook,
// not here. This keeps normal HMR active between agent turns.
} catch (err) {
if (err.name === 'TimeoutError') {
fail(
`MCP endpoint at ${url} timed out. Is the dev server running on port ${port}?`
)
}
fail(
`Cannot reach MCP endpoint at ${url}: ${err.message}\n` +
`Make sure the dev server is running: pnpm dev --turbopack -p ${port}`
)
}
#!/usr/bin/env node
/**
* Classifies compilation errors as actionable or non-actionable and dismisses
* the non-actionable ones. Dismissed errors are filtered from future checks
* (stop hook + get-errors) for the rest of the session.
*
* Heuristics for non-actionable:
* - File is in node_modules/ (third-party dependency, agent can't fix)
* - Error references turbopack/empty.js (bundler stub for server-only modules)
*
* Usage: node dismiss-errors.mjs [port]
* --reset Clear all dismissals
*/
import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
const MCP_HEADERS = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
}
function parseSSE(text) {
for (const line of text.split('\n')) {
if (line.startsWith('data:')) {
return JSON.parse(line.slice(5))
}
}
return null
}
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd()
const dismissedFile = join(projectDir, '.claude', 'dismissed-issues.json')
function getPort() {
return readFileSync(join(projectDir, '.claude', 'port'), 'utf8').trim()
}
function getMcpUrl(port) {
return `http://localhost:${port}/_next/mcp`
}
function issueKey(issue) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || ''
const line = issue.source?.range?.start?.line ?? '?'
const col = issue.source?.range?.start?.column ?? '?'
return `${severity}|${file}|${title}|${line}:${col}`
}
/**
* Classify an issue as non-actionable if the agent can't fix it.
*/
function isNonActionable(issue) {
const file = issue.filePath || ''
const description = issue.description || ''
const detail = issue.detail || ''
const title = issue.title || ''
const text = `${title} ${description} ${detail}`
// Third-party dependency — agent can't edit node_modules
if (file.includes('/node_modules/')) return 'node_modules'
// Turbopack empty module stub — bundler replaces server-only modules with
// an empty shim in client bundles, causing "export not found" errors.
// Not a real code issue; the source file is correct.
if (text.includes('turbopack/empty.js')) return 'turbopack-stub'
return null
}
async function mcpCall(port, id, method, params) {
const url = getMcpUrl(port)
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'dismiss-errors', version: '1.0.0' },
},
}),
})
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
})
const res = await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
})
const body = parseSSE(await res.text())
if (body?.error) throw new Error(body.error.message)
const text = body?.result?.content?.[0]?.text
if (!text) throw new Error('Unexpected MCP response shape')
return JSON.parse(text)
}
// Handle --reset flag
if (process.argv.includes('--reset')) {
try {
if (existsSync(dismissedFile)) {
unlinkSync(dismissedFile)
console.log('Dismissed issues cleared.')
} else {
console.log('No dismissed issues to clear.')
}
} catch (err) {
console.error(`Failed to clear dismissals: ${err.message}`)
process.exit(1)
}
process.exit(0)
}
const port = process.argv[2] || getPort()
try {
// Compile first to flush pending changes.
try {
await mcpCall(port, 2, 'tools/call', {
name: 'compile_and_resume',
arguments: {},
})
} catch {}
const result = await mcpCall(port, 3, 'tools/call', {
name: 'get_compilation_issues',
arguments: {},
})
const allIssues = result.issues || []
if (allIssues.length === 0) {
console.log('No compilation errors to classify.')
process.exit(0)
}
// Load existing dismissals so we can merge
let existingKeys = []
if (existsSync(dismissedFile)) {
try {
existingKeys = JSON.parse(readFileSync(dismissedFile, 'utf8')).keys || []
} catch {}
}
const dismissedSet = new Set(existingKeys)
const actionable = []
const dismissed = []
for (const issue of allIssues) {
const reason = isNonActionable(issue)
if (reason) {
dismissed.push({ issue, reason })
dismissedSet.add(issueKey(issue))
} else {
actionable.push(issue)
}
}
// Write merged dismissals
if (dismissedSet.size > 0) {
writeFileSync(
dismissedFile,
JSON.stringify({ keys: [...dismissedSet] }),
'utf8'
)
}
// Report dismissed
if (dismissed.length > 0) {
const byReason = {}
for (const { reason } of dismissed) {
byReason[reason] = (byReason[reason] || 0) + 1
}
const summary = Object.entries(byReason)
.map(([reason, count]) => `${count} ${reason}`)
.join(', ')
console.log(
`Dismissed ${dismissed.length} non-actionable error(s): ${summary}.`
)
}
// Report actionable
if (actionable.length === 0) {
console.log('No actionable errors remain.')
process.exit(0)
}
console.log(`\n${actionable.length} actionable error(s):\n`)
for (const issue of actionable) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || 'Unknown error'
let line = `[${severity}] ${file}: ${title}`
if (issue.description) line += ` — ${issue.description}`
if (issue.source?.range) {
const r = issue.source.range
line += ` (line ${r.start?.line ?? '?'}:${r.start?.column ?? '?'})`
}
console.log(line)
if (issue.detail) console.log(issue.detail.trim())
if (issue.codeFrame) console.log(issue.codeFrame)
console.log()
}
} catch (err) {
console.error(`Cannot reach dev server on port ${port}: ${err.message}`)
process.exit(1)
}
#!/usr/bin/env node
/**
* Returns current compilation errors from the Next.js dev server.
*
* Usage: node get-errors.mjs [port]
*/
import { readFileSync, existsSync } from 'node:fs'
import { join } from 'node:path'
const MCP_HEADERS = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
}
function parseSSE(text) {
for (const line of text.split('\n')) {
if (line.startsWith('data:')) {
return JSON.parse(line.slice(5))
}
}
return null
}
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd()
function getPort() {
return readFileSync(join(projectDir, '.claude', 'port'), 'utf8').trim()
}
function issueKey(issue) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || ''
const line = issue.source?.range?.start?.line ?? '?'
const col = issue.source?.range?.start?.column ?? '?'
return `${severity}|${file}|${title}|${line}:${col}`
}
function filterDismissedIssues(issues) {
const dismissedFile = join(projectDir, '.claude', 'dismissed-issues.json')
if (!existsSync(dismissedFile)) return { issues, dismissedCount: 0 }
try {
const { keys } = JSON.parse(readFileSync(dismissedFile, 'utf8'))
const dismissed = new Set(keys)
const kept = issues.filter((i) => !dismissed.has(issueKey(i)))
return { issues: kept, dismissedCount: issues.length - kept.length }
} catch {
return { issues, dismissedCount: 0 }
}
}
function getMcpUrl(port) {
return `http://localhost:${port}/_next/mcp`
}
async function mcpCall(port, id, method, params) {
const url = getMcpUrl(port)
// Initialize
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'get-errors', version: '1.0.0' },
},
}),
})
await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
})
const res = await fetch(url, {
method: 'POST',
headers: MCP_HEADERS,
body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
})
const body = parseSSE(await res.text())
if (body?.error) throw new Error(body.error.message)
const text = body?.result?.content?.[0]?.text
if (!text) throw new Error('Unexpected MCP response shape')
return JSON.parse(text)
}
const port = process.argv[2] || getPort()
try {
// Compile first to flush pending changes.
try {
await mcpCall(port, 2, 'tools/call', {
name: 'compile_and_resume',
arguments: {},
})
} catch {}
const result = await mcpCall(port, 3, 'tools/call', {
name: 'get_compilation_issues',
arguments: {},
})
const allIssues = result.issues || []
const { issues, dismissedCount } = filterDismissedIssues(allIssues)
if (issues.length === 0) {
if (dismissedCount > 0) {
console.log(`No compilation errors (${dismissedCount} dismissed hidden).`)
} else {
console.log('No compilation errors.')
}
process.exit(0)
}
for (const issue of issues) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || 'Unknown error'
let line = `[${severity}] ${file}: ${title}`
if (issue.description) line += ` — ${issue.description}`
if (issue.source?.range) {
const r = issue.source.range
line += ` (line ${r.start?.line ?? '?'}:${r.start?.column ?? '?'})`
}
console.log(line)
if (issue.detail) console.log(issue.detail.trim())
if (issue.codeFrame) console.log(issue.codeFrame)
console.log()
}
if (dismissedCount > 0) {
console.log(
`${issues.length} issue(s) found (${dismissedCount} dismissed hidden).`
)
} else {
console.log(`${issues.length} issue(s) found.`)
}
} catch (err) {
console.error(`Cannot reach dev server on port ${port}: ${err.message}`)
process.exit(1)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment