Unverified Commit 5ff5ae21 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

feat(trace-server): add query CLI and MCP API to turbopack-trace-server (#92030)

### What?

Adds a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/)
HTTP server and a companion CLI to the Turbopack trace server (`next
internal trace`), so AI agents and developers can explore trace data
from a build or dev session incrementally through a structured tool API.

Two new user-facing features:

1. **`--mcp-port` flag on `next internal trace`** — starts an
MCP-over-HTTP endpoint (at `/mcp`) alongside the existing WebSocket
trace viewer.
2. **`next internal query-trace`** — a standalone CLI command that
queries a running trace server from the terminal, using the same MCP
endpoint under the hood.

### Why?

Trace files from Turbopack builds can be very large. An agent querying
raw trace data would be overwhelmed by tens of thousands of spans. The
MCP API exposes the data incrementally:

- **Pagination** (20 spans per page) prevents context overflow.
- **Aggregation** groups repeated spans by name (same logic as the
WebSocket viewer's graph), so agents see one entry per span type with
count/total/avg statistics rather than thousands of identical entries.
- **Drill-down** lets agents pick a span ID from one response and fetch
its children in the next call.
- **Search** filters spans by name/args using `SpanRef::search` (full
subtree search index, same as the WebSocket viewer).
- **Sort** orders by corrected (wall-clock) duration to surface the
slowest spans first.
- **Output format** — `outputType: "json"` for machine-readable
structured data, `"markdown"` (default) for human-readable rendering.

### How?

#### Rust (`turbopack/crates/turbopack-trace-server/src/lib.rs`)

- `start_turbopack_trace_server_non_blocking(path, port) ->
Arc<StoreContainer>` — starts the reader and WebSocket server on
background threads and returns the store handle immediately (previously
the function blocked forever).
- `QueryOptions` — struct with `parent`, `aggregated`, `sort`, `search`,
`page` fields.
- `query_spans(store, opts) -> QueryResult` — queries up to 20 spans per
page. In aggregated mode it uses the existing `SpanGraphRef` graph logic
(the same grouping the WebSocket viewer uses). Waits up to 10s for the
store to finish initial data loading on the first call.
- Helper functions extracted: `paginate()`, `format_span_name()`,
`build_span_id()` to avoid duplication between aggregated and raw code
paths.

#### Span ID format

IDs encode both the span type and the navigation path:

| Span kind | Leaf format | Example full path |
|---|---|---|
| Raw span | `<index>` (decimal) | `a1-a5-20` |
| Aggregated span | `a<first-span-index>` | `a1-a5-a34` |

Segments are joined by `-` as the caller drills deeper.
`resolve_span_by_id` only needs the last segment to look up the
underlying store index.

#### NAPI bridge (`crates/next-napi-bindings/src/turbo_trace_server.rs`)

- `TraceServerHandle` — opaque NAPI class wrapping
`Arc<StoreContainer>`.
- `startTurbopackTraceServerHandle(path, port)` — calls the non-blocking
Rust function.
- `queryTraceSpans(handle, options)` — calls `query_spans` and returns a
plain JS object.
- Doc comments on `SpanInfo` fields clarify that
`cpu_duration`/`corrected_duration` hold the first example span's values
for aggregated groups (while `total_*` fields hold group totals).

#### TypeScript (`packages/next/src/...`)

- `generated-native.d.ts` / `types.ts` / `index.ts` — type declarations,
native wrappers, and WASM stubs.
- `next.ts` — adds `--mcp-port <port>` to `next internal trace`
(defaults to `5748`); registers `next internal query-trace` subcommand
with `--json` flag.
- `turbo-trace-server.ts` — rewrites the CLI handler to:
1. Start the WebSocket trace viewer server non-blocking (was blocking).
2. Start an HTTP server at `/mcp` running MCP
`StreamableHTTPServerTransport` (stateless — one transport per request,
`sessionIdGenerator: undefined`).
3. `renderSpanMarkdown()` — extracted helper that renders a single span
as markdown.
4. Error handling: `server.on('error')` for `EADDRINUSE`, `try/catch`
around `loadBindings()` and `startTurbopackTraceServerHandle()`.
- `query-trace.ts` — new CLI command that POSTs JSON-RPC to the MCP
endpoint and prints the response. On connection failure, shows
instructions to start `next internal trace` first. Supports `--json`
flag for structured output.

#### `next internal query-trace` CLI

```
Usage: next internal query-trace [options]

Options:
  --port <port>      MCP port of the running trace server. Defaults to 5748.
  --parent <parent>  Span ID to enumerate children of. Omit for root level.
  --no-aggregated    Disable aggregation of spans by name (aggregated by default).
  --sort             Sort results by corrected duration descending (default: false).
  --search <search>  Substring filter on span name/category.
  --json             Output as JSON instead of markdown.
  --page <page>      Page number (1-based, default 1).
  -h, --help         Displays this message.
```

#### Startup output

When `next internal trace` starts with `--mcp-port`:

```
Turbopack trace server started. View trace at https://trace.nextjs.org?port=5747
Query this trace from the command line: next internal query-trace --help
Alternatively, connect an MCP client to http://127.0.0.1:5748/mcp
```

#### Markdown output format (per span)

```markdown
### `<name>` (ID: `<id>`)
- CPU Duration: …
- Corrected Duration: …
- Start (relative to parent): …
- End (relative to parent): …

**Attributes:**
- `key`: value
```

For aggregated spans with count > 1, totals and averages are shown
first, then one example span's raw data.

### Tests

**E2E test
(`test/e2e/turbopack-trace-server-query/turbopack-trace-server.test.ts`)**

Uses `nextTestSetup` with `env: { NEXT_TURBOPACK_TRACING: '1' }` to
produce a real trace file. Spawns `next internal trace <file> --mcp-port
<port>`, waits for the MCP server to be ready, then runs both MCP HTTP
and CLI queries:

- Root listing (markdown format)
- Aggregation mode
- Pagination
- Drill-down by span ID (using JSON output to extract IDs)
- Search with a real span name match and a non-matching term
- Sort by duration
- JSON output format (`outputType: 'json'`)
- CLI: `--sort`, `--search`, `--no-aggregated`, `--parent`, `--json`
- Error path: connection failure message with instructions

Turbopack-only (skips via `if (!isTurbopack) return` at describe level).
The error-path test runs regardless of bundler.

### Usage

```bash
# Build with tracing
NEXT_TURBOPACK_TRACING=1 next build

# Start the trace viewer + MCP server
next internal trace .next-profiles/trace-turbopack --mcp-port 5748

# Query from CLI
next internal query-trace --sort
next internal query-trace --parent a1 --sort
next internal query-trace --search "turbo_tasks::function" --page 2
next internal query-trace --no-aggregated
next internal query-trace --json

# Or connect an MCP client to http://127.0.0.1:5748/mcp
```

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 26b87589
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
dist dist
!.github/actions/*/dist !.github/actions/*/dist
.next .next
.next-profiles
target target
packages/next/wasm/@next packages/next/wasm/@next
tarballs/ tarballs/
......
use std::path::PathBuf; use std::{path::PathBuf, sync::Arc};
use napi_derive::napi; use napi_derive::napi;
use turbopack_trace_server::{
QueryOptions, query_spans, start_turbopack_trace_server, store_container::StoreContainer,
};
/// An opaque handle to a running trace server instance.
/// Holds a reference to the shared store so that `query_trace_spans` can
/// query it without blocking Node.js with the WebSocket server loop.
#[napi] #[napi]
pub fn start_turbopack_trace_server(path: String, port: Option<u16>) { pub struct TraceServerHandle {
let path_buf = PathBuf::from(path); store: Arc<StoreContainer>,
turbopack_trace_server::start_turbopack_trace_server(path_buf, port); }
/// Options for `query_trace_spans`.
#[napi(object)]
pub struct TraceQueryOptions {
/// Optional parent span ID (as returned by a previous query).
/// Omit or set to `null`/`undefined` for root-level spans.
pub parent: Option<String>,
/// When `true` (default), aggregate child spans with the same name.
pub aggregated: Option<bool>,
/// When `true`, sort results by corrected duration descending. Default `false`.
pub sort: Option<bool>,
/// Optional substring search query applied to span name/category.
pub search: Option<String>,
/// 1-based page number. Default `1`.
pub page: Option<u32>,
}
/// Information about a single span or aggregated span group.
#[napi(object)]
pub struct TraceSpanInfo {
/// Span ID. Pass this as `parent` in a follow-up call to get children.
pub id: String,
/// Display name of the span.
pub name: String,
/// Raw CPU total time in internal ticks (100 ticks = 1 µs).
pub cpu_duration: i64,
/// Concurrency-corrected total time in internal ticks (100 ticks = 1 µs).
pub corrected_duration: i64,
/// Start time relative to parent start, in internal ticks.
pub start_relative_to_parent: i64,
/// End time relative to parent start, in internal ticks.
pub end_relative_to_parent: i64,
/// Key-value attributes attached to the span.
pub args: Vec<Vec<String>>,
/// True if this entry represents an aggregated group of spans.
pub is_aggregated: bool,
/// Number of spans in this aggregated group (only set when `is_aggregated`).
pub count: Option<i64>,
/// Sum of CPU duration across all spans in the group.
pub total_cpu_duration: Option<i64>,
/// Average CPU duration across spans in the group.
pub avg_cpu_duration: Option<i64>,
/// Sum of corrected duration across all spans in the group.
pub total_corrected_duration: Option<i64>,
/// Average corrected duration across spans in the group.
pub avg_corrected_duration: Option<i64>,
/// Raw span ID for aggregated groups (the index of the first span).
pub first_span_id: Option<String>,
}
/// The result of a `query_trace_spans` call.
#[napi(object)]
pub struct TraceQueryResult {
pub spans: Vec<TraceSpanInfo>,
/// Current page (1-based).
pub page: u32,
/// Total number of pages available.
pub total_pages: u32,
/// Total number of matching spans across all pages.
pub total_count: u32,
}
/// Starts the turbopack trace server on a background thread and returns a
/// handle immediately (non-blocking). The WebSocket server will be available
/// at `ws://127.0.0.1:<port>` (default port 5747).
#[napi]
pub fn start_turbopack_trace_server_handle(path: String, port: Option<u16>) -> TraceServerHandle {
let store = start_turbopack_trace_server(PathBuf::from(path), port);
TraceServerHandle { store }
}
/// Query spans from the trace store held by a `TraceServerHandle`.
#[napi]
pub fn query_trace_spans(
handle: &TraceServerHandle,
options: TraceQueryOptions,
) -> TraceQueryResult {
let result = query_spans(
&handle.store,
QueryOptions {
parent: options.parent,
aggregated: options.aggregated.unwrap_or(true),
sort: options.sort.unwrap_or(false),
search: options.search,
page: options.page.unwrap_or(1) as usize,
},
);
TraceQueryResult {
spans: result
.spans
.into_iter()
.map(|s| TraceSpanInfo {
id: s.id,
name: s.name,
cpu_duration: s.cpu_duration as i64,
corrected_duration: s.corrected_duration as i64,
start_relative_to_parent: s.start_relative_to_parent,
end_relative_to_parent: s.end_relative_to_parent,
args: s.args.into_iter().map(|(k, v)| vec![k, v]).collect(),
is_aggregated: s.is_aggregated,
count: s.count.map(|c| c as i64),
total_cpu_duration: s.total_cpu_duration.map(|v| v as i64),
avg_cpu_duration: s.avg_cpu_duration.map(|v| v as i64),
total_corrected_duration: s.total_corrected_duration.map(|v| v as i64),
avg_corrected_duration: s.avg_corrected_duration.map(|v| v as i64),
first_span_id: s.first_span_id,
})
.collect(),
page: result.page as u32,
total_pages: result.total_pages as u32,
total_count: result.total_count as u32,
}
} }
...@@ -601,11 +601,66 @@ internal ...@@ -601,11 +601,66 @@ internal
parseValidPositiveInteger parseValidPositiveInteger
) )
) )
.action((file: string, options: { port: number | undefined }) => { .addOption(
new Option(
'--mcp-port <mcpPort>',
'Port for the MCP (Model Context Protocol) server. Defaults to 5748.'
).argParser(parseValidPositiveInteger)
)
.action(
(
file: string,
options: { port: number | undefined; mcpPort: number | undefined }
) => {
return import('../cli/internal/turbo-trace-server.js').then((mod) => return import('../cli/internal/turbo-trace-server.js').then((mod) =>
mod.startTurboTraceServerCli(file, options.port) mod.startTurboTraceServerCli(file, options.port, options.mcpPort)
)
}
)
internal
.command('query-trace')
.description(
'Query a running turbopack trace server (started with `next internal trace --mcp-port <port>`).'
)
.addOption(
new Option(
'--port <port>',
'MCP port of the running trace server. Defaults to 5748.'
).argParser(parseValidPositiveInteger)
)
.addOption(
new Option(
'--parent <parent>',
'Span ID to enumerate children of. Omit for root level.'
)
)
.addOption(
new Option(
'--no-aggregated',
'Disable aggregation of spans by name (aggregated by default).'
)
)
.addOption(
new Option(
'--sort',
'Sort results by corrected duration descending (default: false).'
)
)
.addOption(
new Option('--search <search>', 'Substring filter on span name/category.')
)
.addOption(new Option('--json', 'Output as JSON instead of markdown.'))
.addOption(
new Option('--page <page>', 'Page number (1-based, default 1).').argParser(
parseValidPositiveInteger
)
)
.action((options) =>
import('../cli/internal/query-trace.js').then((mod) =>
mod.queryTraceCli(options)
)
) )
})
internal internal
.command('post-build') .command('post-build')
......
...@@ -615,10 +615,77 @@ export declare function transformSync( ...@@ -615,10 +615,77 @@ export declare function transformSync(
isModule: boolean, isModule: boolean,
options: Buffer options: Buffer
): object ): object
export declare function startTurbopackTraceServer( /** Options for `query_trace_spans`. */
export interface TraceQueryOptions {
/**
* Optional parent span ID (as returned by a previous query).
* Omit or set to `null`/`undefined` for root-level spans.
*/
parent?: string
/** When `true` (default), aggregate child spans with the same name. */
aggregated?: boolean
/** When `true`, sort results by corrected duration descending. Default `false`. */
sort?: boolean
/** Optional substring search query applied to span name/category. */
search?: string
/** 1-based page number. Default `1`. */
page?: number
}
/** Information about a single span or aggregated span group. */
export interface TraceSpanInfo {
/** Span ID. Pass this as `parent` in a follow-up call to get children. */
id: string
/** Display name of the span. */
name: string
/** Raw CPU total time in internal ticks (100 ticks = 1 µs). */
cpuDuration: number
/** Concurrency-corrected total time in internal ticks (100 ticks = 1 µs). */
correctedDuration: number
/** Start time relative to parent start, in internal ticks. */
startRelativeToParent: number
/** End time relative to parent start, in internal ticks. */
endRelativeToParent: number
/** Key-value attributes attached to the span. */
args: Array<Array<string>>
/** True if this entry represents an aggregated group of spans. */
isAggregated: boolean
/** Number of spans in this aggregated group (only set when `is_aggregated`). */
count?: number
/** Sum of CPU duration across all spans in the group. */
totalCpuDuration?: number
/** Average CPU duration across spans in the group. */
avgCpuDuration?: number
/** Sum of corrected duration across all spans in the group. */
totalCorrectedDuration?: number
/** Average corrected duration across spans in the group. */
avgCorrectedDuration?: number
/** Raw span ID for aggregated groups (the index of the first span). */
firstSpanId?: string
}
/** The result of a `query_trace_spans` call. */
export interface TraceQueryResult {
spans: Array<TraceSpanInfo>
/** Current page (1-based). */
page: number
/** Total number of pages available. */
totalPages: number
/** Total number of matching spans across all pages. */
totalCount: number
}
/**
* Starts the turbopack trace server on a background thread and returns a
* handle immediately (non-blocking). The WebSocket server will be available
* at `ws://127.0.0.1:<port>` (default port 5747).
*/
export declare function startTurbopackTraceServerHandle(
path: string, path: string,
port?: number | undefined | null port?: number | undefined | null
): void ): TraceServerHandle
/** Query spans from the trace store held by a `TraceServerHandle`. */
export declare function queryTraceSpans(
handle: TraceServerHandle,
options: TraceQueryOptions
): TraceQueryResult
export interface NextBuildContext { export interface NextBuildContext {
/** The root directory of the workspace. */ /** The root directory of the workspace. */
root?: string root?: string
...@@ -667,3 +734,9 @@ export declare function initCustomTraceSubscriber( ...@@ -667,3 +734,9 @@ export declare function initCustomTraceSubscriber(
export declare function teardownTraceSubscriber( export declare function teardownTraceSubscriber(
guardExternal: ExternalObject<RefCell> guardExternal: ExternalObject<RefCell>
): void ): void
/**
* An opaque handle to a running trace server instance.
* Holds a reference to the shared store so that `query_trace_spans` can
* query it without blocking Node.js with the WebSocket server loop.
*/
export declare class TraceServerHandle {}
...@@ -1395,10 +1395,16 @@ async function loadWasm(importPath = '') { ...@@ -1395,10 +1395,16 @@ async function loadWasm(importPath = '') {
`Use the --webpack flag instead.` `Use the --webpack flag instead.`
) )
}, },
startTurbopackTraceServer( startTurbopackTraceServerHandle(
_traceFilePath: string, _traceFilePath: string,
_port: number | undefined _port: number | undefined
): void { ) {
throw new Error(
`Turbopack trace server is not supported on this platform (${PlatformName}/${ArchName}) because native bindings are not available. ` +
`Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.`
)
},
queryTraceSpans(_handle: any, _options: any) {
throw new Error( throw new Error(
`Turbopack trace server is not supported on this platform (${PlatformName}/${ArchName}) because native bindings are not available. ` + `Turbopack trace server is not supported on this platform (${PlatformName}/${ArchName}) because native bindings are not available. ` +
`Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.` `Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.`
...@@ -1644,15 +1650,15 @@ function loadNative(importPath?: string): Binding { ...@@ -1644,15 +1650,15 @@ function loadNative(importPath?: string): Binding {
customBindingsPath ?? bindingsPath!, customBindingsPath ?? bindingsPath!,
false false
), ),
startTurbopackTraceServer(traceFilePath, port) { startTurbopackTraceServerHandle(traceFilePath, port) {
Log.warn( return (customBindings ?? bindings).startTurbopackTraceServerHandle(
`Turbopack trace server started. View trace at https://trace.nextjs.org${port != null ? `?port=${port}` : ''}`
)
;(customBindings ?? bindings).startTurbopackTraceServer(
traceFilePath, traceFilePath,
port port
) )
}, },
queryTraceSpans(handle, options) {
return (customBindings ?? bindings).queryTraceSpans(handle, options)
},
databaseCompact(dbPath: string) { databaseCompact(dbPath: string) {
return (customBindings ?? bindings).turbopackDatabaseCompact(dbPath) return (customBindings ?? bindings).turbopackDatabaseCompact(dbPath)
}, },
......
...@@ -9,8 +9,13 @@ import type { ...@@ -9,8 +9,13 @@ import type {
NapiPartialProjectOptions, NapiPartialProjectOptions,
NapiCodeFrameOptions, NapiCodeFrameOptions,
NapiCodeFrameLocation, NapiCodeFrameLocation,
TraceServerHandle,
TraceQueryOptions,
TraceQueryResult,
} from './generated-native' } from './generated-native'
export type { TraceServerHandle, TraceQueryOptions, TraceQueryResult }
export type { NapiTurboEngineOptions as TurboEngineOptions } export type { NapiTurboEngineOptions as TurboEngineOptions }
export type Lockfile = { __napiType: 'Lockfile' } export type Lockfile = { __napiType: 'Lockfile' }
...@@ -27,10 +32,14 @@ export interface Binding { ...@@ -27,10 +32,14 @@ export interface Binding {
turboEngineOptions?: NapiTurboEngineOptions, turboEngineOptions?: NapiTurboEngineOptions,
callbacks?: TurbopackProjectCallbacks callbacks?: TurbopackProjectCallbacks
): Promise<Project> ): Promise<Project>
startTurbopackTraceServer( startTurbopackTraceServerHandle(
traceFilePath: string, traceFilePath: string,
port: number | undefined port: number | undefined
): void ): TraceServerHandle
queryTraceSpans(
handle: TraceServerHandle,
options: TraceQueryOptions
): TraceQueryResult
databaseCompact(path: string): Promise<void> databaseCompact(path: string): Promise<void>
nextBuild?: any nextBuild?: any
......
/**
* CLI client for querying a running turbopack trace server via its MCP endpoint.
* Sends a JSON-RPC `tools/call` request and prints the response to stdout.
* Use --json for machine-readable JSON output (default: markdown).
*
* Usage: next internal query-trace [options]
*/
const DEFAULT_MCP_PORT = 5748 // Keep in sync with turbo-trace-server.ts
interface QueryTraceOptions {
port: number | undefined
parent: string | undefined
aggregated: boolean | undefined
sort: boolean | undefined
search: string | undefined
page: number | undefined
json: boolean | undefined
}
export async function queryTraceCli(options: QueryTraceOptions): Promise<void> {
const port = options.port ?? DEFAULT_MCP_PORT
// Build arguments — only include values explicitly set by the user.
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,
})
let res: Response
try {
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,
})
} catch {
console.error(
[
`Error: Could not connect to trace server on port ${port}.`,
'',
'Make sure the trace server is running in the background:',
'',
` next internal trace <file> --mcp-port ${port}`,
'',
'Then run your query in another terminal. For all available options, see:',
'',
' next internal query-trace --help',
].join('\n')
)
process.exit(1)
}
if (!res.ok) {
console.error(`Error: MCP server responded with HTTP ${res.status}`)
process.exit(1)
}
const body = await res.text()
// Parse SSE stream: each event looks like:
// event: message
// data: <JSON-RPC response JSON>
//
// We scan for "data: " lines, parse the JSON, and extract the text content.
for (const line of body.split('\n')) {
if (!line.startsWith('data: ')) continue
let msg: {
result?: { content?: Array<{ type: string; text?: string }> }
error?: unknown
}
try {
msg = JSON.parse(line.slice('data: '.length))
} catch {
continue
}
if (msg.error) {
console.error(`Error: MCP tool error: ${JSON.stringify(msg.error)}`)
process.exit(1)
}
const text = msg.result?.content?.find((c) => c.type === 'text')?.text
if (text !== undefined) {
process.stdout.write(text)
return
}
}
console.error(`Error: No text content in MCP response:\n${body}`)
process.exit(1)
}
import http from 'node:http'
import z from 'next/dist/compiled/zod'
import { loadBindings } from '../../build/swc' import { loadBindings } from '../../build/swc'
import type { TraceSpanInfo } from '../../build/swc/generated-native'
const { McpServer } =
require('next/dist/compiled/@modelcontextprotocol/sdk/server/mcp') as typeof import('next/dist/compiled/@modelcontextprotocol/sdk/server/mcp')
const { StreamableHTTPServerTransport } =
require('next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp') as typeof import('next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp')
const DEFAULT_WS_PORT = 5747
const DEFAULT_MCP_PORT = 5748 // Keep in sync with query-trace.ts
/** 100 internal ticks = 1 µs */
const TICKS_PER_US = 100
const TICKS_PER_MS = TICKS_PER_US * 1000
const TICKS_PER_S = TICKS_PER_MS * 1000
function formatDuration(ticks: number): string {
if (ticks < TICKS_PER_MS) {
const us = ticks / TICKS_PER_US
return `${us.toFixed(0)}µs`
}
if (ticks < TICKS_PER_S) {
const ms = ticks / TICKS_PER_MS
return `${ms.toFixed(2)}ms`
}
const s = ticks / TICKS_PER_S
return `${s.toFixed(3)}s`
}
function formatRelative(ticks: number): string {
// ticks may be negative if the child starts before the parent reference point
const prefix = ticks < 0 ? '-' : ''
return prefix + formatDuration(Math.abs(ticks))
}
/**
* Render a single span (or aggregated span group) as a markdown section.
*/
function renderSpanMarkdown(span: TraceSpanInfo): string {
let md = `### \`${span.name}\` (ID: \`${span.id}\`)\n`
if (span.isAggregated && span.count !== undefined && span.count > 1) {
md += `- **Count:** ${span.count} spans\n`
if (span.totalCpuDuration !== undefined) {
md += `- **Total CPU Duration:** ${formatDuration(span.totalCpuDuration)}\n`
}
if (span.avgCpuDuration !== undefined) {
md += `- **Avg CPU Duration:** ${formatDuration(span.avgCpuDuration)}\n`
}
if (span.totalCorrectedDuration !== undefined) {
md += `- **Total Corrected Duration:** ${formatDuration(span.totalCorrectedDuration)}\n`
}
if (span.avgCorrectedDuration !== undefined) {
md += `- **Avg Corrected Duration:** ${formatDuration(span.avgCorrectedDuration)}\n`
}
md += `- **Start (relative to parent):** ${formatRelative(span.startRelativeToParent)}\n`
md += `- **End (relative to parent):** ${formatRelative(span.endRelativeToParent)}\n`
const exampleId = span.firstSpanId ?? span.id
md += `\n#### First span as example (ID: \`${exampleId}\`)\n`
md += `- **CPU Duration:** ${formatDuration(span.cpuDuration)}\n`
md += `- **Corrected Duration:** ${formatDuration(span.correctedDuration)}\n`
} else {
md += `- **CPU Duration:** ${formatDuration(span.cpuDuration)}\n`
md += `- **Corrected Duration:** ${formatDuration(span.correctedDuration)}\n`
md += `- **Start (relative to parent):** ${formatRelative(span.startRelativeToParent)}\n`
md += `- **End (relative to parent):** ${formatRelative(span.endRelativeToParent)}\n`
}
if (span.args && span.args.length > 0) {
md += `\n**Attributes:**\n`
for (const [k, v] of span.args) {
md += `- \`${k}\`: ${v}\n`
}
}
md += '\n---\n\n'
return md
}
export async function startTurboTraceServerCli( export async function startTurboTraceServerCli(
file: string, file: string,
port: number | undefined port: number | undefined,
mcpPort: number | undefined
) { ) {
let bindings = await loadBindings() const wsPort = port ?? DEFAULT_WS_PORT
bindings.turbo.startTurbopackTraceServer(file, port) const httpPort = mcpPort ?? DEFAULT_MCP_PORT
let bindings
try {
bindings = await loadBindings()
} catch {
console.error(
'Error: Could not load native bindings. The trace server requires native (non-WASM) bindings.'
)
process.exit(1)
}
let handle
try {
// Start the WebSocket trace server on a background thread (non-blocking).
handle = bindings.turbo.startTurbopackTraceServerHandle(file, wsPort)
} catch (err) {
console.error(
`Error: Could not start trace server for "${file}": ${err instanceof Error ? err.message : err}`
)
process.exit(1)
}
console.log(
`Turbopack trace server started. View trace at https://trace.nextjs.org?port=${wsPort}`
)
// Create the MCP server.
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. Returns spans with timing, CPU usage, and attribute details. Set `outputType` to "json" for machine-readable output or "markdown" (default) for human-readable output. Use the `parent` parameter (with an ID from a previous result) to drill into children. Results are paginated to 20 spans per page.',
inputSchema: {
parent: z
.string()
.optional()
.describe(
'Span ID to enumerate children of. Omit for root-level spans. Use the `id` field from a previous result.'
),
aggregated: z
.boolean()
.optional()
.describe(
'When true (default), aggregate spans with the same name into a single entry. Set to false to see individual raw spans.'
),
sort: z
.boolean()
.optional()
.describe(
'When true, sort results by corrected duration descending. Default false.'
),
search: z
.string()
.optional()
.describe(
'Substring search query applied to span name and category.'
),
page: z.number().optional().describe('1-based page number. Default 1.'),
outputType: z
.enum(['markdown', 'json'])
.optional()
.describe(
'Output format. "markdown" (default) returns human-readable markdown. "json" returns structured JSON with all span fields.'
),
},
},
(args) => {
const result = bindings.turbo.queryTraceSpans(handle, {
parent: args.parent,
aggregated: args.aggregated ?? true,
sort: args.sort ?? false,
search: args.search,
page: args.page ?? 1,
})
const { spans, page, totalPages, totalCount } = result
if (args.outputType === 'json') {
return {
content: [
{
type: 'text',
text: JSON.stringify({ spans, page, totalPages, totalCount }),
},
],
}
}
const parentLabel = args.parent
? `children of ID \`${args.parent}\``
: 'root level'
let md = `## Spans at ${parentLabel} — Page ${page} of ${totalPages} (${totalCount} total)\n\n`
if (spans.length === 0) {
md += '_No spans found._\n'
}
for (const span of spans) {
md += renderSpanMarkdown(span)
}
if (page < totalPages) {
md += `Use \`page=${page + 1}\` to see more results.\n`
}
return { content: [{ type: 'text', text: md }] }
}
)
// Start the HTTP server for MCP (served at /mcp).
const server = http.createServer(async (req, res) => {
if (req.url !== '/mcp') {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not found. MCP endpoint is at /mcp\n')
return
}
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
})
try {
res.on('close', () => transport.close())
await mcpServer.connect(transport)
let body = ''
req.setEncoding('utf8')
await new Promise<void>((resolve, reject) => {
req.on('data', (chunk: string) => {
body += chunk
})
req.on('end', resolve)
req.on('error', reject)
})
await transport.handleRequest(
req,
res,
body ? JSON.parse(body) : undefined
)
} catch (err) {
if (!res.headersSent) {
res.writeHead(500, {
'Content-Type': 'application/json; charset=utf-8',
})
res.end(
JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Internal server error' },
id: null,
})
)
}
}
})
server.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') {
console.error(
`Error: MCP port ${httpPort} is already in use. Use --mcp-port to specify a different port.`
)
} else {
console.error(`Error starting MCP server: ${err.message}`)
}
process.exit(1)
})
server.listen(httpPort, '127.0.0.1', () => {
console.log(
`Query this trace from the command line: next internal query-trace --help`
)
console.log(
`Alternatively, connect an MCP client to http://127.0.0.1:${httpPort}/mcp`
)
})
} }
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>Hello from turbopack-trace-server-query test</p>
}
...@@ -18,6 +18,12 @@ struct StoreWithGeneration { ...@@ -18,6 +18,12 @@ struct StoreWithGeneration {
generation: usize, generation: usize,
} }
impl Default for StoreContainer {
fn default() -> Self {
Self::new()
}
}
impl StoreContainer { impl StoreContainer {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
......
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