@@ -13,8 +13,10 @@ import {
1313 diag ,
1414 DiagConsoleLogger ,
1515 DiagLogLevel ,
16+ type Context ,
1617} from "@opentelemetry/api" ;
1718import type { MiddlewareHandler } from "hono" ;
19+ import { hashToken } from "./utils.js" ;
1820
1921const __dirname = dirname ( fileURLToPath ( import . meta. url ) ) ;
2022const 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+
70109export 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 ( ) ;
0 commit comments