Unverified Commit 41839289 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Add MCP `get_compilation_issues` tool and NAPI method (#92062)

### What?

Adds a new \`get_compilation_issues\` MCP tool (and the underlying
\`projectGetAllCompilationIssues\` NAPI method) that returns all
compilation issues from all routes in a single call.

**New files:**
- \`crates/next-napi-bindings/src/next_api/project.rs\` —
\`project_get_all_compilation_issues\` NAPI function +
\`get_all_compilation_issues_operation\` /
\`get_all_compilation_issues_inner_operation\` turbo-tasks operations
- \`packages/next/src/server/mcp/tools/get-compilation-issues.ts\` — MCP
tool implementation
-
\`packages/next/src/server/mcp/tools/utils/format-compilation-issues.ts\`
— output formatter
-
\`test/development/mcp-server/mcp-server-get-compilation-issues.test.ts\`
— e2e test
- \`test/development/mcp-server/fixtures/compilation-errors-app/\` —
fixture app with three routes (valid page, missing-module error, syntax
error)

**Modified files:**
- \`packages/next/src/build/swc/generated-native.d.ts\` + \`types.ts\` +
\`index.ts\` — expose the new NAPI method
- \`packages/next/src/server/mcp/get-or-create-mcp-server.ts\` —
register the new tool, accept \`getTurbopackProject\` option
- \`packages/next/src/server/dev/hot-reloader-turbopack.ts\` — pass
\`project\` to MCP middleware
- \`packages/next/src/telemetry/events/build.ts\` — add
\`'mcp/get_compilation_issues'\` to the \`McpToolName\` union

### Why?

The existing MCP tools require a browser session (and thus a specific
route to be rendered) to surface compilation errors.
\`get_compilation_issues\` works without a browser session and covers
all routes proactively — useful for AI coding agents that want to check
for errors across the whole app before trying to render a page.

### How?

**NAPI layer:**  
\`project_get_all_compilation_issues\` calls a two-level turbo-tasks
operation pair:

1. \`get_all_compilation_issues_inner_operation\` — iterates all
endpoint groups via \`project.get_all_endpoint_groups(false)\` and calls
\`endpoint_group.module_graphs().as_side_effect()\` on each. This builds
the module graph (resolution + transformation) for every entrypoint
without chunking, emitting, or code generation. Issues are emitted as
turbo-tasks collectables.

2. \`get_all_compilation_issues_operation\` — wraps the inner op in
\`strongly_consistent_catch_collectables\` to harvest
issues/diagnostics/effects, then returns an \`OperationResult\`.

> **Why not \`project.whole_app_module_graphs()\`?**  
> \`whole_app_module_graphs()\` calls \`drop_issues()\` in development
mode to prevent every per-route HMR subscription from seeing all global
issues. Calling it here would return zero issues in dev. Per-endpoint
\`module_graphs()\` calls don't have this suppression.

**Output formatting (\`format-compilation-issues.ts\`):**  
The raw Turbopack wire types are transformed before being returned to
MCP consumers:

- **StyledString → plain string**: \`title\`, \`description\`, and
\`detail\` are \`StyledString\` union trees (recursive \`{type, value}\`
objects). These are flattened to plain strings —
\`text\`/\`code\`/\`strong\` variants return their \`.value\` directly,
\`line\` joins with \`""\`, \`stack\` joins with \`"\n"\`.
- **ANSI codes stripped**: \`codeFrame\` is a pre-rendered string from
the Rust NAPI layer that contains ANSI terminal colour codes. These are
stripped via \`next/dist/compiled/strip-ansi\`.
- **1-indexed source positions**: Turbopack's \`SourcePos\` is 0-indexed
for both \`line\` and \`column\`. The formatter adds \`+1\` to each so
consumers get the conventional editor-style 1-indexed values.
- **Deduplication**: the same issue can surface from multiple endpoints
during the module graph traversal. Issues are deduplicated by a
\`severity|filePath|title|startLine:startCol\` key.
- **No diagnostics**: Turbopack diagnostics are internal telemetry
(\`EVENT_BUILD_FEATURE_USAGE\` feature-adoption counters). They are not
actionable for the user, so the \`diagnostics\` field is omitted
entirely from the response.

**MCP tool (\`get_compilation_issues\`):**  
Calls \`project.getAllCompilationIssues()\`, passes the issues through
\`formatCompilationIssues()\`, and returns \`{ issues: FormattedIssue[]
}\` as JSON. Works without a browser session.

**Test:**  
A fixture app with three routes (valid \`app/page.tsx\`,
\`app/missing-module/page.tsx\` importing a non-existent package,
\`app/syntax-error/page.tsx\` with unclosed JSX) is used to verify:
1. The tool returns a result without any browser session
2. Module-not-found errors are detected
3. Syntax errors are detected
4. Issues include \`severity\`, \`title\`, \`filePath\` metadata — all
as plain strings (not StyledString objects)

e2e tests: added —
\`test/development/mcp-server/mcp-server-get-compilation-issues.test.ts\`

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent be3ee02b
......@@ -47,6 +47,7 @@ export default globalIgnores([
'examples/with-typescript-graphql/lib/gql/',
'test/development/basic/hmr/components/parse-error.js',
'test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx',
'test/development/mcp-server/fixtures/compilation-errors-app/app/syntax-error/page.tsx',
'test/production/debug-build-path/fixtures/with-compile-error/app/broken/page.tsx',
'packages/next-swc/native/index.d.ts',
'packages/next-swc/docs/assets/**/*',
......
......@@ -59,6 +59,7 @@ test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/ignored.js
test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/sourcemapped.js
test/e2e/app-dir/server-source-maps/fixtures/default/external-pkg/sourcemapped.js
test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx
test/development/mcp-server/fixtures/compilation-errors-app/app/syntax-error/page.tsx
# Tested against auto-generated content that isn't formatted
test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts
......
......@@ -2508,6 +2508,74 @@ pub async fn project_write_analyze_data(
})
}
#[turbo_tasks::function(operation)]
async fn get_all_compilation_issues_inner_operation(
container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<()>> {
let project = container.project();
// Build the module graph for every endpoint without chunking, code gen, or disk emission.
// We iterate endpoints rather than calling project.whole_app_module_graphs() because the
// latter calls drop_issues() in development mode (to avoid duplicate per-route HMR noise).
// Per-endpoint module_graphs() calls are not subject to that suppression, so issues like
// missing modules and transform errors are properly collected as collectables here.
let endpoint_groups = project.get_all_endpoint_groups(false).await?;
endpoint_groups
.iter()
.map(|(_, endpoint_group)| async move {
endpoint_group.module_graphs().as_side_effect().await
})
.try_join()
.await?;
Ok(Vc::cell(()))
}
#[turbo_tasks::function(operation)]
async fn get_all_compilation_issues_operation(
container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<OperationResult>> {
let inner_op = get_all_compilation_issues_inner_operation(container);
let filter = issue_filter_from_container(container);
let (_, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(inner_op, filter).await?;
Ok(OperationResult {
issues,
diagnostics,
effects,
}
.cell())
}
#[tracing::instrument(level = "info", name = "get all compilation issues", skip_all)]
#[napi]
pub async fn project_get_all_compilation_issues(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) -> napi::Result<TurbopackResult<()>> {
let container = project.container;
let (issues, diagnostics) = project
.turbopack_ctx
.turbo_tasks()
.run_once(async move {
let op = get_all_compilation_issues_operation(container);
let OperationResult {
issues,
diagnostics,
effects: _,
} = &*op.read_strongly_consistent().await?;
Ok((issues.clone(), diagnostics.clone()))
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(TurbopackResult {
result: (),
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
diagnostics: diagnostics
.iter()
.map(|d| NapiDiagnostic::from(d))
.collect(),
})
}
/// Opens the Turbopack persistent cache database at the given path and performs a full compaction.
///
/// The `path` should point to the `<distDir>/cache/turbopack` directory.
......
......@@ -491,6 +491,9 @@ export declare function projectWriteAnalyzeData(
project: { __napiType: 'Project' },
appDirOnly: boolean
): Promise<TurbopackResult>
export declare function projectGetAllCompilationIssues(project: {
__napiType: 'Project'
}): Promise<TurbopackResult>
/**
* Opens the Turbopack persistent cache database at the given path and performs a full compaction.
*
......
......@@ -708,6 +708,13 @@ function bindingToApi(
return napiResult
}
async getAllCompilationIssues(): Promise<TurbopackResult<void>> {
const napiResult = (await binding.projectGetAllCompilationIssues(
this._nativeProject
)) as TurbopackResult<void>
return napiResult
}
async writeAllEntrypointsToDisk(
appDirOnly: boolean
): Promise<TurbopackResult<Partial<RawEntrypoints>>> {
......
......@@ -290,6 +290,8 @@ export interface Project {
writeAnalyzeData(appDirOnly: boolean): Promise<TurbopackResult<void>>
getAllCompilationIssues(): Promise<TurbopackResult<void>>
writeAllEntrypointsToDisk(
appDirOnly: boolean
): Promise<TurbopackResult<Partial<RawEntrypoints>>>
......
......@@ -1049,6 +1049,7 @@ export async function createHotReloaderTurbopack(
getActiveConnectionCount: () =>
clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,
getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN,
getTurbopackProject: () => project,
}),
]
: []),
......
......@@ -5,8 +5,10 @@ import { registerGetPageMetadataTool } from './tools/get-page-metadata'
import { registerGetLogsTool } from './tools/get-logs'
import { registerGetActionByIdTool } from './tools/get-server-action-by-id'
import { registerGetRoutesTool } from './tools/get-routes'
import { registerGetCompilationIssuesTool } from './tools/get-compilation-issues'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
import type { NextConfigComplete } from '../config-shared'
import type { Project } from '../../build/swc/types'
export interface McpServerOptions {
projectPath: string
......@@ -17,6 +19,7 @@ export interface McpServerOptions {
sendHmrMessage: (message: HmrMessageSentToBrowser) => void
getActiveConnectionCount: () => number
getDevServerUrl: () => string | undefined
getTurbopackProject?: () => Project | undefined
}
let mcpServer: McpServer | undefined
......@@ -55,5 +58,9 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
appDir: options.appDir,
})
if (options.getTurbopackProject) {
registerGetCompilationIssuesTool(mcpServer, options.getTurbopackProject)
}
return mcpServer
}
/**
* MCP tool for getting compilation issues from all routes via Turbopack.
*
* Unlike get_errors (which requires a browser session and reflects the runtime
* error overlay), this tool builds the module graph for every endpoint and
* collects Turbopack issues directly — no browser needed. Covers
* module-not-found, syntax errors, and other transform failures across all
* routes.
*/
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import type { Project } from '../../../build/swc/types'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
import { formatCompilationIssues } from './utils/format-compilation-issues'
export function registerGetCompilationIssuesTool(
server: McpServer,
getProject: () => Project | undefined
) {
server.registerTool(
'get_compilation_issues',
{
description:
'Build the module graph for all routes and return all compilation issues (resolve errors, missing modules, transform errors, etc.). Does not require a browser session. Covers all routes proactively.',
inputSchema: {},
},
async () => {
mcpTelemetryTracker.recordToolCall('mcp/get_compilation_issues')
try {
const project = getProject()
if (!project) {
return {
content: [
{
type: 'text',
text: JSON.stringify({
error:
'Turbopack project is not available. This tool requires the Turbopack bundler.',
}),
},
],
}
}
const { issues } = await project.getAllCompilationIssues()
const formattedIssues = formatCompilationIssues(issues)
return {
content: [
{
type: 'text',
text: JSON.stringify({ issues: formattedIssues }),
},
],
}
} catch (error) {
return {
content: [
{
type: 'text',
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
}
}
)
}
import type { Issue, StyledString } from '../../../../build/swc/types'
import stripAnsi from 'next/dist/compiled/strip-ansi'
/** Convert a StyledString tree to Markdown. */
function styledStringToMarkdown(s: StyledString): string {
switch (s.type) {
case 'text':
return s.value
case 'code':
return `\`${s.value}\``
case 'strong':
return `**${s.value}**`
case 'line':
return s.value.map(styledStringToMarkdown).join('')
case 'stack':
return s.value.map(styledStringToMarkdown).join('\n')
default:
return ''
}
}
export interface FormattedIssue {
severity: string
filePath: string
title: string
description?: string
detail?: string
source?: {
filePath: string
range?: {
/** 1-indexed */
start: { line: number; column: number }
/** 1-indexed */
end: { line: number; column: number }
}
}
/** Code frame with ANSI codes stripped */
codeFrame?: string
}
/**
* Transform raw Turbopack issues into a clean format for MCP consumers:
* - Converts StyledString trees (title/description/detail) to Markdown
* - Strips ANSI codes from code frames
* - Converts 0-indexed source positions to 1-indexed
* - Deduplicates issues (same error can surface from multiple endpoints)
*/
export function formatCompilationIssues(issues: Issue[]): FormattedIssue[] {
const seen = new Set<string>()
const formattedIssues: FormattedIssue[] = []
for (const issue of issues) {
const title = styledStringToMarkdown(issue.title)
// Include source position in the key so two distinct errors in the same
// file with the same message are not collapsed into one.
const startLine = issue.source?.range?.start.line ?? ''
const startCol = issue.source?.range?.start.column ?? ''
const key = `${issue.severity}|${issue.filePath}|${title}|${startLine}:${startCol}`
if (seen.has(key)) continue
seen.add(key)
const { range } = issue.source ?? {}
formattedIssues.push({
severity: issue.severity,
filePath: issue.filePath,
title,
description: issue.description
? styledStringToMarkdown(issue.description)
: undefined,
detail: issue.detail ? styledStringToMarkdown(issue.detail) : undefined,
source: issue.source
? {
filePath: issue.source.source.filePath,
range: range
? {
start: {
line: range.start.line + 1,
column: range.start.column + 1,
},
end: {
line: range.end.line + 1,
column: range.end.column + 1,
},
}
: undefined,
}
: undefined,
codeFrame: issue.codeFrame ? stripAnsi(issue.codeFrame) : undefined,
})
}
return formattedIssues
}
......@@ -259,6 +259,7 @@ export type McpToolName =
| 'mcp/get_project_metadata'
| 'mcp/get_routes'
| 'mcp/get_server_action_by_id'
| 'mcp/get_compilation_issues'
export type EventMcpToolUsage = {
toolName: McpToolName
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import { something } from './non-existent-module'
export default function MissingModulePage() {
return <div>{something}</div>
}
export default function HomePage() {
return <div>Home Page - No Errors</div>
}
export default function SyntaxErrorPage() {
return <div>Broken JSX
}
module.exports = {
experimental: {
mcpServer: true,
},
}
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
// get_compilation_issues is a Turbopack-only feature (requires NAPI project handle)
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'mcp-server get_compilation_issues tool',
() => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'compilation-errors-app'),
skipDeployment: true,
})
if (skipped) {
return
}
async function callMcpTool() {
const response = await fetch(`${next.url}/_next/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'get-compilation-issues',
method: 'tools/call',
params: { name: 'get_compilation_issues', arguments: {} },
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
expect(match).toBeTruthy()
const result = JSON.parse(match![1])
return JSON.parse(result.result?.content?.[0]?.text)
}
type Issue = { severity: string; filePath: string; title: string }
let compilationResult: { issues: Issue[] }
beforeAll(async () => {
compilationResult = await callMcpTool()
})
function errorIssues() {
return compilationResult.issues.filter(
(issue) => issue.severity === 'error' || issue.severity === 'fatal'
)
}
it('should return compilation issues without requiring a browser session', () => {
expect(compilationResult).toHaveProperty('issues')
expect(Array.isArray(compilationResult.issues)).toBe(true)
})
it('should detect module-not-found errors', () => {
const errors = errorIssues()
expect(errors.length).toBeGreaterThan(0)
const moduleNotFoundIssue = errors.find(
(issue) =>
issue.filePath.includes('missing-module') ||
issue.title.includes('non-existent-module')
)
expect(moduleNotFoundIssue).toBeDefined()
})
it('should detect syntax errors', () => {
const errors = errorIssues()
const syntaxErrorIssue = errors.find((issue) =>
issue.filePath.includes('syntax-error')
)
expect(syntaxErrorIssue).toBeDefined()
})
it('should include issue metadata fields', () => {
const errors = errorIssues()
expect(errors.length).toBeGreaterThan(0)
const issue = errors[0]
expect(issue).toHaveProperty('severity')
expect(issue).toHaveProperty('filePath')
expect(issue).toHaveProperty('title')
expect(typeof issue.severity).toBe('string')
expect(typeof issue.filePath).toBe('string')
// title must be a plain string, not a StyledString object
expect(typeof issue.title).toBe('string')
})
}
)
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