Skip to content

Commit cbccf05

Browse files
i11vclaude
andcommitted
Fix OTel context propagation: parent tool spans to HTTP root span
The MCP SDK dispatches tool handlers via Promise.resolve().then(), breaking AsyncLocalStorage context propagation. Tool spans were orphaned root traces disconnected from the HTTP request span. Workaround: inject a nonce into request headers in the tracing middleware, recover the parent OTel context in tool handlers via startToolSpan(). Also sets user.id on the root HTTP span. See docs/decisions/001-otel-context-propagation.md Tracking: modelcontextprotocol/typescript-sdk#1264 Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent 60274b0 commit cbccf05

4 files changed

Lines changed: 141 additions & 10 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# ADR-001: OpenTelemetry Context Propagation in MCP Tool Handlers
2+
3+
**Status:** Accepted
4+
**Date:** 2026-04-06
5+
6+
## Context
7+
8+
We use OpenTelemetry to trace requests through the Fastmail MCP server. The
9+
tracing middleware creates a root HTTP span, and each tool handler creates a
10+
child span for the tool invocation.
11+
12+
The MCP TypeScript SDK (v1.x) dispatches tool handlers via a detached
13+
`Promise.resolve().then()` chain in `Protocol._onrequest`. This breaks Node.js
14+
`AsyncLocalStorage` context propagation, which the OpenTelemetry JS SDK relies
15+
on. As a result:
16+
17+
- `trace.getActiveSpan()` returns `undefined` inside tool handlers.
18+
- `tracer.startSpan()` creates orphaned root spans instead of children of the
19+
HTTP request span.
20+
- Traces in Honeycomb appear as disconnected events rather than a single
21+
request tree.
22+
23+
There is no built-in OTel support in the MCP SDK today. Native support is
24+
tracked in [modelcontextprotocol/typescript-sdk#1264][issue-1264] (P2, v2
25+
milestone, no active PR). The `Promise.resolve().then()` pattern persists on
26+
both the `v1.x` branch and `main` as of 2026-04-06.
27+
28+
## Decision
29+
30+
We work around the broken context propagation by passing the OTel `Context`
31+
through a per-request nonce injected into HTTP request headers.
32+
33+
### How it works
34+
35+
1. The tracing middleware generates a random nonce and stores the active OTel
36+
`Context` in an in-memory `Map<string, Context>`.
37+
2. The nonce is injected into the raw request headers (`x-otel-ctx-nonce`).
38+
3. The `@hono/mcp` `StreamableHTTPTransport` copies all request headers into
39+
`extra.requestInfo.headers` when dispatching to tool handlers.
40+
4. Tool handlers call `startToolSpan(name, extra.requestInfo?.headers)` which
41+
looks up the parent context via the nonce and creates a properly-parented
42+
span.
43+
5. The middleware cleans up the nonce entry in its `finally` block.
44+
45+
### Surface area
46+
47+
- `src/tracing.ts` -- `startToolSpan()`, nonce storage, middleware changes
48+
- `src/tools.ts` -- tool handlers call `startToolSpan()` instead of
49+
`tracer.startSpan()`
50+
51+
## Consequences
52+
53+
**Positive:**
54+
- Tool spans are proper children of the HTTP root span in Honeycomb.
55+
- `user.id` appears on the root HTTP span (extracted in the middleware).
56+
- The workaround is contained in `startToolSpan()` -- tool handlers don't need
57+
to know about the nonce mechanism.
58+
59+
**Negative:**
60+
- Relies on the `@hono/mcp` transport forwarding all request headers to
61+
`extra.requestInfo.headers`. If the transport changes this behavior, the
62+
workaround breaks silently (spans become orphaned again, no errors).
63+
- Small in-memory map of active contexts. Cleaned up per-request, so only a
64+
concern under extreme concurrency.
65+
66+
## When to Remove
67+
68+
Replace this workaround when either:
69+
70+
1. The MCP SDK ships native OTel support ([#1264][issue-1264]).
71+
2. The `Promise.resolve().then()` pattern in `Protocol._onrequest` is replaced
72+
with context-preserving async dispatch.
73+
74+
At that point, `startToolSpan()` can be replaced with a plain
75+
`tracer.startSpan(name)` call and the nonce machinery removed.
76+
77+
[issue-1264]: https://github.com/modelcontextprotocol/typescript-sdk/issues/1264

‎src/tools.ts‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { createHash } from "node:crypto";
21
import { SpanStatusCode, type Span } from "@opentelemetry/api";
3-
import { tracer } from "./tracing.js";
2+
import { startToolSpan } from "./tracing.js";
43
import { z } from "zod";
54
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
65
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
76
import { getCachedSession, setCachedSession } from "./redis.js";
7+
import { hashToken } from "./utils.js";
88

99
// Constants
1010
const FASTMAIL_SESSION_ENDPOINT = "https://api.fastmail.com/jmap/session";
@@ -76,10 +76,6 @@ function extractBearerToken(extra: RequestHandlerExtra<any, any>): string {
7676
return authHeader.substring(7);
7777
}
7878

79-
function hashToken(token: string): string {
80-
return createHash("sha256").update(token).digest("hex").slice(0, 16);
81-
}
82-
8379
// --- Session management ---
8480

8581
async function fetchSession(bearerToken: string): Promise<JMAPSession> {
@@ -509,7 +505,7 @@ export function registerTools(server: McpServer) {
509505
inputSchema: ExecuteSchema,
510506
},
511507
async (args, extra) => {
512-
const span = tracer.startSpan("tool:execute");
508+
const span = startToolSpan("tool:execute", extra.requestInfo?.headers);
513509
try {
514510
// Validate
515511
const validated = validateStructure(args.methodCalls);
@@ -596,7 +592,7 @@ export function registerTools(server: McpServer) {
596592
inputSchema: SaveDraftSchema,
597593
},
598594
async (args, extra) => {
599-
const span = tracer.startSpan("tool:save_draft");
595+
const span = startToolSpan("tool:save_draft", extra.requestInfo?.headers);
600596
span.setAttribute("mcp.tool", "save_draft");
601597
try {
602598
const { session, bearerToken } = await getSession(extra, span);
@@ -655,7 +651,7 @@ export function registerTools(server: McpServer) {
655651
inputSchema: SendEmailSchema,
656652
},
657653
async (args, extra) => {
658-
const span = tracer.startSpan("tool:send_email");
654+
const span = startToolSpan("tool:send_email", extra.requestInfo?.headers);
659655
span.setAttribute("mcp.tool", "send_email");
660656
try {
661657
if (!args.to.trim()) {

‎src/tracing.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ import {
1313
diag,
1414
DiagConsoleLogger,
1515
DiagLogLevel,
16+
type Context,
1617
} from "@opentelemetry/api";
1718
import type { MiddlewareHandler } from "hono";
19+
import { hashToken } from "./utils.js";
1820

1921
const __dirname = dirname(fileURLToPath(import.meta.url));
2022
const pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8")) as {
@@ -67,26 +69,77 @@ export async function forceFlush(): Promise<void> {
6769
}
6870
}
6971

72+
// ---------------------------------------------------------------------------
73+
// OTel context propagation workaround
74+
// ---------------------------------------------------------------------------
75+
// The MCP SDK dispatches tool handlers via a detached Promise.resolve().then()
76+
// chain (Protocol._onrequest), which breaks Node.js AsyncLocalStorage context
77+
// propagation. This means trace.getActiveSpan() and tracer.startSpan() cannot
78+
// find the parent HTTP span inside tool handlers.
79+
//
80+
// Workaround: the tracing middleware injects a nonce into the request headers.
81+
// The MCP transport copies headers into extra.requestInfo.headers, so tool
82+
// handlers can recover the parent OTel context via startToolSpan().
83+
//
84+
// Tracking issue: https://github.com/modelcontextprotocol/typescript-sdk/issues/1264
85+
// See also: docs/decisions/001-otel-context-propagation.md
86+
// ---------------------------------------------------------------------------
87+
88+
const NONCE_HEADER = "x-otel-ctx-nonce";
89+
const activeContexts = new Map<string, Context>();
90+
91+
/**
92+
* Create a span that is properly parented to the HTTP root span.
93+
*
94+
* Call this instead of `tracer.startSpan()` inside MCP tool handlers.
95+
* Pass `extra.requestInfo?.headers` so the parent context can be recovered.
96+
*
97+
* When the MCP SDK gains native OTel support, replace the implementation
98+
* with a plain `tracer.startSpan(name)` call.
99+
*/
100+
export function startToolSpan(
101+
name: string,
102+
headers?: Record<string, string | string[] | undefined>,
103+
) {
104+
const nonce = headers?.[NONCE_HEADER];
105+
const parentCtx = typeof nonce === "string" ? activeContexts.get(nonce) : undefined;
106+
return tracer.startSpan(name, {}, parentCtx ?? context.active());
107+
}
108+
70109
export function tracingMiddleware(): MiddlewareHandler {
71110
return async (c, next) => {
111+
// Extract user.id from bearer token on the root span
112+
const auth = c.req.header("authorization");
113+
const userId = auth?.startsWith("Bearer ") ? hashToken(auth.substring(7)) : undefined;
114+
72115
const span = tracer.startSpan(`${c.req.method} ${c.req.routePath}`, {
73116
attributes: {
74117
"http.request.method": c.req.method,
75118
"http.route": c.req.routePath,
76119
"url.full": c.req.url,
120+
"user.id": userId,
77121
},
78122
});
79123

80124
const ctx = trace.setSpan(context.active(), span);
81125

126+
// Inject nonce so tool handlers can recover this context (see startToolSpan)
127+
const nonce = crypto.randomUUID();
128+
c.req.raw.headers.set(NONCE_HEADER, nonce);
129+
activeContexts.set(nonce, ctx);
130+
82131
try {
83132
await context.with(ctx, () => next());
84133
span.setAttribute("http.response.status_code", c.res.status);
85134
} catch (err) {
86135
span.recordException(err as Error);
87-
span.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message });
136+
span.setStatus({
137+
code: SpanStatusCode.ERROR,
138+
message: (err as Error).message,
139+
});
88140
throw err;
89141
} finally {
142+
activeContexts.delete(nonce);
90143
span.end();
91144
if (process.env.VERCEL) {
92145
await forceFlush();

‎src/utils.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { createHash } from "node:crypto";
2+
3+
export function hashToken(token: string): string {
4+
return createHash("sha256").update(token).digest("hex").slice(0, 16);
5+
}

0 commit comments

Comments
 (0)