Skip to content

fix: propagate context at MCP server #1644

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ def _instrument(self, **kwargs: Any) -> None:
),
"mcp.server.stdio",
)
register_post_import_hook(
lambda _: wrap_function_wrapper(
"mcp.server.lowlevel.server",
"Server._handle_request",
self._wrap_handle_request,
),
"mcp.server.lowlevel.server",
)

# While we prefer to instrument the lowest level primitive, the transports above, it doesn't
# mean context will be propagated to handlers automatically. Notably, the MCP SDK passes
Expand All @@ -79,6 +87,7 @@ def _instrument(self, **kwargs: Any) -> None:
def _uninstrument(self, **kwargs: Any) -> None:
unwrap("mcp.client.stdio", "stdio_client")
unwrap("mcp.server.stdio", "stdio_server")
unwrap("mcp.client.session", "ClientSession.call_tool")

@asynccontextmanager
async def _wrap_transport_with_callback(
Expand All @@ -98,6 +107,21 @@ async def _wrap_plain_transport(
async with wrapped(*args, **kwargs) as (read_stream, write_stream):
yield InstrumentedStreamReader(read_stream), InstrumentedStreamWriter(write_stream)

async def _wrap_handle_request(
self, wrapped: Callable[..., Any], instance: Any, args: Any, kwargs: Any
) -> Any:
token = None
try:
# Message has been deserialized, we need to extract the traceparent
_meta = {"traceparent": args[1].params.meta.traceparent}
ctx = propagate.extract(_meta)
token = context.attach(ctx)
finally:
res = await wrapped(*args, **kwargs)
if token:
context.detach(token)
return res

def _base_session_init_wrapper(
self, wrapped: Callable[..., None], instance: Any, args: Any, kwargs: Any
) -> None:
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.3.0"
__version__ = "1.3.1"
Loading