---
title: "MCP Tool Integration"
description: "The Next.js Model Context Protocol (MCP) tool integration provides a standardized interface for AI agents and external clients to interact directly with a running Next.js development server and bui..."
last_updated: "2026-09-23T10:52:03.186406+00:00"
canonical_url: "https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development-and-diagnostics/mcp-tool-integration"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [packages/next/src/server/dev/hot-reloader-turbopack.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/hot-reloader-turbopack.ts)
- [packages/next/src/server/mcp/get-or-create-mcp-server.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts)
- [packages/next/src/server/dev/hot-reloader-webpack.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/hot-reloader-webpack.ts)
- [packages/next/src/server/mcp/tools/get-compilation-issues.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-compilation-issues.ts)
- [packages/next/src/server/mcp/tools/compile-route.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts)
- [packages/next/src/server/dev/on-demand-entry-handler.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/on-demand-entry-handler.ts)
- [packages/next/src/server/mcp/tools/get-errors.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-errors.ts)
- [packages/next/src/server/mcp/tools/get-logs.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-logs.ts)
- [packages/next/src/cli/internal/turbo-trace-server.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts)
- [packages/next/src/server/mcp/get-mcp-middleware.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts)
- [packages/next/src/server/mcp/tools/get-project-metadata.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-project-metadata.ts)
- [packages/next/src/server/mcp/tools/get-page-metadata.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts)
- [packages/next/src/server/mcp/mcp-telemetry-tracker.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/mcp-telemetry-tracker.ts)
- [packages/next/src/server/lib/router-utils/setup-dev-bundler.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts)
- [packages/next/src/server/mcp/tools/next-instance-error-state.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/next-instance-error-state.ts)
- [packages/next/src/server/mcp/tools/get-routes.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-routes.ts)
- [packages/next/src/cli/internal/query-trace.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/query-trace.ts)
- [packages/next/src/server/dev/next-dev-server.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/next-dev-server.ts)
- [packages/next/src/shared/lib/mcp-error-types.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/shared/lib/mcp-error-types.ts)
- [packages/next/src/server/mcp/tools/get-server-action-by-id.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-server-action-by-id.ts)
- [packages/next/src/server/mcp/tools/utils/browser-communication.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/utils/browser-communication.ts)
- [packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts)
- [packages/next/src/shared/lib/mcp-page-metadata-types.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/shared/lib/mcp-page-metadata-types.ts)
- [packages/next/src/next-devtools/server/restart-dev-server-middleware.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/next-devtools/server/restart-dev-server-middleware.ts)
- [packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts)
- [packages/next/src/server/dev/middleware-webpack.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/middleware-webpack.ts)
- [packages/next/src/server/dev/middleware-turbopack.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/middleware-turbopack.ts)
- [packages/next/src/next-devtools/server/devtools-config-middleware.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/next-devtools/server/devtools-config-middleware.ts)
- [packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx](https://github.com/blade47/next.js/blob/main/packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx)
- [packages/next/src/server/patch-error-inspect.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/patch-error-inspect.ts)
</details>

## Overview

The Next.js Model Context Protocol (MCP) tool integration provides a standardized interface for AI agents and external clients to interact directly with a running Next.js development server and build pipeline. By exposing structured tools over HTTP and streamable transport layers, the MCP server allows external agents to inspect project and page metadata, enumerate routes, trigger on-demand route compilation, query compilation diagnostics, and retrieve error states or development logs without requiring manual browser navigation. 

Sources: [packages/next/src/server/mcp/get-or-create-mcp-server.ts:1-76](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L1-L76)

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:1-44](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L1-L44)

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:1-103](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L1-L103)

## Server Architecture and HTTP Middleware

### Overview

The Next.js Model Context Protocol (MCP) server instance is managed via a lazy initialization lifecycle linked directly to the development server's hot reloaders. When experimental MCP server support is enabled via configuration (`experimental.mcpServer`), the dev server registers HTTP middleware inside both Turbopack and Webpack hot reloaders. This middleware intercepts incoming requests matching the `/_next/mcp` prefix, connects an isolated streamable transport, and delegates execution to the core MCP server instance. 

Sources: [packages/next/src/server/dev/hot-reloader-turbopack.ts:1034-1046](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/hot-reloader-turbopack.ts#L1034-L1046)

Sources: [packages/next/src/server/mcp/get-or-create-mcp-server.ts:33-76](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L33-L76)

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:9-44](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L9-L44)

### Lifecycle and Middleware Integration

The lifecycle of the MCP server begins with `getOrCreateMcpServer`, which guards against duplicate initialization by retaining a module-level `mcpServer` singleton reference. Upon first invocation, it instantiates an `McpServer` with the name `'Next.js MCP Server'` and version `'0.2.0'`, registering the foundational tools such as `get-project-metadata`, `get-errors`, `get-page-metadata`, `get-logs`, `get-server-action-by-id`, and `get-routes`. Turbopack-specific capabilities like `get-compilation-issues` and `compile-route` are conditionally attached when their corresponding options are supplied. 

Sources: [packages/next/src/server/mcp/get-or-create-mcp-server.ts:1-76](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L1-L76)

HTTP requests entering the dev server flow through `getMcpMiddleware`, which performs path filtering, connection cleanup, and request body parsing before handing the payload off to the MCP SDK transport layer.

```mermaid
sequenceDiagram
    participant Client as HTTP Client
    participant MW as getMcpMiddleware
    participant Factory as getOrCreateMcpServer
    participant Transport as StreamableHTTPServerTransport
    participant Server as McpServer

    Client->>MW: HTTP Request (/_next/mcp)
    MW->>MW: Verify pathname starts with /_next/mcp
    MW->>Factory: getOrCreateMcpServer(options)
    Factory-->>MW: McpServer singleton
    MW->>Transport: new StreamableHTTPServerTransport()
    MW->>Server: mcpServer.connect(transport)
    MW->>MW: parseBody(req, 1MB limit)
    MW->>Transport: transport.handleRequest(req, res, parsedBody)
    Transport-->>Client: JSON-RPC Response
    Note over MW,Transport: On connection close, transport.close() is invoked
```

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:9-44](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L9-L44)

### Middleware Execution Walkthrough

When an incoming HTTP request hits the Next.js development server, the middleware pipeline executes a precise sequence of checks and operations to handle JSON-RPC messaging.

1. `getMcpMiddleware` receives `req` (IncomingMessage), `res` (ServerResponse), and `next` (`() => void`). 

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:9-14](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L9-L14)

2. It parses the request URL and evaluates whether `pathname` starts with `/_next/mcp`. If it does not match, control immediately falls through by invoking `next()`. 

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:15-18](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L15-L18)

3. If the path matches, `getOrCreateMcpServer(options)` is called to retrieve or initialize the `McpServer` instance with its registered tools. 

Sources: [packages/next/src/server/mcp/get-or-create-mcp-server.ts:33-76](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L33-L76)

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:19-19](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L19-L19)

4. A new `StreamableHTTPServerTransport` is instantiated with `sessionIdGenerator: undefined`. 

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:20-22](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L20-L22)

5. A `'close'` listener is bound to the response object (`res`) to guarantee that `transport.close()` is invoked if the connection drops prematurely. 

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:23-26](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L23-L26)

6. `mcpServer.connect(transport)` establishes the session bridge, after which `parseBody(req, 1024 * 1024)` parses up to 1 megabyte of incoming JSON-RPC payload data. 

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:27-28](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L27-L28)

7. `transport.handleRequest(req, res, parsedBody)` processes the execution request. If an exception occurs and headers have not yet been sent, a `500` status code with a JSON-RPC formatted error object (`code: -32000`, message: `'Internal server error'`) is written to the response. 

Sources: [packages/next/src/server/mcp/get-mcp-middleware.ts:29-42](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-mcp-middleware.ts#L29-L42)

> [!NOTE]
> The `compile_route` tool and compilation issue subscriptions are exclusively available when running under Turbopack (`getTurbopackProject`). When initializing the MCP middleware inside the Webpack hot reloader, `compile_route` is intentionally omitted from the server options. 

Sources: [packages/next/src/server/dev/hot-reloader-turbopack.ts:1034-1047](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/hot-reloader-turbopack.ts#L1034-L1047)

Sources: [packages/next/src/server/dev/hot-reloader-webpack.ts:1681-1694](https://github.com/blade47/next.js/blob/main/packages/next/src/server/dev/hot-reloader-webpack.ts#L1681-L1694)

### Server Configuration Options

| Option Name | Type | Purpose | Sources |
| :--- | :--- | :--- | :--- |
| `projectPath` | `string` | Root filesystem path of the Next.js development project. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-16](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L16) |
| `distDir` | `string` | Distribution output directory path (e.g., `.next`). | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-17](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L17) |
| `nextConfig` | `NextConfigComplete` | Fully resolved Next.js configuration object. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-18](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L18) |
| `pagesDir` | `string \| undefined` | Absolute path to the legacy `pages` directory, if present. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-19](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L19) |
| `appDir` | `string \| undefined` | Absolute path to the App Router `app` directory, if present. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-20](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L20) |
| `sendHmrMessage` | `(message) => void` | Callback to broadcast HMR control messages to connected browser clients. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-21](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L21) |
| `getActiveConnectionCount` | `() => number` | Returns the total count of active browser HMR client connections. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-22](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L22) |
| `getDevServerUrl` | `() => string \| undefined` | Resolves the private origin URL of the running dev server instance. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-23](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L23) |
| `getTurbopackProject` | `() => Project \| undefined` | Accessor for the active Turbopack project reference. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-24](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L24) |
| `compileRoute` | `(opts) => Promise` | Turbopack-exclusive callback to trigger on-demand route compilation. | [packages/next/src/server/mcp/get-or-create-mcp-server.ts:15-29](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/get-or-create-mcp-server.ts#L15-L29) |

## Route Discovery and On-Demand Compilation

### Overview

The Model Context Protocol (MCP) server provides tools to discover entry routes across `app/` and `pages/` directories and trigger targeted on-demand route compilation without executing live HTTP requests. These capabilities allow clients to inspect application structure, warm module graphs, measure build latencies, and perform memory benchmarking. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:1-9](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L1-L9)

Sources: [packages/next/src/server/mcp/tools/get-routes.ts:1-14](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-routes.ts#L1-L14)

### Route Discovery via `get_routes`

The `get_routes` tool scans the project filesystem directly to locate all route files in the App Router and Pages Router directories, returning them grouped by router type. 

Sources: [packages/next/src/server/mcp/tools/get-routes.ts:1-10](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-routes.ts#L1-L10)

```mermaid
sequenceDiagram
    participant Client
    participant get_routes as registerGetRoutesTool
    participant Discovery as discoverRoutes
    Client->>get_routes: Call tool (optional routerType)
    get_routes->>get_routes: Validate pagesDir / appDir existence
    get_routes->>Discovery: Parallel scan (appDir, pagesDir)
    Discovery-->>get_routes: Return raw route definitions
    get_routes->>get_routes: Map, sort, and group results
    get_routes-->>Client: JSON response { appRouter, pagesRouter }
```

Sources: [packages/next/src/server/mcp/tools/get-routes.ts:30-146](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-routes.ts#L30-L146)

When invoked, the tool records telemetry via `mcpTelemetryTracker.recordToolCall('mcp/get_routes')`, validates that at least one directory exists, and independently executes `discoverRoutes` for both App and Pages routers in parallel to ensure a failure in one router does not block the other. 

Sources: [packages/next/src/server/mcp/tools/get-routes.ts:41-91](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-routes.ts#L41-L91)

> [!NOTE]
> Dynamic route segments are returned as defined in the filesystem (e.g., `[id]`, `[slug]`, ` [...slug]`). The `get_routes` tool does not expand `generateStaticParams` or dynamic parameters. 

Sources: [packages/next/src/server/mcp/tools/get-routes.ts:11-13](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-routes.ts#L11-L13)

### On-Demand Compilation via `compile_route`

The `compile_route` tool triggers on-demand compilation through the development server handler, simulating the code path executed when a user first visits a route. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:1-9](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L1-L9)

| Parameter Name | Type | Description | Sources |
| :--- | :--- | :--- | :--- |
| `routeSpecifier` | `string` (optional) | Resolved route specifier from `get_routes` (e.g., `"/"`, `"/blog/[slug]"`). Mutually exclusive with `path`. | [packages/next/src/server/mcp/tools/compile-route.ts:31-38](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L31-L38) |
| `path` | `string` (optional) | URL path on the site (e.g., `"/blog/hello-world"`). Query strings are ignored. Mutually exclusive with `routeSpecifier`. | [packages/next/src/server/mcp/tools/compile-route.ts:39-47](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L39-L47) |

Execution follows a strict validation and error-handling flow:
1. `mcpTelemetryTracker.recordToolCall('mcp/compile_route')` logs the tool invocation. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:50-51](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L50-L51)

2. The input validator checks exclusivity: exactly one of `routeSpecifier` or `path` must be provided, returning an error response if both or neither are supplied. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:53-65](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L53-L65)

3. `compileRoute({ routeSpecifier, path })` is awaited. On success, it returns `{ routeSpecifier, issues }`. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:67-80](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L67-L80)

4. If an exception occurs, the catch block inspects the error code; an `ENOENT` error returns `{ notFound: true, input }`, while general compilation failures return the serialized error message. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:81-99](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L81-L99)

> [!WARNING]
> Providing both `routeSpecifier` and `path`, or omitting both parameters entirely, results in an immediate `isError: true` JSON response requiring exactly one argument. 

Sources: [packages/next/src/server/mcp/tools/compile-route.ts:53-65](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/compile-route.ts#L53-L65)

## Compilation Issues and Development Logs

### Overview

The Model Context Protocol (MCP) server integrates tools for inspecting development diagnostics, specifically focusing on Turbopack compilation errors across all routes and locating the Next.js development log files. These capabilities allow an AI agent to proactively analyze codebases without requiring a live browser session. 

Sources: [packages/next/src/server/mcp/tools/get-compilation-issues.ts:1-9](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-compilation-issues.ts#L1-L9)

Sources: [packages/next/src/server/mcp/tools/get-logs.ts:1-6](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-logs.ts#L1-L6)

### Compilation Issues Tool

The `get_compilation_issues` tool builds the module graph for every application endpoint and collects diagnostics directly from Turbopack, covering module-not-found errors, syntax issues, and transform failures. 

Sources: [packages/next/src/server/mcp/tools/get-compilation-issues.ts:1-9](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-compilation-issues.ts#L1-L9)

```typescript
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),
              }),
            },
          ],
        }
      }
    }
  )
}
```

Sources: [packages/next/src/server/mcp/tools/get-compilation-issues.ts:15-70](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-compilation-issues.ts#L15-L70)

> [!NOTE]
> Unlike `get_errors`, which relies on an active browser session to reflect the runtime error overlay, `get_compilation_issues` evaluates all project routes proactively through Turbopack without opening a browser. 

Sources: [packages/next/src/server/mcp/tools/get-compilation-issues.ts:4-9](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-compilation-issues.ts#L4-L9)

### Development Log File Tool

The `get_logs` tool exposes the filesystem path to the Next.js development log file, enabling agents to read browser console logs and development events directly. 

Sources: [packages/next/src/server/mcp/tools/get-logs.ts:1-6](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-logs.ts#L1-L6)

```typescript
export function registerGetLogsTool(server: McpServer, distDir: string) {
  server.registerTool(
    'get_logs',
    {
      description:
        'Get the path to the Next.js development log file. Returns the file path so the agent can read the logs directly.',
    },
    async () => {
      // Track telemetry
      mcpTelemetryTracker.recordToolCall('mcp/get_logs')

      try {
        const logFilePath = join(distDir, 'logs', 'next-development.log')

        // Check if the log file exists
        try {
          await stat(logFilePath)
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  error: `Log file not found at ${logFilePath}.`,
                }),
              },
            ],
          }
        }

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                logFilePath,
              }),
            },
          ],
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                error: `Error getting log file path: ${error instanceof Error ? error.message : String(error)}`,
              }),
            },
          ],
        }
      }
    }
  )
}
```

Sources: [packages/next/src/server/mcp/tools/get-logs.ts:12-66](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-logs.ts#L12-L66)

> [!WARNING]
> If the development log file has not yet been initialized under `{nextConfig.distDir}/logs/next-development.log`, the tool catches the filesystem `stat` error and returns an explicit JSON error payload stating that the log file was not found. 

Sources: [packages/next/src/server/mcp/tools/get-logs.ts:26-40](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-logs.ts#L26-L40)

## Error State Collection and Formatting

### Overview

The error reporting and collection subsystem combines Next.js instance-level configuration validation errors, build errors, and browser runtime errors into structured output via the Model Context Protocol (MCP). The `get_errors` tool orchestrates error retrieval by checking active browser connections, dispatching bidirectional HMR communication requests, combining route-specific overlay states with global instance errors, and invoking source-mapped stack trace inspection. 

Sources: [packages/next/src/server/mcp/tools/get-errors.ts:1-15](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-errors.ts#L1-L15)

```typescript
export const NextInstanceErrorState: {
  nextConfig: unknown[]
} = {
  nextConfig: [],
}
```

Sources: [packages/next/src/server/mcp/tools/next-instance-error-state.ts:18-22](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/next-instance-error-state.ts#L18-L22)

> [!NOTE]
> `NextInstanceErrorState` captures global instance errors that are not associated with a specific browser session or route, such as validation errors within `next.config.js`. 

Sources: [packages/next/src/server/mcp/tools/next-instance-error-state.ts:1-7](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/next-instance-error-state.ts#L1-L7)

### Bidirectional Browser Overlay Error Synchronization

Retrieving runtime browser errors requires communication between the MCP server and connected browser sessions using Hot Module Replacement (HMR) messaging. The communication utility manages pending requests with unique identifiers, connection counts, and timeout handlers.

```typescript
export function createBrowserRequest<T>(
  messageType: HMR_MESSAGE_SENT_TO_BROWSER,
  sendHmrMessage: (message: HmrMessageSentToBrowser) => void,
  getActiveConnectionCount: () => number,
  timeoutMs: number
): Promise<BrowserResponse<T>[]> {
  const connectionCount = getActiveConnectionCount()
  if (connectionCount === 0) {
    return Promise.resolve([])
  }

  const requestId = `mcp-${messageType}-${nanoid()}`

  const responsePromise = new Promise<BrowserResponse<T>[]>(
    (resolve, reject) => {
      const timeout = setTimeout(() => {
        const pending = pendingRequests.get(requestId)
        if (pending && pending.responses.length > 0) {
          resolve(pending.responses as BrowserResponse<T>[])
        } else {
          reject(
            new Error(
              `Timeout waiting for response from frontend. The browser may not be responding to HMR messages.`
            )
          )
        }
        pendingRequests.delete(requestId)
      }, timeoutMs)

      pendingRequests.set(requestId, {
        responses: [],
        expectedCount: connectionCount,
        resolve: resolve as (value: BrowserResponse<unknown>[]) => void,
        reject,
        timeout,
      })
    }
  )

  sendHmrMessage({
    type: messageType,
    requestId,
  } as HmrMessageSentToBrowser)

  return responsePromise
}
```

Sources: [packages/next/src/server/mcp/tools/utils/browser-communication.ts:30-75](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/utils/browser-communication.ts#L30-L75)

The execution flow for gathering browser error state follows a precise sequence:
1. `get_errors` tool execution invokes `getActiveConnectionCount()` and records telemetry via `mcpTelemetryTracker.recordToolCall('mcp/get_errors')`. 

Sources: [packages/next/src/server/mcp/tools/get-errors.ts:44-61](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-errors.ts#L44-L61)

2. `createBrowserRequest()` generates a unique `requestId` prefixed with `mcp-`, registers a pending request entry mapped by ID, and initializes a timer for `DEFAULT_BROWSER_REQUEST_TIMEOUT_MS` (5000ms). 

Sources: [packages/next/src/server/mcp/tools/utils/browser-communication.ts:13-67](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/utils/browser-communication.ts#L13-L67)

3. `sendHmrMessage()` transmits the `HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE` message containing the `requestId` to the browser frontend. 

Sources: [packages/next/src/server/mcp/tools/get-errors.ts:63-68](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-errors.ts#L63-L68)

Sources: [packages/next/src/server/mcp/tools/utils/browser-communication.ts:69-74](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/utils/browser-communication.ts#L69-L74)

4. The browser responds via HMR, triggering `handleErrorStateResponse()` which invokes `handleBrowserPageResponse()`. 

Sources: [packages/next/src/server/mcp/tools/get-errors.ts:130-140](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-errors.ts#L130-L140)

5. `handleBrowserPageResponse()` pushes the received error state and URL into the pending request's responses array. Once `responses.length >= expectedCount`, it clears the timeout, resolves the promise, and purges the pending map entry. 

Sources: [packages/next/src/server/mcp/tools/utils/browser-communication.ts:77-97](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/utils/browser-communication.ts#L77-L97)

> [!WARNING]
> If zero browser connections are active when `get_errors` runs, the tool returns an immediate JSON message instructing the user to open the application in a browser, bypassing the HMR request step entirely. 

Sources: [packages/next/src/server/mcp/tools/get-errors.ts:48-61](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-errors.ts#L48-L61)

### Source-Mapped Stack Frame Inspection and Error Patching

To make stack traces readable during debugging, Next.js patches error inspection routines for Node.js (`patchErrorInspectNodeJS`) and Edge Lite (`patchErrorInspectEdgeLite`) runtimes. Stack frames are parsed, mapped back to original source files via source map consumers, and cleaned up by ignoring framework or Node internal frames.

```typescript
export function patchErrorInspectNodeJS(
  errorConstructor: ErrorConstructor
): void {
  const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')

  errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace

  // @ts-expect-error -- TODO upstream types
  errorConstructor.prototype[inspectSymbol] = function (
    depth: number,
    inspectOptions: util.InspectOptions,
    inspect: typeof util.inspect
  ): string {
    // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.
    return workUnitAsyncStorage.exit(() => {
      const newError = sourceMapError(this, inspectOptions)

      const originalCustomInspect = (newError as any)[inspectSymbol]
      // Prevent infinite recursion.
      // { customInspect: false } would result in `error.cause` not using our inspect.
      Object.defineProperty(newError, inspectSymbol, {
        value: undefined,
        enumerable: false,
        writable: true,
      })
      try {
        return inspect(newError, {
          ...inspectOptions,
          depth,
        })
      } finally {
        ;(newError as any)[inspectSymbol] = originalCustomInspect
      }
    })
  }
}
```

Sources: [packages/next/src/server/patch-error-inspect.ts:499-534](https://github.com/blade47/next.js/blob/main/packages/next/src/server/patch-error-inspect.ts#L499-L534)

| Error Inspect Function | Runtime Environment | Custom Inspect Symbol | Behavior on Error Customization | Sources |
| :--- | :--- | :--- | :--- | :--- |
| `patchErrorInspectNodeJS` | Node.js | `Symbol.for('nodejs.util.inspect.custom')` | Exits workUnitAsyncStorage, maps source stack, strips custom inspect symbol, and invokes util.inspect. | [packages/next/src/server/patch-error-inspect.ts:499-534](https://github.com/blade47/next.js/blob/main/packages/next/src/server/patch-error-inspect.ts#L499-L534) |
| `patchErrorInspectEdgeLite` | Edge Lite | `Symbol.for('edge-runtime.inspect.custom')` | Exits workUnitAsyncStorage, maps source stack, strips custom inspect symbol, and formats via edge formatter. | [packages/next/src/server/patch-error-inspect.ts:536-567](https://github.com/blade47/next.js/blob/main/packages/next/src/server/patch-error-inspect.ts#L536-L567) |

> [!CAUTION]
> Both error patching functions execute inside `workUnitAsyncStorage.exit()` to prevent false-positive dynamic I/O warnings caused by internal dependencies such as random number generation in the `source-map` library. 

Sources: [packages/next/src/server/patch-error-inspect.ts:512-514](https://github.com/blade47/next.js/blob/main/packages/next/src/server/patch-error-inspect.ts#L512-L514)

Sources: [packages/next/src/server/patch-error-inspect.ts:549-551](https://github.com/blade47/next.js/blob/main/packages/next/src/server/patch-error-inspect.ts#L549-L551)

## Page Metadata and Action Introspection

### Overview

Next.js Model Context Protocol (MCP) tooling exposes runtime page segment trees, absolute project filepaths, developer server URLs, and Server Action mappings by communicating directly with active browser sessions and reading internal build manifests. This introspection layer enables AI assistants and debugging clients to examine the live structure of an application without manual DOM inspection or guesswork.

Sources: [packages/next/src/server/mcp/tools/get-page-metadata.ts:24-30](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts#L24-L30)

Sources: [packages/next/src/server/mcp/tools/get-project-metadata.ts:9-15](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-project-metadata.ts#L9-L15)

Sources: [packages/next/src/server/mcp/tools/get-server-action-by-id.ts:22-31](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-server-action-by-id.ts#L22-L31)

### Runtime Page Metadata and Segment Traversal

The `get_page_metadata` tool queries connected browser sessions for runtime page segment data via WebSocket communication. When invoked, it checks active client connections, issues an `HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA` payload, converts the returned trie into structured page segments, and formats the metadata grouped by session URL and router type.

```typescript
export function registerGetPageMetadataTool(
  server: McpServer,
  sendHmrMessage: (message: HmrMessageSentToBrowser) => void,
  getActiveConnectionCount: () => number
) {
  server.registerTool(
    'get_page_metadata',
    {
      description:
        'Get runtime metadata about what contributes to the current page render from active browser sessions.',
      inputSchema: {},
    },
    async (_request) => {
      // Track telemetry
      mcpTelemetryTracker.recordToolCall('mcp/get_page_metadata')

      try {
        const connectionCount = getActiveConnectionCount()
        if (connectionCount === 0) {
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  error:
                    'No browser sessions connected. Please open your application in a browser to retrieve page metadata.',
                }),
              },
            ],
          }
        }

        const responses = await createBrowserRequest<SegmentTrieData>(
          HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA,
          sendHmrMessage,
          getActiveConnectionCount,
          DEFAULT_BROWSER_REQUEST_TIMEOUT_MS
        )
        // ... conversion and formatting
```

Sources: [packages/next/src/server/mcp/tools/get-page-metadata.ts:19-56](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts#L19-L56)

During trie conversion, `convertSegmentTrieToPageMetadata` traverses the segment tree recursively. Nodes containing a value push a `PageSegment` record containing the node's `type`, `pagePath`, and `boundaryType` into the output array before visiting child nodes.

```typescript
function convertSegmentTrieToPageMetadata(data: SegmentTrieData): PageMetadata {
  const segments: PageSegment[] = []

  if (data.segmentTrie) {
    // Traverse the trie and collect all segments
    function traverseTrie(node: SegmentTrieNode): void {
      if (node.value) {
        segments.push({
          type: node.value.type,
          pagePath: node.value.pagePath,
          boundaryType: node.value.boundaryType,
        })
      }

      for (const childNode of Object.values(node.children)) {
        if (childNode) {
          traverseTrie(childNode)
        }
      }
    }

    traverseTrie(data.segmentTrie)
  }

  return {
    segments,
    routerType: data.routerType,
  }
}
```

Sources: [packages/next/src/server/mcp/tools/get-page-metadata.ts:132-160](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts#L132-L160)

> [!WARNING]
> If `getActiveConnectionCount()` returns `0`, `get_page_metadata` immediately returns an error JSON object without attempting browser communication. Users must open the application in a browser session to populate active connections. 

Sources: [packages/next/src/server/mcp/tools/get-page-metadata.ts:36-49](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts#L36-L49)

### Project Metadata and Server Action Resolution

The `get_project_metadata` tool evaluates project path availability and dev server URLs, returning absolute paths and endpoints for MCP clients. Complementing this, `get_server_action_by_id` inspects compiled build output to locate Server Actions by their unique string identifier within `server-reference-manifest.json`.

```typescript
export function registerGetActionByIdTool(server: McpServer, distDir: string) {
  server.registerTool(
    'get_server_action_by_id',
    {
      description:
        'Locates a Server Action by its ID in the server-reference-manifest.json. Returns the filename and export name for the action.',
      inputSchema: {
        actionId: z.string(),
      },
    },
    async (request) => {
      // Track telemetry
      mcpTelemetryTracker.recordToolCall('mcp/get_server_action_by_id')

      try {
        const { actionId } = request

        if (!actionId) {
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  error: 'actionId parameter is required',
                }),
              },
            ],
          }
        }

        const manifestPath = join(
          distDir,
          'server',
          'server-reference-manifest.json'
        )
```

Sources: [packages/next/src/server/mcp/tools/get-server-action-by-id.ts:22-56](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-server-action-by-id.ts#L22-L56)

When an action ID is supplied, the tool parses both `node` and `edge` records inside the server reference manifest. If an exported name starts with the inline action prefix `$$RSC_SERVER_ACTION_`, the returned function name is reported as `'inline server action'`; otherwise, the actual export name is preserved.

```typescript
        const manifest: ServerReferenceManifest = JSON.parse(manifestContent)

        // Search in node entries
        if (manifest.node && manifest.node[actionId]) {
          const entry = manifest.node[actionId]
          const isInlineAction =
            entry.exportedName.startsWith(INLINE_ACTION_PREFIX)
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(
                  {
                    actionId,
                    runtime: 'node',
                    filename: entry.filename,
                    functionName: isInlineAction
                      ? 'inline server action'
                      : entry.exportedName,
                    layer: entry.layer,
                    workers: entry.workers,
                  },
                  null,
                  2
                ),
              },
            ],
          }
        }
```

Sources: [packages/next/src/server/mcp/tools/get-server-action-by-id.ts:74-102](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-server-action-by-id.ts#L74-L102)

| MCP Introspection Tool | Input Schema | Target Artifact / Source | Returned Properties / Details | Sources |
| :--- | :--- | :--- | :--- | :--- |
| `get_project_metadata` | `{}` | Runtime project state | `projectPath`, `devServerUrl`, or `error`. | [packages/next/src/server/mcp/tools/get-project-metadata.ts:11-45](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-project-metadata.ts#L11-L45) |
| `get_page_metadata` | `{}` | Connected browser sessions via HMR | `sessions` array containing session `url`, `routerType`, and sorted `segments`. | [packages/next/src/server/mcp/tools/get-page-metadata.ts:26-103](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts#L26-L103) |
| `get_server_action_by_id` | `{ actionId: string }` | `distDir/server/server-reference-manifest.json` | `actionId`, `runtime` (`node` or `edge`), `filename`, `functionName`, `layer`, and `workers`. | [packages/next/src/server/mcp/tools/get-server-action-by-id.ts:28-56](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-server-action-by-id.ts#L28-L56) |

> [!TIP]
> Segment sorting in `formatPageMetadata` prioritizes layout segments (`0`), boundary types (`1`), page segments (`2`), and fallback types (`3`), with tie-breaking handled alphabetically via `localeCompare` on `pagePath`. 

Sources: [packages/next/src/server/mcp/tools/get-page-metadata.ts:194-206](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/tools/get-page-metadata.ts#L194-L206)

## Tool Telemetry and Trace Server

### Overview

The MCP telemetry and trace server infrastructure records tool call invocation metrics and exposes native Turbopack profiling spans via an integrated Model Context Protocol server. The telemetry tracker manages an in-memory usage map associating each feature name with its execution count, which can be flushed and recorded through standard telemetry events.

```typescript
class McpTelemetryTracker {
  private usageMap = new Map<McpToolName, number>()

  recordToolCall(toolName: McpToolName): void {
    const current = this.usageMap.get(toolName) || 0
    this.usageMap.set(toolName, current + 1)
  }

  getUsages(): McpToolUsage[] {
    return Array.from(this.usageMap.entries()).map(([featureName, count]) => ({
      featureName,
      invocationCount: count,
    }))
  }

  reset(): void {
    this.usageMap.clear()
  }

  hasUsage(): boolean {
    return this.usageMap.size > 0
  }
}

export const mcpTelemetryTracker = new McpTelemetryTracker()
```

Sources: [packages/next/src/server/mcp/mcp-telemetry-tracker.ts:13-50](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/mcp-telemetry-tracker.ts#L13-L50)

> [!NOTE]
> When `recordMcpTelemetry` is called with a telemetry instance, it retrieves active tool usages via `getMcpTelemetryUsage()`, loads the build telemetry events module dynamically, and iterates through generated events to record each invocation count. 

Sources: [packages/next/src/server/mcp/mcp-telemetry-tracker.ts:69-83](https://github.com/blade47/next.js/blob/main/packages/next/src/server/mcp/mcp-telemetry-tracker.ts#L69-L83)

### Trace Server CLI and Query Engine

The Turbopack trace server CLI (`startTurboTraceServerCli`) loads native SWC bindings, starts a background trace server handle on a WebSocket port, and sets up an MCP server instance registered with the `query_spans` tool.

```typescript
export async function startTurboTraceServerCli(
  file: string,
  port: number | undefined,
  mcpPort: number | undefined
) {
  const wsPort = port ?? DEFAULT_WS_PORT
  const httpPort = mcpPort ?? wsPort + 1

  let bindings = await loadBindings()
  let handle = bindings.turbo.startTurbopackTraceServerHandle(file, wsPort)

  const mcpServer = new McpServer({
    name: 'Next.js Trace Server MCP',
    version: '0.1.0',
  })

  mcpServer.registerTool(
    'query_spans',
    {
      description: 'Query spans from a turbopack trace file...',
      inputSchema: {
        parent: z.string().optional(),
        aggregated: z.boolean().optional(),
        sort: z.enum(['value', 'name']).optional(),
        search: z.string().optional(),
        page: z.number().optional(),
        outputType: z.enum(['markdown', 'json']).optional(),
      },
    },
    (args) => {
      const result = bindings.turbo.queryTraceSpans(handle, {
        parent: args.parent,
        aggregated: args.aggregated ?? true,
        sort: args.sort,
        search: args.search,
        page: args.page ?? 1,
      })
      // Returns spans, page, totalPages, and totalCount
    }
  )
}
```

Sources: [packages/next/src/cli/internal/turbo-trace-server.ts:114-233](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L114-L233)

Client interactions with the trace server are mediated by the `queryTraceCli` utility, which constructs a JSON-RPC request targeting the `/mcp` HTTP endpoint and parses Server-Sent Events (SSE) data streams to extract response text.

```typescript
export async function queryTraceCli(options: QueryTraceOptions): Promise<void> {
  const port = options.port ?? DEFAULT_MCP_PORT

  const args: Record<string, unknown> = {}
  if (options.parent !== undefined) args.parent = options.parent
  if (options.aggregated !== undefined) args.aggregated = options.aggregated
  if (options.sort !== undefined) args.sort = options.sort
  if (options.search !== undefined) args.search = options.search
  if (options.page !== undefined) args.page = options.page
  if (options.json) args.outputType = 'json'

  const requestBody = JSON.stringify({
    jsonrpc: '2.0',
    method: 'tools/call',
    params: {
      name: 'query_spans',
      arguments: args,
    },
    id: 1,
  })

  const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json, text/event-stream',
    },
    body: requestBody,
  })

  const body = await res.text()
  for (const line of body.split('\n')) {
    if (!line.startsWith('data: ')) continue
    const msg = JSON.parse(line.slice('data: '.length))
    const text = msg.result?.content?.find((c) => c.type === 'text')?.text
    if (text !== undefined) {
      process.stdout.write(text)
      return
    }
  }
}
```

Sources: [packages/next/src/cli/internal/query-trace.ts:21-102](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/query-trace.ts#L21-L102)

### Query Parameters and Telemetry Reference

| Parameter / Field | Type | Default Value | Description / Purpose | Sources |
| :--- | :--- | :--- | :--- | :--- |
| `parent` | `string` (Zod) | `undefined` | Span ID to enumerate children of; omit for root-level spans. | [packages/next/src/cli/internal/turbo-trace-server.ts:159-164](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L159-L164) |
| `aggregated` | `boolean` (Zod) | `true` | Aggregate spans with the same name into a single entry when true. | [packages/next/src/cli/internal/turbo-trace-server.ts:165-170](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L165-L170) |
| `sort` | `enum` (`value`, `name`) | `undefined` | Sort mode: `"value"` for corrected duration descending, `"name"` for alphabetical. | [packages/next/src/cli/internal/turbo-trace-server.ts:171-176](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L171-L176) |
| `search` | `string` (Zod) | `undefined` | Substring search query applied to span name and category. | [packages/next/src/cli/internal/turbo-trace-server.ts:177-182](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L177-L182) |
| `page` | `number` (Zod) | `1` | 1-based page number for paginated results (20 spans per page). | [packages/next/src/cli/internal/turbo-trace-server.ts:157](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L157), [packages/next/src/cli/internal/turbo-trace-server.ts:183-183](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L183-L183) |
| `outputType` | `enum` (`markdown`, `json`) | `'markdown'` | Output format: human-readable markdown or structured JSON with raw memory samples. | [packages/next/src/cli/internal/turbo-trace-server.ts:157](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L157), [packages/next/src/cli/internal/turbo-trace-server.ts:184-189](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/turbo-trace-server.ts#L184-L189) |

## Related

- [Dev Server and HMR](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development-and-diagnostics/dev-server-and-hmr)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/llms.txt) for all pages in this wiki.
