Unverified Commit abc848d7 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Scope MCP compilation issues to an explicit route

Co-authored-by: 's avatarAndrew Imm <494043+andrewimm@users.noreply.github.com>
parent 7748e532
......@@ -131,7 +131,9 @@ First, `next dev` forwards browser console errors and warnings to the terminal (
`next dev` also writes its PID, port, and URL to `.next/dev/lock`. If you run `next dev` while another development server is already running for the project, the command prints the existing server's URL and PID, along with a command to stop it. Continue with the existing server when possible to avoid interrupting the active development session.
The **framework's view** comes from the [Next.js MCP server](/docs/app/guides/mcp) at `/_next/mcp`, which exposes the running dev server's routes, server logs, and compilation issues. Its `get_compilation_issues` and `compile_route` tools report whether the code compiles straight from the dev server, so an agent doesn't have to run a full `next build` to find out.
The **framework's view** comes from the [Next.js MCP server](/docs/app/guides/mcp) at `/_next/mcp`, which exposes the running dev server's routes, server logs, and compilation issues. Discover capabilities with `tools/list` without compiling. After an edit, use `compile_route` with exactly one explicit `routeSpecifier` or `path` to check the changed route and its dependencies. It returns `{ routeSpecifier, issues }` inline without a full `next build`. On current servers, `get_compilation_issues` is a scoped alias with the same selectors; empty calls fail with `ROUTE_REQUIRED` instead of compiling the app. If scoped compilation is unavailable, report it as unsupported rather than falling back to an older server's whole-app tool.
These checks do not validate every route that imports a shared file. A single route can still be expensive, and the tools do not supply hard memory limits, native cancellation, or graph reclamation. Make exhaustive validation explicit and use CI or a resource-isolated process for large apps.
The [`next-dev-loop` skill](#next-dev-loop) adds the **browser's view** through [`agent-browser`](https://github.com/vercel-labs/agent-browser), a CLI that exposes the DOM, console, network, and Web Vitals as structured text. The Skill opens `agent-browser` with React DevTools enabled, which also exposes the component tree and pending Suspense boundaries. An agent can run a command such as `react tree` and use the structured output to decide what to inspect next.
......
......@@ -57,11 +57,24 @@ Through `nextjs_call`, agents can use the tools the Next.js development server e
- **`get_project_metadata`**: Get the project path and dev server URL.
- **`get_routes`**: Get all routes that will become entry points by scanning the filesystem. Returns routes grouped by router type (`appRouter`, `pagesRouter`). Dynamic segments appear as `[param]` or `[...slug]` patterns.
- **`get_server_action_by_id`**: Look up a Server Action by its ID to find its source file and export name.
- **`get_compilation_issues`**: Build the module graph for all routes and return compilation issues such as resolve errors, missing modules, and transform errors. Doesn't require a browser session. Turbopack only.
- **`compile_route`**: Compile a specific route without making an HTTP request to it. Accepts either a `routeSpecifier` (for example, `/blog/[slug]`, as returned by `get_routes`) or a `path` (for example, `/blog/hello-world`), which is resolved to the matching route. Returns any compilation issues for the route. Turbopack only.
- **`get_compilation_issues`**: Compile one selected route and return compilation issues such as resolve errors, missing modules, and transform errors. Requires exactly one of `routeSpecifier` or `path` and returns `{ routeSpecifier, issues }`, matching `compile_route`. An empty call returns a `ROUTE_REQUIRED` tool error without compiling. Doesn't require a browser session. Turbopack only.
- **`compile_route`**: Compile a specific route without making an HTTP request to it. Requires exactly one of `routeSpecifier` (for example, `/blog/[slug]`, as returned by `get_routes`) or `path` (for example, `/blog/hello-world`), which is resolved to the matching route. Returns `{ routeSpecifier, issues }` with compilation issues inline. Turbopack only.
- **`get_request_insights`**: Get recent App Router request timelines, server fetches, and cache behavior captured by the local span recorder. Requires `experimental.requestInsights`.
With the compilation tools, agents can check whether code compiles from the running dev server instead of running `next build` while they are still editing.
With the compilation tools, agents can check a selected route from the running dev server instead of running `next build` while they are still editing. The route's applicable layouts, imports, and shared dependencies are included naturally; other routes that use those dependencies are not validated.
Use MCP `tools/list` for capability discovery without compiling. Do not call a compilation tool just to detect Turbopack. On older servers, `get_compilation_issues` may perform whole-app analysis; if `compile_route` is unavailable, report scoped compile verification as unsupported rather than falling back to that tool. A missing tool alone does not identify the Next.js version or bundler.
For example, after editing a blog page, call `compile_route` with an explicit route:
```json filename="MCP tools/call parameters"
{
"name": "compile_route",
"arguments": { "routeSpecifier": "/blog/[slug]" }
}
```
Neither tool falls back to compiling all routes. Route scope reduces unwanted work, but a single route can still be expensive: these tools do not enforce hard memory limits, provide native cancellation, or guarantee graph reclamation. Checking a route is not exhaustive app validation. For large apps, make broader validation explicit and run exhaustive checks in CI or a resource-isolated process.
## Development workflow
......
......@@ -1359,7 +1359,6 @@ export async function createHotReloaderTurbopack(
getActiveConnectionCount: () =>
clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,
getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN,
getTurbopackProject: () => project,
compileRoute: async ({ routeSpecifier, path }) => {
// Resolve the caller's input to a concrete route specifier. The
// path-mode branch reuses the dev router's own live route table
......@@ -1400,8 +1399,12 @@ export async function createHotReloaderTurbopack(
// "/blog/[slug]/page" for a dynamic page). Use normalizeAppPath to
// strip that suffix and find the entry matching the user-facing route.
let extraOptions: object | undefined = undefined
let issueEntryKeys: EntryKey[] = [
getEntryKey('pages', 'server', page),
]
for (const [name] of currentEntrypoints.app) {
if (normalizeAppPath(name) === page) {
issueEntryKeys = [getEntryKey('app', 'server', name)]
extraOptions = {
// Synthesize a definition so ensurePage bypasses findPagePathData.
// Only page and bundlePath are used from the definition:
......@@ -1416,6 +1419,26 @@ export async function createHotReloaderTurbopack(
break
}
}
if (
!extraOptions &&
(currentEntrypoints.page.get(page)?.type === 'page' ||
page === '/_error')
) {
// Pages HTML compilation also writes the shared framework
// endpoints. API routes and App routes do not compile these.
issueEntryKeys.push(getEntryKey('pages', 'client', page))
if (currentEntrypoints.global.app) {
issueEntryKeys.push(getEntryKey('pages', 'server', '_app'))
}
if (currentEntrypoints.global.document) {
issueEntryKeys.push(
getEntryKey('pages', 'server', '_document')
)
}
if (page === '/_error') {
issueEntryKeys.push(getEntryKey('pages', 'server', '_error'))
}
}
const ensureOpts = {
page,
// Compile both server and client bundles, matching what happens
......@@ -1429,12 +1452,6 @@ export async function createHotReloaderTurbopack(
...extraOptions,
}
// Snapshot the current issue maps before compilation so we can
// identify which entry keys were added or updated by this call.
// processIssues always creates a new Map() reference, so identity
// comparison detects changes even for re-compilations.
const snapshotBefore = new Map(currentEntryIssues)
// For app-page routes, processIssues is called with throwIssue=true,
// meaning it throws ModuleBuildError when there are compile errors—but
// it still writes the issues into currentEntryIssues before throwing.
......@@ -1451,14 +1468,17 @@ export async function createHotReloaderTurbopack(
}
}
const rawIssues = []
for (const [key, issueMap] of currentEntryIssues) {
if (snapshotBefore.get(key) !== issueMap) {
rawIssues.push(...issueMap.values())
}
// Read only this route's entries, not every map changed while we
// awaited compilation: another MCP call, browser or HMR update may
// have compiled an unrelated route in the meantime. Top-level
// project/entrypoint issues apply independently of route selection.
const rawIssues = [...currentTopLevelIssues.values()]
for (const key of issueEntryKeys) {
const issueMap = currentEntryIssues.get(key)
if (issueMap) rawIssues.push(...issueMap.values())
}
// If ensurePage threw ModuleBuildError but we found no new issues in
// If ensurePage threw ModuleBuildError but we found no issues in
// the map (shouldn't happen, but be safe), re-surface the original
// error so its message and stack are preserved.
if (moduleBuildError && rawIssues.length === 0) {
......@@ -2132,7 +2152,9 @@ export async function createHotReloaderTurbopack(
productionRewrites: undefined,
logErrors: true,
hooks: {
subscribeToChanges: subscribeToClientChanges,
subscribeToChanges: subscribeToChanges
? subscribeToClientChanges
: ((async () => {}) as StartChangeSubscription),
handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result.value)
assetMapper.setPathsForKey(id, result.value.clientPaths)
......
......@@ -10,8 +10,7 @@ import { registerCompileRouteTool } from './tools/compile-route'
import { registerGetRequestInsightsTool } from './tools/get-request-insights'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
import type { NextConfigComplete } from '../config-shared'
import type { Project } from '../../build/swc/types'
import type { FormattedIssue } from './tools/utils/format-compilation-issues'
import type { CompileRoute } from './tools/utils/compile-route'
export interface McpServerOptions {
projectPath: string
......@@ -22,11 +21,7 @@ export interface McpServerOptions {
sendHmrMessage: (message: HmrMessageSentToBrowser) => void
getActiveConnectionCount: () => number
getDevServerUrl: () => string | undefined
getTurbopackProject?: () => Project | undefined
compileRoute?: (opts: {
routeSpecifier?: string
path?: string
}) => Promise<{ routeSpecifier: string; issues: FormattedIssue[] }>
compileRoute?: CompileRoute
}
let mcpServer: McpServer | undefined
......@@ -66,11 +61,8 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
})
registerGetRequestInsightsTool(mcpServer)
if (options.getTurbopackProject) {
registerGetCompilationIssuesTool(mcpServer, options.getTurbopackProject)
}
if (options.compileRoute) {
registerGetCompilationIssuesTool(mcpServer, options.compileRoute)
registerCompileRouteTool(mcpServer, options.compileRoute)
}
......
/**
* MCP tool for compiling a specific route via the on-demand entry handler.
*
* Triggers on-demand compilation so the route's assets are built without making an
* HTTP request to the route. This is the same call path the dev server uses
* when a route is first navigated to, making it useful for warming the module
* graph, measuring compile time, or pre-compiling routes for memory
* benchmarking without requiring live backends.
* Compile a selected route via the on-demand entry handler, without making an
* HTTP request to the route or installing persistent HMR subscriptions.
*/
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
import type { FormattedIssue } from './utils/format-compilation-issues'
import z from 'next/dist/compiled/zod'
import {
type CompileRoute,
createCompileRouteHandler,
routeSelectorSchema,
} from './utils/compile-route'
export function registerCompileRouteTool(
server: McpServer,
compileRoute: (opts: {
routeSpecifier?: string
path?: string
}) => Promise<{ routeSpecifier: string; issues: FormattedIssue[] }>
compileRoute: CompileRoute
) {
server.registerTool(
'compile_route',
{
description:
'Compile a specific route (page or API route) without making an HTTP request. ' +
'Triggers the same on-demand compilation the dev server uses when a route is first visited. ' +
'Useful for warming up the module graph, measuring compile time, or pre-compiling routes for memory benchmarking. ' +
'Provide exactly one of routeSpecifier or path. ' +
'Triggers the same on-demand compilation the dev server uses when a route is first visited, including its dependencies. ' +
'Returns { routeSpecifier, issues } on success where routeSpecifier is the resolved route and issues contains any compilation warnings or errors. ' +
'Returns an error if no matching route exists.',
inputSchema: {
routeSpecifier: z
.string()
.describe(
'A route specifier as returned by the get_routes tool (e.g. "/", "/blog/[slug]", "/api/users/[id]"). ' +
'Mutually exclusive with `path`; provide exactly one.'
)
.optional(),
path: z
.string()
.describe(
'A URL path on this site (e.g. "/blog/hello-world", "/docs/a/b/c"). ' +
'Query strings are allowed and ignored. Do not include scheme/host/port. ' +
"The path is resolved to its matching route specifier using the dev router's live route table. " +
'Mutually exclusive with `routeSpecifier`; provide exactly one.'
)
.optional(),
},
'Returns an error if no matching route exists. Never falls back to compiling all routes. ' +
'Use tools/list for capability discovery without compilation. A single route can still be expensive; this tool does not enforce a memory limit.',
inputSchema: routeSelectorSchema,
},
async ({ routeSpecifier, path }) => {
mcpTelemetryTracker.recordToolCall('mcp/compile_route')
if ((routeSpecifier == null) === (path == null)) {
return {
isError: true,
content: [
{
type: 'text',
text: JSON.stringify({
error: 'Provide exactly one of `routeSpecifier` or `path`.',
}),
},
],
}
}
try {
const { routeSpecifier: resolvedRouteSpecifier, issues } =
await compileRoute({ routeSpecifier, path })
return {
content: [
{
type: 'text',
text: JSON.stringify({
routeSpecifier: resolvedRouteSpecifier,
issues,
}),
},
],
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
const notFound =
error instanceof Error &&
(error as NodeJS.ErrnoException).code === 'ENOENT'
return {
isError: true,
content: [
{
type: 'text',
text: JSON.stringify(
notFound
? { notFound: true, input: path ?? routeSpecifier }
: { input: path ?? routeSpecifier, error: message }
),
},
],
}
}
}
createCompileRouteHandler('compile_route', compileRoute)
)
}
/**
* 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.
* Get compilation issues for one selected route using the same on-demand
* compilation as compile_route. Never constructs the whole-app module graph.
*/
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'
import {
type CompileRoute,
createCompileRouteHandler,
routeSelectorSchema,
} from './utils/compile-route'
export function registerGetCompilationIssuesTool(
server: McpServer,
getProject: () => Project | undefined
compileRoute: CompileRoute
) {
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: {},
'Compile one selected route and return its compilation issues (resolve errors, missing modules, transform errors, etc.). ' +
"Provide exactly one of routeSpecifier or path. Includes the route's layouts, imports and shared dependencies as applicable; does not require a browser session. " +
'Returns { routeSpecifier, issues }, matching compile_route. Empty calls return a ROUTE_REQUIRED error without compiling. ' +
'Never falls back to compiling all routes. Use tools/list for capability discovery without compilation. ' +
'A single route can still be expensive; this tool does not enforce a memory limit.',
inputSchema: routeSelectorSchema,
},
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),
}),
},
],
}
}
}
createCompileRouteHandler('get_compilation_issues', compileRoute)
)
}
import z from 'next/dist/compiled/zod'
import { mcpTelemetryTracker } from '../../mcp-telemetry-tracker'
import type { FormattedIssue } from './format-compilation-issues'
export type RouteSelector = { routeSpecifier?: string; path?: string }
export type CompileRoute = (
opts: RouteSelector
) => Promise<{ routeSpecifier: string; issues: FormattedIssue[] }>
export const routeSelectorSchema = {
routeSpecifier: z
.string()
.describe(
'A route specifier as returned by the get_routes tool (e.g. "/", "/blog/[slug]", "/api/users/[id]"). ' +
'Mutually exclusive with `path`; provide exactly one.'
)
.optional(),
path: z
.string()
.describe(
'A URL path on this site (e.g. "/blog/hello-world", "/docs/a/b/c"). ' +
'Query strings are allowed and ignored. Do not include scheme/host/port. ' +
"The path is resolved to its matching route specifier using the dev router's live route table. " +
'Mutually exclusive with `routeSpecifier`; provide exactly one.'
)
.optional(),
}
export function createCompileRouteHandler(
toolName: 'compile_route' | 'get_compilation_issues',
compileRoute: CompileRoute
) {
return async ({ routeSpecifier, path }: RouteSelector) => {
mcpTelemetryTracker.recordToolCall(`mcp/${toolName}`)
if ((routeSpecifier == null) === (path == null)) {
const routeRequired =
toolName === 'get_compilation_issues' && routeSpecifier == null
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
routeRequired
? {
code: 'ROUTE_REQUIRED',
error:
'Provide exactly one of `routeSpecifier` or `path`. Use tools/list for capability discovery without compiling routes.',
}
: {
error: 'Provide exactly one of `routeSpecifier` or `path`.',
}
),
},
],
}
}
try {
const { routeSpecifier: resolvedRouteSpecifier, issues } =
await compileRoute({ routeSpecifier, path })
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
routeSpecifier: resolvedRouteSpecifier,
issues,
}),
},
],
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
const notFound =
error instanceof Error &&
(error as NodeJS.ErrnoException).code === 'ENOENT'
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify(
notFound
? { notFound: true, input: path ?? routeSpecifier }
: { input: path ?? routeSpecifier, error: message }
),
},
],
}
}
}
}
......@@ -30,8 +30,9 @@ The two views cross-check each other.
## requires
- Next.js **16.3+** with **Turbopack** — `/_next/mcp` plus the
proactive compile check via `get_compilation_issues`.
- Next.js **16.3+** with **Turbopack** — `/_next/mcp` with
`compile_route` listed by `tools/list` for route-scoped checks.
Verify this capability; do not assume every older server supports it.
- `agent-browser` **>= 0.31.1** — React introspection, worktree-scoped
`session id`, idempotent `--restore`, and launch flag reconciliation.
......@@ -87,18 +88,21 @@ Once per session, confirm both views are live.
Pause while the user drives login, then continue with the same session and
keep it headed for the rest of the loop.
2. Probe `/_next/mcp` (`tools/list`) — confirm it's reachable and
lists `get_compilation_issues`. First read the port off the
`next dev` banner; if it isn't 3000, set
`NEXT_MCP_URL=http://localhost:<port>/_next/mcp` before probing:
- Unreachable → either `next dev` isn't running, or Next.js is
below 16.3. Check `package.json` to disambiguate, then refuse.
- `get_compilation_issues` not in the list → Next.js below 16.3.
Refuse and tell the user to upgrade.
3. `get_compilation_issues` doubles as a Turbopack probe. An error
response of `"Turbopack project is not available..."` means the
user is on webpack. Refuse — Turbopack is required.
4. `get_routes` → your route map for the rest of the session.
2. Discover `/_next/mcp` capabilities with **`tools/list` only** —
confirm it's reachable and lists `compile_route`. First read the
port off the `next dev` banner; if it isn't 3000, set
`NEXT_MCP_URL=http://localhost:<port>/_next/mcp` before discovery:
- Unreachable → check the server, port, configuration and installed
version. Do not infer a Next.js version from this alone.
- `compile_route` missing → report scoped compile verification as
unsupported and stop. Check the bundler/version and tell the user
how to enable Turbopack or upgrade as appropriate. A missing tool
alone does not establish either one.
- Never call either compilation tool just to detect the bundler.
In particular, do not fall back to an older server's whole-app
`get_compilation_issues` tool; even an empty call may compile all routes.
3. `get_routes` → your route map for the rest of the session. This
filesystem scan does not compile routes.
## loop
......@@ -113,7 +117,12 @@ search doesn't.
Four failure modes. Check each:
- **Compiles** — `get_compilation_issues`.
- **Compiles** — `compile_route` with exactly one explicit selector:
`{ "routeSpecifier": "/blog/[slug]" }` from `get_routes`, or
`{ "path": "/blog/hello-world" }`. Verify the route you changed and
consume `{ routeSpecifier, issues }` inline; do not make a second
empty `get_compilation_issues` call. Its layouts, imports and shared
dependencies are included as applicable, not every route using them.
- **Runs without errors** — `/_next/mcp` (server and bubbled-up
browser errors both surface here).
- **Behaves as intended** — `agent-browser` drives the page; assert
......@@ -129,6 +138,13 @@ manual rather than from memory.
## gotchas
- **Route scope is not a memory budget.** One route can still be expensive.
These checks do not supply hard memory limits, native cancellation or
graph reclamation, and do not prove that the whole app compiles. Do not
loop through every route as an invisible preflight. Agree on broader
validation explicitly and use CI or a resource-isolated process for
exhaustive checks on large apps.
- **Preserve `.next` while the development server is running.** Moving or
deleting it disconnects the server from its generated state and discards
incremental caches. Moving it to a backup is still a reset. If a production
......@@ -166,12 +182,13 @@ manual rather than from memory.
## reference
All tools below are present once preflight passes. If `tools/list`
is missing any of them, preflight should have refused — re-check.
Use `tools/list` as the authority for the installed server's tools.
The surface can vary by version and configuration; scoped compilation
requires `compile_route` to be listed.
```
# /_next/mcp notes
get_project_metadata projectPath, devServerUrl, bundler
get_project_metadata projectPath, devServerUrl
get_routes fs-scan; no browser session needed
get_errors runtime + build; needs a browser session;
includes browser-side errors caught by the
......@@ -181,8 +198,12 @@ get_page_metadata segment trie + routerType; needs a browser
which files power a route
get_logs returns logFilePath
get_server_action_by_id hashed id → file + functionName
get_compilation_issues Turbopack only; errors on webpack
("Turbopack project is not available")
compile_route Turbopack only; exactly one of routeSpecifier
or path; returns { routeSpecifier, issues }
get_compilation_issues scoped alias on current servers; same selectors
and response; empty call errors ROUTE_REQUIRED
without compiling; older servers may instead
perform whole-app work — never use as a probe
```
## teardown
......
import Shared from 'shared-layout-dependency'
export default function Layout({ children }) {
return <Shared>{children}</Shared>
}
import sentinel from './asset.sentinel'
export default function Page() {
return <p>{sentinel}</p>
}
module.exports = {
turbopack: {
rules: {
'*.sentinel': {
loaders: ['./sentinel-loader.js'],
as: '*.js',
},
},
},
experimental: {
mcpServer: true,
},
......
export default function Page() {
return <p>Pages Router</p>
}
const fs = require('fs')
const path = require('path')
module.exports = function () {
fs.writeFileSync(
path.join(this.rootContext, 'sentinel-transformed'),
'compiled'
)
return 'export default "sentinel"'
}
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
async function callMcpTool(
url: string,
......@@ -59,6 +60,24 @@ async function callMcpTool(
expect(result).toMatchObject({ routeSpecifier: '/about', issues: [] })
})
it('should compile a custom Pages error route through both aliases', async () => {
await next.patchFile(
'pages/_error.tsx',
'export default function ErrorPage() { return <p>Error</p> }',
async () => {
await retry(async () => {
for (const name of ['compile_route', 'get_compilation_issues']) {
expect(
await callMcpTool(next.url, name, {
routeSpecifier: '/_error',
})
).toEqual({ routeSpecifier: '/_error', issues: [] })
}
})
}
)
})
it('should compile a valid app router API route', async () => {
const result = await callMcpTool(next.url, 'compile_route', {
routeSpecifier: '/api/users/[id]',
......
......@@ -5,6 +5,31 @@ describe('mcp-server get_project_metadata tool', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
it('advertises scoped compilation only on Turbopack without calling it', async () => {
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: 'list-tools',
method: 'tools/list',
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
expect(match).toBeTruthy()
const envelope = JSON.parse(match![1])
const names = envelope.result.tools.map(
(tool: { name: string }) => tool.name
)
for (const name of ['compile_route', 'get_compilation_issues']) {
expect(names.includes(name)).toBe(Boolean(process.env.IS_TURBOPACK_TEST))
}
})
it('should return correct project metadata via get_project_metadata tool', async () => {
const mcpEndpoint = `${next.url}/_next/mcp`
......
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