Commit 3265e4d5 authored by Tobias Koppers's avatar Tobias Koppers

Add MCP `get_compilation_issues` tool for Turbopack issues

Exposes a new MCP tool that returns fresh Turbopack compilation issues
(all severities) as JSON grouped by route. Adds a Rust NAPI method
`endpoint_get_issues` that peeks issues from an endpoint without side
effects, and wires it through the TypeScript Endpoint interface to the
new MCP tool. Issues are fetched for all routes that have been compiled
in the current dev session (tracked via `currentWrittenEntrypoints`).
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 56993a6c
...@@ -47,6 +47,7 @@ export default globalIgnores([ ...@@ -47,6 +47,7 @@ export default globalIgnores([
'examples/with-typescript-graphql/lib/gql/', 'examples/with-typescript-graphql/lib/gql/',
'test/development/basic/hmr/components/parse-error.js', '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/default-template/app/build-error/page.tsx',
'test/development/mcp-server/fixtures/compilation-issues-app/app/broken/page.tsx',
'test/production/debug-build-path/fixtures/with-compile-error/app/broken/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/native/index.d.ts',
'packages/next-swc/docs/assets/**/*', 'packages/next-swc/docs/assets/**/*',
......
...@@ -59,6 +59,7 @@ test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/ignored.js ...@@ -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/internal-pkg/sourcemapped.js
test/e2e/app-dir/server-source-maps/fixtures/default/external-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/default-template/app/build-error/page.tsx
test/development/mcp-server/fixtures/compilation-issues-app/app/broken/page.tsx
# Tested against auto-generated content that isn't formatted # Tested against auto-generated content that isn't formatted
test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts
......
...@@ -20,7 +20,7 @@ use turbopack_core::{ ...@@ -20,7 +20,7 @@ use turbopack_core::{
}; };
use crate::next_api::utils::{ use crate::next_api::utils::{
DetachedVc, NapiDiagnostic, NapiIssue, RootTask, TurbopackResult, DetachedVc, NapiDiagnostic, NapiIssue, RootTask, TurbopackResult, get_diagnostics, get_issues,
strongly_consistent_catch_collectables, subscribe, strongly_consistent_catch_collectables, subscribe,
}; };
...@@ -299,3 +299,51 @@ pub fn endpoint_client_changed_subscribe( ...@@ -299,3 +299,51 @@ pub fn endpoint_client_changed_subscribe(
}, },
) )
} }
#[turbo_tasks::value(serialization = "none")]
struct EndpointIssuesPeek {
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
}
#[turbo_tasks::function(operation)]
async fn peek_endpoint_issues_operation(
endpoint_op: OperationVc<OptionEndpoint>,
) -> Result<Vc<EndpointIssuesPeek>> {
let changed_op = endpoint_server_changed_operation(endpoint_op);
let filter = issue_filter_from_endpoint(endpoint_op).await?;
let issues = get_issues(changed_op, filter).await?;
let diagnostics = get_diagnostics(changed_op).await?;
Ok(EndpointIssuesPeek {
issues,
diagnostics,
}
.cell())
}
#[tracing::instrument(level = "info", name = "get endpoint issues", skip_all)]
#[napi]
pub async fn endpoint_get_issues(
#[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: External<ExternalEndpoint>,
) -> napi::Result<TurbopackResult<()>> {
let ctx = endpoint.turbopack_ctx();
let endpoint_op = ***endpoint;
let (issues, diags) = endpoint
.turbopack_ctx()
.turbo_tasks()
.run(async move {
let peek_op = peek_endpoint_issues_operation(endpoint_op);
let EndpointIssuesPeek {
issues,
diagnostics,
} = &*peek_op.read_strongly_consistent().await?;
Ok((issues.clone(), diagnostics.clone()))
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e.into()))
.await?;
Ok(TurbopackResult {
result: (),
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
diagnostics: diags.iter().map(|d| NapiDiagnostic::from(d)).collect(),
})
}
...@@ -175,6 +175,9 @@ export declare function endpointClientChangedSubscribe( ...@@ -175,6 +175,9 @@ export declare function endpointClientChangedSubscribe(
endpoint: { __napiType: 'Endpoint' }, endpoint: { __napiType: 'Endpoint' },
func: (...args: any[]) => any func: (...args: any[]) => any
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export declare function endpointGetIssues(endpoint: {
__napiType: 'Endpoint'
}): Promise<TurbopackResult>
export interface NapiEnvVar { export interface NapiEnvVar {
name: RcStr name: RcStr
value: RcStr value: RcStr
......
...@@ -857,6 +857,12 @@ function bindingToApi( ...@@ -857,6 +857,12 @@ function bindingToApi(
)) as TurbopackResult<WrittenEndpoint> )) as TurbopackResult<WrittenEndpoint>
} }
async getIssues(): Promise<TurbopackResult> {
return (await binding.endpointGetIssues(
this._nativeEndpoint
)) as TurbopackResult
}
async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult>> { async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult>> {
const clientSubscription = subscribe<TurbopackResult>( const clientSubscription = subscribe<TurbopackResult>(
false, false,
......
...@@ -367,6 +367,12 @@ export interface Endpoint { ...@@ -367,6 +367,12 @@ export interface Endpoint {
/** Write files for the endpoint to disk. */ /** Write files for the endpoint to disk. */
writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>>
/**
* Peek the current compilation issues for this endpoint without writing to disk.
* Returns fresh issues from the last compilation.
*/
getIssues(): Promise<TurbopackResult>
/** /**
* Listen to client-side changes to the endpoint. * Listen to client-side changes to the endpoint.
* After clientChanged() has been awaited it will listen to changes. * After clientChanged() has been awaited it will listen to changes.
......
...@@ -1041,6 +1041,8 @@ export async function createHotReloaderTurbopack( ...@@ -1041,6 +1041,8 @@ export async function createHotReloaderTurbopack(
getActiveConnectionCount: () => getActiveConnectionCount: () =>
clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size, clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,
getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN, getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN,
getCurrentEntrypoints: () => currentEntrypoints,
getWrittenEntrypoints: () => currentWrittenEntrypoints,
}), }),
] ]
: []), : []),
......
...@@ -5,8 +5,11 @@ import { registerGetPageMetadataTool } from './tools/get-page-metadata' ...@@ -5,8 +5,11 @@ import { registerGetPageMetadataTool } from './tools/get-page-metadata'
import { registerGetLogsTool } from './tools/get-logs' import { registerGetLogsTool } from './tools/get-logs'
import { registerGetActionByIdTool } from './tools/get-server-action-by-id' import { registerGetActionByIdTool } from './tools/get-server-action-by-id'
import { registerGetRoutesTool } from './tools/get-routes' import { registerGetRoutesTool } from './tools/get-routes'
import { registerGetCompilationIssuesTool } from './tools/get-compilation-issues'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types' import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
import type { NextConfigComplete } from '../config-shared' import type { NextConfigComplete } from '../config-shared'
import type { Entrypoints } from '../../build/swc/types'
import type { EntryKey } from '../../shared/lib/turbopack/entry-key'
export interface McpServerOptions { export interface McpServerOptions {
projectPath: string projectPath: string
...@@ -17,6 +20,8 @@ export interface McpServerOptions { ...@@ -17,6 +20,8 @@ export interface McpServerOptions {
sendHmrMessage: (message: HmrMessageSentToBrowser) => void sendHmrMessage: (message: HmrMessageSentToBrowser) => void
getActiveConnectionCount: () => number getActiveConnectionCount: () => number
getDevServerUrl: () => string | undefined getDevServerUrl: () => string | undefined
getCurrentEntrypoints?: () => Entrypoints
getWrittenEntrypoints?: () => ReadonlyMap<EntryKey, unknown>
} }
let mcpServer: McpServer | undefined let mcpServer: McpServer | undefined
...@@ -55,5 +60,12 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => { ...@@ -55,5 +60,12 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
appDir: options.appDir, appDir: options.appDir,
}) })
if (options.getCurrentEntrypoints && options.getWrittenEntrypoints) {
registerGetCompilationIssuesTool(mcpServer, {
getCurrentEntrypoints: options.getCurrentEntrypoints,
getWrittenEntrypoints: options.getWrittenEntrypoints,
})
}
return mcpServer return mcpServer
} }
/**
* MCP tool for retrieving Turbopack compilation issues from the Next.js dev server.
*
* This tool provides fresh compilation issues (errors, warnings, all severities)
* grouped by route, for all routes that have been compiled in the current dev session.
*
* Flow:
* MCP client → determine compiled routes from written entrypoints →
* look up Endpoint objects from currentEntrypoints →
* call endpoint.getIssues() (NAPI) for fresh issues →
* return JSON grouped by route.
*/
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import type { Entrypoints, Issue } from '../../../build/swc/types'
import type { EntryKey } from '../../../shared/lib/turbopack/entry-key'
import { splitEntryKey } from '../../../shared/lib/turbopack/entry-key'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
export interface GetCompilationIssuesOptions {
getCurrentEntrypoints: () => Entrypoints
getWrittenEntrypoints: () => ReadonlyMap<EntryKey, unknown>
}
interface CompilationIssueOutput {
severity: string
stage: string
filePath: string
title: unknown
description?: unknown
detail?: unknown
source?: unknown
additionalSources?: unknown[]
documentationLink: string
importTraces?: unknown
codeFrame?: string
}
interface CompilationIssuesOutput {
routes: Record<string, { issues: CompilationIssueOutput[] }>
message?: string
}
function formatIssue(issue: Issue): CompilationIssueOutput {
return {
severity: issue.severity,
stage: issue.stage,
filePath: issue.filePath,
title: issue.title,
description: issue.description,
detail: issue.detail,
source: issue.source,
additionalSources: issue.additionalSources ?? [],
documentationLink: issue.documentationLink,
importTraces: issue.importTraces,
codeFrame: issue.codeFrame,
}
}
export function registerGetCompilationIssuesTool(
server: McpServer,
options: GetCompilationIssuesOptions
) {
server.registerTool(
'get_compilation_issues',
{
description:
'Get current Turbopack compilation issues (errors, warnings) for all routes that have been compiled in the current dev session, grouped by route',
inputSchema: {},
},
async (_request) => {
mcpTelemetryTracker.recordToolCall('mcp/get_compilation_issues')
try {
const entrypoints = options.getCurrentEntrypoints()
const writtenEntrypoints = options.getWrittenEntrypoints()
// Determine compiled routes from written entrypoints.
// Each EntryKey is JSON like {"type":"app","side":"server","page":"/page"}.
// Extract unique page names and look them up in currentEntrypoints.
const compiledPages = new Set<string>()
for (const key of writtenEntrypoints.keys()) {
const { page } = splitEntryKey(key)
compiledPages.add(page)
}
if (compiledPages.size === 0) {
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
routes: {},
message: 'No routes have been compiled yet.',
}),
},
],
}
}
// For each compiled route, find the Endpoint(s) and call getIssues()
const output: CompilationIssuesOutput = { routes: {} }
await Promise.all(
Array.from(compiledPages).map(async (page) => {
const appRoute = entrypoints.app.get(page)
const pageRoute = entrypoints.page.get(page)
const routeEntry = appRoute ?? pageRoute
if (!routeEntry) {
// Route not found in current entrypoints (may have been removed)
return
}
const allIssues: Issue[] = []
try {
switch (routeEntry.type) {
case 'app-page': {
const result = await routeEntry.htmlEndpoint.getIssues()
allIssues.push(...result.issues)
break
}
case 'app-route': {
const result = await routeEntry.endpoint.getIssues()
allIssues.push(...result.issues)
break
}
case 'page': {
const result = await routeEntry.htmlEndpoint.getIssues()
allIssues.push(...result.issues)
break
}
case 'page-api': {
const result = await routeEntry.endpoint.getIssues()
allIssues.push(...result.issues)
break
}
default:
break
}
} catch (err) {
console.error(
`[MCP get_compilation_issues] Error getting issues for route ${page}:`,
err
)
return
}
output.routes[page] = {
issues: allIssues.map(formatIssue),
}
})
)
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(output, null, 2),
},
],
}
} catch (error) {
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
}
}
)
}
...@@ -259,6 +259,7 @@ export type McpToolName = ...@@ -259,6 +259,7 @@ export type McpToolName =
| 'mcp/get_project_metadata' | 'mcp/get_project_metadata'
| 'mcp/get_routes' | 'mcp/get_routes'
| 'mcp/get_server_action_by_id' | 'mcp/get_server_action_by_id'
| 'mcp/get_compilation_issues'
export type EventMcpToolUsage = { export type EventMcpToolUsage = {
toolName: McpToolName toolName: McpToolName
......
export default function BrokenPage() {
// Syntax error - missing closing tag
return <div>Page
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function HomePage() {
return <div>Home Page</div>
}
module.exports = {
experimental: {
mcpServer: true,
},
}
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { retry } from 'next-test-utils'
describe('mcp-server get_compilation_issues tool', () => {
const { next, skipped } = nextTestSetup({
files: new FileRef(
path.join(__dirname, 'fixtures', 'compilation-issues-app')
),
skipDeployment: true,
})
if (skipped) {
return
}
async function callGetCompilationIssues(id: string): Promise<string> {
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,
method: 'tools/call',
params: { name: 'get_compilation_issues', arguments: {} },
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
const result = JSON.parse(match![1])
return result.result?.content?.[0]?.text
}
it('should return empty issues for a page with no errors', async () => {
await next.browser('/')
let response: any = null
await retry(async () => {
const sessionId = 'test-clean-' + Date.now()
const responseText = await callGetCompilationIssues(sessionId)
response = JSON.parse(responseText)
// The '/page' route should be present once the page has been compiled
expect(response.routes).toHaveProperty('/page')
})
expect(response.routes['/page'].issues).toEqual([])
})
it('should return compilation issues for a page with a syntax error', async () => {
await next.browser('/broken')
let response: any = null
await retry(async () => {
const sessionId = 'test-broken-' + Date.now()
const responseText = await callGetCompilationIssues(sessionId)
response = JSON.parse(responseText)
expect(response.routes['/broken/page']?.issues?.length).toBeGreaterThan(0)
})
const issue = response.routes['/broken/page'].issues[0]
expect(issue).toMatchObject({
severity: 'error',
filePath: expect.stringContaining('broken/page.tsx'),
})
})
it('should reflect fixed issues after the file is patched', async () => {
await next.browser('/broken')
// Confirm there are issues before patching
await retry(async () => {
const sessionId = 'test-before-fix-' + Date.now()
const responseText = await callGetCompilationIssues(sessionId)
const resp = JSON.parse(responseText)
expect(resp.routes['/broken/page']?.issues?.length).toBeGreaterThan(0)
})
// Patch the broken page to a valid implementation
await next.patchFile(
'app/broken/page.tsx',
`export default function BrokenPage() {
return <div>Fixed</div>
}`
)
// After the fix, the issues for '/broken/page' should be empty
await retry(async () => {
const sessionId = 'test-after-fix-' + Date.now()
const responseText = await callGetCompilationIssues(sessionId)
const resp = JSON.parse(responseText)
expect(
resp.routes['/broken/page'] == null ||
resp.routes['/broken/page'].issues.length === 0
).toBe(true)
})
})
})
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