Skip to content

Commit e955392

Browse files
committed
fix: propagate context to MCP server
1 parent 2e20007 commit e955392

File tree

1 file changed

+20
-0
lines changed
  • python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp

1 file changed

+20
-0
lines changed

python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,14 @@ def _instrument(self, **kwargs: Any) -> None:
6161
),
6262
"mcp.server.stdio",
6363
)
64+
register_post_import_hook(
65+
lambda _: wrap_function_wrapper(
66+
"mcp.server.lowlevel.server",
67+
"Server._handle_request",
68+
self._wrap_handle_request,
69+
),
70+
"mcp.server.lowlevel.server",
71+
)
6472

6573
# While we prefer to instrument the lowest level primitive, the transports above, it doesn't
6674
# mean context will be propagated to handlers automatically. Notably, the MCP SDK passes
@@ -98,6 +106,18 @@ async def _wrap_plain_transport(
98106
async with wrapped(*args, **kwargs) as (read_stream, write_stream):
99107
yield InstrumentedStreamReader(read_stream), InstrumentedStreamWriter(write_stream)
100108

109+
def _wrap_handle_request(
110+
self, wrapped: Callable[..., Any], instance: Any, args: Any, kwargs: Any
111+
) -> Any:
112+
try:
113+
# Message has been deserialized, we need to extract the traceparent
114+
_meta = {"traceparent": args[1].params.meta.traceparent}
115+
ctx = propagate.extract(_meta)
116+
context.attach(ctx)
117+
return wrapped(*args, **kwargs)
118+
finally:
119+
pass
120+
101121
def _base_session_init_wrapper(
102122
self, wrapped: Callable[..., None], instance: Any, args: Any, kwargs: Any
103123
) -> None:

0 commit comments

Comments
 (0)