Propagate contextvars.Context through anyio streams without modifying SessionMessage

Merged
KL
8mo ago
+310-94

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 / ContextReceiveStream wrappers capture the sender's context at send() time and expose it via last_context on the receive side
  • BaseSession._receive_loop reads last_context and passes it to RequestResponder, which carries it to the server handler boundary
  • lowlevel/server.py uses context.run(tg.start_soon, handler) so handler tasks inherit the sender's context
  • Client transport post_writer functions restore sender context the same way
  • Protocol-based ReadStream / WriteStream replace concrete MemoryObjectSendStream / MemoryObjectReceiveStream types, 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_lines to exclude_also to inherit coverage.py's built-in defaults (which handle ... stubs and pragma: 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 on main, passes with this PR.
  • All existing tests pass
  • pyright passes with 0 errors