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([ ...@@ -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',
// Intentionally broken fixture (syntax error for MCP compilation-issues test)
'test/development/mcp-server/fixtures/compilation-issues-app/app/broken/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',
......
...@@ -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
# Intentionally broken fixture (syntax error for MCP compilation-issues test)
test/development/mcp-server/fixtures/compilation-issues-app/app/broken/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
......
...@@ -300,12 +300,16 @@ pub fn endpoint_client_changed_subscribe( ...@@ -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")] #[turbo_tasks::value(serialization = "none")]
struct EndpointIssuesPeek { struct EndpointIssuesPeek {
issues: Arc<Vec<ReadRef<PlainIssue>>>, issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>, 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)] #[turbo_tasks::function(operation)]
async fn peek_endpoint_issues_operation( async fn peek_endpoint_issues_operation(
endpoint_op: OperationVc<OptionEndpoint>, endpoint_op: OperationVc<OptionEndpoint>,
...@@ -328,8 +332,7 @@ pub async fn endpoint_get_issues( ...@@ -328,8 +332,7 @@ pub async fn endpoint_get_issues(
) -> napi::Result<TurbopackResult<()>> { ) -> napi::Result<TurbopackResult<()>> {
let ctx = endpoint.turbopack_ctx(); let ctx = endpoint.turbopack_ctx();
let endpoint_op = ***endpoint; let endpoint_op = ***endpoint;
let (issues, diags) = endpoint let (issues, diags) = ctx
.turbopack_ctx()
.turbo_tasks() .turbo_tasks()
.run(async move { .run(async move {
let peek_op = peek_endpoint_issues_operation(endpoint_op); let peek_op = peek_endpoint_issues_operation(endpoint_op);
......
...@@ -60,6 +60,8 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => { ...@@ -60,6 +60,8 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
appDir: options.appDir, 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) { if (options.getCurrentEntrypoints && options.getWrittenEntrypoints) {
registerGetCompilationIssuesTool(mcpServer, { registerGetCompilationIssuesTool(mcpServer, {
getCurrentEntrypoints: options.getCurrentEntrypoints, getCurrentEntrypoints: options.getCurrentEntrypoints,
......
...@@ -11,48 +11,44 @@ ...@@ -11,48 +11,44 @@
* return JSON grouped by route. * return JSON grouped by route.
*/ */
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' 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 type { EntryKey } from '../../../shared/lib/turbopack/entry-key'
import { splitEntryKey } from '../../../shared/lib/turbopack/entry-key' import { splitEntryKey } from '../../../shared/lib/turbopack/entry-key'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker' import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
export interface GetCompilationIssuesOptions { export interface GetCompilationIssuesOptions {
getCurrentEntrypoints: () => Entrypoints getCurrentEntrypoints: () => Entrypoints
/**
* Only the keys are used to determine which routes have been compiled;
* the value type is intentionally opaque.
*/
getWrittenEntrypoints: () => ReadonlyMap<EntryKey, unknown> getWrittenEntrypoints: () => ReadonlyMap<EntryKey, unknown>
} }
interface CompilationIssueOutput { /**
severity: string * Returns the primary endpoint for a route entry.
stage: string *
filePath: string * For page-rendering routes (`app-page`, `page`), `htmlEndpoint` is used because
title: unknown * it is the primary compilation unit that aggregates issues from both client and
description?: unknown * server components. For API-style routes (`app-route`, `page-api`), `endpoint`
detail?: unknown * is the only compilation unit.
source?: unknown */
additionalSources?: unknown[] function getRouteEndpoint(route: AppRoute | PageRoute): Endpoint | null {
documentationLink: string switch (route.type) {
importTraces?: unknown case 'app-page':
codeFrame?: string case 'page':
} return route.htmlEndpoint
case 'app-route':
interface CompilationIssuesOutput { case 'page-api':
routes: Record<string, { issues: CompilationIssueOutput[] }> return route.endpoint
message?: string default:
} return null
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,
} }
} }
...@@ -97,57 +93,25 @@ export function registerGetCompilationIssuesTool( ...@@ -97,57 +93,25 @@ export function registerGetCompilationIssuesTool(
} }
} }
// For each compiled route, find the Endpoint(s) and call getIssues() const routes: Record<string, { issues: Issue[] }> = {}
const output: CompilationIssuesOutput = { routes: {} }
await Promise.all( await Promise.all(
Array.from(compiledPages).map(async (page) => { Array.from(compiledPages).map(async (page) => {
const appRoute = entrypoints.app.get(page) const routeEntry =
const pageRoute = entrypoints.page.get(page) entrypoints.app.get(page) ?? entrypoints.page.get(page)
const routeEntry = appRoute ?? pageRoute if (!routeEntry) return
if (!routeEntry) { const endpoint = getRouteEndpoint(routeEntry)
// Route not found in current entrypoints (may have been removed) if (!endpoint) return
return
}
const allIssues: Issue[] = []
try { try {
switch (routeEntry.type) { const result = await endpoint.getIssues()
case 'app-page': { routes[page] = { issues: result.issues }
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) { } catch (err) {
console.error( console.error(
`[MCP get_compilation_issues] Error getting issues for route ${page}:`, `[MCP get_compilation_issues] Error getting issues for route ${page}:`,
err err
) )
return
}
output.routes[page] = {
issues: allIssues.map(formatIssue),
} }
}) })
) )
...@@ -156,7 +120,7 @@ export function registerGetCompilationIssuesTool( ...@@ -156,7 +120,7 @@ export function registerGetCompilationIssuesTool(
content: [ content: [
{ {
type: 'text' as const, 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', () => { ...@@ -14,7 +14,7 @@ describe('mcp-server get_compilation_issues tool', () => {
return return
} }
async function callGetCompilationIssues(id: string): Promise<string> { async function callGetCompilationIssues(): Promise<string> {
const response = await fetch(`${next.url}/_next/mcp`, { const response = await fetch(`${next.url}/_next/mcp`, {
method: 'POST', method: 'POST',
headers: { headers: {
...@@ -23,7 +23,7 @@ describe('mcp-server get_compilation_issues tool', () => { ...@@ -23,7 +23,7 @@ describe('mcp-server get_compilation_issues tool', () => {
}, },
body: JSON.stringify({ body: JSON.stringify({
jsonrpc: '2.0', jsonrpc: '2.0',
id, id: `test-${Date.now()}`,
method: 'tools/call', method: 'tools/call',
params: { name: 'get_compilation_issues', arguments: {} }, params: { name: 'get_compilation_issues', arguments: {} },
}), }),
...@@ -40,8 +40,7 @@ describe('mcp-server get_compilation_issues tool', () => { ...@@ -40,8 +40,7 @@ describe('mcp-server get_compilation_issues tool', () => {
let response: any = null let response: any = null
await retry(async () => { await retry(async () => {
const sessionId = 'test-clean-' + Date.now() const responseText = await callGetCompilationIssues()
const responseText = await callGetCompilationIssues(sessionId)
response = JSON.parse(responseText) response = JSON.parse(responseText)
// The '/page' route should be present once the page has been compiled // The '/page' route should be present once the page has been compiled
expect(response.routes).toHaveProperty('/page') expect(response.routes).toHaveProperty('/page')
...@@ -55,8 +54,7 @@ describe('mcp-server get_compilation_issues tool', () => { ...@@ -55,8 +54,7 @@ describe('mcp-server get_compilation_issues tool', () => {
let response: any = null let response: any = null
await retry(async () => { await retry(async () => {
const sessionId = 'test-broken-' + Date.now() const responseText = await callGetCompilationIssues()
const responseText = await callGetCompilationIssues(sessionId)
response = JSON.parse(responseText) response = JSON.parse(responseText)
expect(response.routes['/broken/page']?.issues?.length).toBeGreaterThan(0) expect(response.routes['/broken/page']?.issues?.length).toBeGreaterThan(0)
}) })
...@@ -73,9 +71,7 @@ describe('mcp-server get_compilation_issues tool', () => { ...@@ -73,9 +71,7 @@ describe('mcp-server get_compilation_issues tool', () => {
// Confirm there are issues before patching // Confirm there are issues before patching
await retry(async () => { await retry(async () => {
const sessionId = 'test-before-fix-' + Date.now() const resp = JSON.parse(await callGetCompilationIssues())
const responseText = await callGetCompilationIssues(sessionId)
const resp = JSON.parse(responseText)
expect(resp.routes['/broken/page']?.issues?.length).toBeGreaterThan(0) expect(resp.routes['/broken/page']?.issues?.length).toBeGreaterThan(0)
}) })
...@@ -89,9 +85,7 @@ describe('mcp-server get_compilation_issues tool', () => { ...@@ -89,9 +85,7 @@ describe('mcp-server get_compilation_issues tool', () => {
// After the fix, the issues for '/broken/page' should be empty // After the fix, the issues for '/broken/page' should be empty
await retry(async () => { await retry(async () => {
const sessionId = 'test-after-fix-' + Date.now() const resp = JSON.parse(await callGetCompilationIssues())
const responseText = await callGetCompilationIssues(sessionId)
const resp = JSON.parse(responseText)
expect( expect(
resp.routes['/broken/page'] == null || resp.routes['/broken/page'] == null ||
resp.routes['/broken/page'].issues.length === 0 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