Commit 3ebfe319 authored by Tobias Koppers's avatar Tobias Koppers

Clean up get_compilation_issues tool

- Extract getRouteEndpoint() helper to eliminate duplicated 4-arm switch
- Remove redundant CompilationIssueOutput interface and formatIssue() — use Issue directly
- Add doc comments on Rust EndpointIssuesPeek and peek_endpoint_issues_operation
- Fix redundant endpoint.turbopack_ctx() call in Rust — use ctx consistently
- Add explanatory comments on conditional registration, opaque value type, and ignore entries
- Simplify test helper to auto-generate JSON-RPC IDs
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 3265e4d5
......@@ -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',
// Intentionally broken fixture (syntax error for MCP compilation-issues test)
'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',
'packages/next-swc/native/index.d.ts',
......
......@@ -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
# Intentionally broken fixture (syntax error for MCP compilation-issues test)
test/development/mcp-server/fixtures/compilation-issues-app/app/broken/page.tsx
# Tested against auto-generated content that isn't formatted
test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts
......
......@@ -300,12 +300,16 @@ pub fn endpoint_client_changed_subscribe(
)
}
/// Like [`WrittenEndpointWithIssues`] but without writing to disk or collecting
/// effects. Used for a read-only peek at current compilation issues.
#[turbo_tasks::value(serialization = "none")]
struct EndpointIssuesPeek {
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
}
/// Peeks issues from [`endpoint_server_changed_operation`] without triggering a
/// disk write (unlike [`get_written_endpoint_with_issues_operation`]).
#[turbo_tasks::function(operation)]
async fn peek_endpoint_issues_operation(
endpoint_op: OperationVc<OptionEndpoint>,
......@@ -328,8 +332,7 @@ pub async fn endpoint_get_issues(
) -> napi::Result<TurbopackResult<()>> {
let ctx = endpoint.turbopack_ctx();
let endpoint_op = ***endpoint;
let (issues, diags) = endpoint
.turbopack_ctx()
let (issues, diags) = ctx
.turbo_tasks()
.run(async move {
let peek_op = peek_endpoint_issues_operation(endpoint_op);
......
......@@ -60,6 +60,8 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
appDir: options.appDir,
})
// Turbopack-only: these options provide live access to compiled endpoint
// state that the webpack dev server does not expose.
if (options.getCurrentEntrypoints && options.getWrittenEntrypoints) {
registerGetCompilationIssuesTool(mcpServer, {
getCurrentEntrypoints: options.getCurrentEntrypoints,
......
......@@ -11,48 +11,44 @@
* 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 {
AppRoute,
Endpoint,
Entrypoints,
Issue,
PageRoute,
} 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
/**
* Only the keys are used to determine which routes have been compiled;
* the value type is intentionally opaque.
*/
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,
/**
* Returns the primary endpoint for a route entry.
*
* For page-rendering routes (`app-page`, `page`), `htmlEndpoint` is used because
* it is the primary compilation unit that aggregates issues from both client and
* server components. For API-style routes (`app-route`, `page-api`), `endpoint`
* is the only compilation unit.
*/
function getRouteEndpoint(route: AppRoute | PageRoute): Endpoint | null {
switch (route.type) {
case 'app-page':
case 'page':
return route.htmlEndpoint
case 'app-route':
case 'page-api':
return route.endpoint
default:
return null
}
}
......@@ -97,57 +93,25 @@ export function registerGetCompilationIssuesTool(
}
}
// For each compiled route, find the Endpoint(s) and call getIssues()
const output: CompilationIssuesOutput = { routes: {} }
const routes: Record<string, { issues: Issue[] }> = {}
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 routeEntry =
entrypoints.app.get(page) ?? entrypoints.page.get(page)
if (!routeEntry) return
const allIssues: Issue[] = []
const endpoint = getRouteEndpoint(routeEntry)
if (!endpoint) return
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
}
const result = await endpoint.getIssues()
routes[page] = { issues: result.issues }
} catch (err) {
console.error(
`[MCP get_compilation_issues] Error getting issues for route ${page}:`,
err
)
return
}
output.routes[page] = {
issues: allIssues.map(formatIssue),
}
})
)
......@@ -156,7 +120,7 @@ export function registerGetCompilationIssuesTool(
content: [
{
type: 'text' as const,
text: JSON.stringify(output, null, 2),
text: JSON.stringify({ routes }, null, 2),
},
],
}
......
......@@ -14,7 +14,7 @@ describe('mcp-server get_compilation_issues tool', () => {
return
}
async function callGetCompilationIssues(id: string): Promise<string> {
async function callGetCompilationIssues(): Promise<string> {
const response = await fetch(`${next.url}/_next/mcp`, {
method: 'POST',
headers: {
......@@ -23,7 +23,7 @@ describe('mcp-server get_compilation_issues tool', () => {
},
body: JSON.stringify({
jsonrpc: '2.0',
id,
id: `test-${Date.now()}`,
method: 'tools/call',
params: { name: 'get_compilation_issues', arguments: {} },
}),
......@@ -40,8 +40,7 @@ describe('mcp-server get_compilation_issues tool', () => {
let response: any = null
await retry(async () => {
const sessionId = 'test-clean-' + Date.now()
const responseText = await callGetCompilationIssues(sessionId)
const responseText = await callGetCompilationIssues()
response = JSON.parse(responseText)
// The '/page' route should be present once the page has been compiled
expect(response.routes).toHaveProperty('/page')
......@@ -55,8 +54,7 @@ describe('mcp-server get_compilation_issues tool', () => {
let response: any = null
await retry(async () => {
const sessionId = 'test-broken-' + Date.now()
const responseText = await callGetCompilationIssues(sessionId)
const responseText = await callGetCompilationIssues()
response = JSON.parse(responseText)
expect(response.routes['/broken/page']?.issues?.length).toBeGreaterThan(0)
})
......@@ -73,9 +71,7 @@ describe('mcp-server get_compilation_issues tool', () => {
// 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)
const resp = JSON.parse(await callGetCompilationIssues())
expect(resp.routes['/broken/page']?.issues?.length).toBeGreaterThan(0)
})
......@@ -89,9 +85,7 @@ describe('mcp-server get_compilation_issues tool', () => {
// 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)
const resp = JSON.parse(await callGetCompilationIssues())
expect(
resp.routes['/broken/page'] == null ||
resp.routes['/broken/page'].issues.length === 0
......
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