feat(core): reserved trace context _meta keys and propagation docs (SEP-414) (#2270)
Co-authored-by: Felix Weinberger <3823880+felixweinberger@users.noreply.github.com>
This commit is contained in:
parent
e84c3e9ad0
commit
78fbe2736d
2 changed files with 330 additions and 5 deletions
|
|
@ -26,7 +26,9 @@ import {
|
|||
SdkError,
|
||||
SdkErrorCode,
|
||||
SSEClientTransport,
|
||||
StreamableHTTPClientTransport
|
||||
StreamableHTTPClientTransport,
|
||||
TRACEPARENT_META_KEY,
|
||||
TRACESTATE_META_KEY
|
||||
} from '@modelcontextprotocol/client';
|
||||
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
|
||||
```
|
||||
|
|
@ -580,6 +582,58 @@ const transport = new StreamableHTTPClientTransport(new URL('http://localhost:30
|
|||
});
|
||||
```
|
||||
|
||||
## Trace context propagation
|
||||
|
||||
The MCP specification ([SEP-414](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/414)) reserves the unprefixed `_meta` keys `traceparent`, `tracestate`, and `baggage` for distributed trace context, as an exception to the usual `_meta` key prefix rule. When present, the values must follow the [W3C Trace Context](https://www.w3.org/TR/trace-context/) and [W3C Baggage](https://www.w3.org/TR/baggage/) formats. The SDK does not interpret these keys — `_meta` passes through both directions untouched — so you can propagate OpenTelemetry context across any transport, including stdio where HTTP headers are unavailable. The key names are exported as `TRACEPARENT_META_KEY`, `TRACESTATE_META_KEY`, and `BAGGAGE_META_KEY`.
|
||||
|
||||
Attach trace context to a single request via `_meta`:
|
||||
|
||||
```ts source="../examples/client/src/clientGuide.examples.ts#traceContext_perRequest"
|
||||
// Values would normally come from your tracer's active span context.
|
||||
const result = await client.callTool({
|
||||
name: 'calculate-bmi',
|
||||
arguments: { weightKg: 70, heightM: 1.75 },
|
||||
_meta: {
|
||||
[TRACEPARENT_META_KEY]: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
|
||||
[TRACESTATE_META_KEY]: 'vendor1=opaqueValue1'
|
||||
}
|
||||
});
|
||||
console.log(result.content);
|
||||
```
|
||||
|
||||
Or inject it into every outgoing request with fetch middleware (Streamable HTTP transport):
|
||||
|
||||
```ts source="../examples/client/src/clientGuide.examples.ts#traceContext_middleware"
|
||||
const traceContextMiddleware = createMiddleware(async (next, input, init) => {
|
||||
if (typeof init?.body !== 'string') {
|
||||
return next(input, init);
|
||||
}
|
||||
const message = JSON.parse(init.body) as {
|
||||
method?: string;
|
||||
params?: { _meta?: Record<string, unknown>; [key: string]: unknown };
|
||||
};
|
||||
// Only requests and notifications carry params._meta; skip responses.
|
||||
if (message.method === undefined) {
|
||||
return next(input, init);
|
||||
}
|
||||
message.params = {
|
||||
...message.params,
|
||||
_meta: {
|
||||
...message.params?._meta,
|
||||
// Replace with values from your tracer's active span context.
|
||||
[TRACEPARENT_META_KEY]: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'
|
||||
}
|
||||
};
|
||||
return next(input, { ...init, body: JSON.stringify(message) });
|
||||
});
|
||||
|
||||
const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'), {
|
||||
fetch: applyMiddlewares(traceContextMiddleware)(fetch)
|
||||
});
|
||||
```
|
||||
|
||||
On the server side, handlers can read the incoming trace context from `ctx.mcpReq._meta` — see the [server guide](./server.md#trace-context-propagation).
|
||||
|
||||
## Resumption tokens
|
||||
|
||||
When using SSE-based streaming, the server can assign event IDs. Pass `onresumptiontoken` to track them, and `resumptionToken` to resume from where you left off after a disconnection:
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import { createMcpExpressApp } from '@modelcontextprotocol/express';
|
||||
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
|
||||
import type { CallToolResult, ResourceLink } from '@modelcontextprotocol/server';
|
||||
import { completable, McpServer, ResourceTemplate } from '@modelcontextprotocol/server';
|
||||
import { completable, McpServer, ResourceTemplate, TRACEPARENT_META_KEY } from '@modelcontextprotocol/server';
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
||||
import * as z from 'zod/v4';
|
||||
```
|
||||
|
|
@ -384,6 +384,34 @@ server.registerTool(
|
|||
|
||||
`progress` must increase on each call. `total` and `message` are optional. If the client does not provide a `progressToken`, skip the notification.
|
||||
|
||||
## Trace context propagation
|
||||
|
||||
The MCP specification ([SEP-414](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/414)) reserves the unprefixed `_meta` keys `traceparent`, `tracestate`, and `baggage` for distributed trace context, as an exception to the usual `_meta` key prefix rule. When present, the values must follow the [W3C Trace Context](https://www.w3.org/TR/trace-context/) and [W3C Baggage](https://www.w3.org/TR/baggage/) formats. The SDK does not interpret these keys — `_meta` passes through untouched on any transport, including stdio. The key names are exported as `TRACEPARENT_META_KEY`, `TRACESTATE_META_KEY`, and `BAGGAGE_META_KEY`.
|
||||
|
||||
Read the caller's trace context from `ctx.mcpReq._meta` in a handler:
|
||||
|
||||
```ts source="../examples/server/src/serverGuide.examples.ts#registerTool_traceContext"
|
||||
server.registerTool(
|
||||
'traced-operation',
|
||||
{
|
||||
description: 'Operation that participates in distributed tracing',
|
||||
inputSchema: z.object({ query: z.string() })
|
||||
},
|
||||
async ({ query }, ctx): Promise<CallToolResult> => {
|
||||
// e.g. '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'
|
||||
const traceparent = ctx.mcpReq._meta?.[TRACEPARENT_META_KEY];
|
||||
if (typeof traceparent === 'string') {
|
||||
// Continue the caller's trace, e.g. start a child span with your
|
||||
// OpenTelemetry tracer using this trace context.
|
||||
}
|
||||
|
||||
return { content: [{ type: 'text', text: `Results for ${query}` }] };
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
To propagate context onward (for example on a server-initiated sampling request, or back on a response), set the same keys in the outgoing `_meta`. See the [client guide](./client.md#trace-context-propagation) for injecting trace context on the client side.
|
||||
|
||||
## Server-initiated requests
|
||||
|
||||
MCP is bidirectional — servers can send requests *to* the client during tool execution, as long as the client declares matching capabilities (see [Architecture](https://modelcontextprotocol.io/docs/learn/architecture) in the MCP overview).
|
||||
|
|
|
|||
Loading…
Reference in a new issue