Propagate contextvars.Context through anyio streams without modifying SessionMessage
Merged
KL
8mo ago+310+310+012345678901234567890123456789-94-94-01234567890123456789
Summary
MCP server handlers currently lose the sender's contextvars.Context. When a client sets context variables (e.g. OpenTelemetry trace/span IDs) before sending a request, the server handler runs in the receive loop's context instead, breaking trace propagation.
This PR propagates contextvars.Context through anyio memory streams without adding any field to SessionMessage, addressing Kludex's review comment on the previous approach (#1996).
How it works
ContextSendStream/ContextReceiveStreamwrappers capture the sender's context atsend()time and expose it vialast_contexton the receive sideBaseSession._receive_loopreadslast_contextand passes it toRequestResponder, which carries it to the server handler boundarylowlevel/server.pyusescontext.run(tg.start_soon, handler)so handler tasks inherit the sender's context- Client transport
post_writerfunctions restore sender context the same way - Protocol-based
ReadStream/WriteStreamreplace concreteMemoryObjectSendStream/MemoryObjectReceiveStreamtypes, so both raw and context-aware streams are accepted create_context_streams[T](n)mirrors anyio's bracket syntax with proper generic propagation
Additional changes
- Switch coverage config from
exclude_linestoexclude_alsoto inherit coverage.py's built-in defaults (which handle...stubs andpragma: no cover)
Fixes https://github.com/modelcontextprotocol/python-sdk/issues/1969
Part of https://github.com/modelcontextprotocol/python-sdk/issues/421
Test plan
-
test_context_propagation: sets a contextvar via a context manager (which resets on exit), calls a tool, verifies the server handler sees the sender's value. Fails onmain, passes with this PR. - All existing tests pass
-
pyrightpasses with 0 errors