Propagate contextvars through anyio streams

Closed
AA
8mo ago
+328-110

Fixes https://github.com/modelcontextprotocol/python-sdk/issues/1969
Part of https://github.com/modelcontextprotocol/python-sdk/issues/421

This PR propagates contextvars.Context through internal anyio memory streams and restores it in long running async tasks, so that they run with the correct context. Works for in memory, streamable http, and sse transports.

  • For MCP clients, this captures the caller's active context and restores it before using the transport.
  • For MCP servers, it captures the active context from the transport and restores it before using the Server's handlers

Motivation and Context

The goal is to make contextvars "work" with the MCP SDK as users expect. The main motivation is OpenTelemetry https://github.com/modelcontextprotocol/python-sdk/issues/421, but there are other use cases e.g. per-request auth, stdlib decimal, starlette-context, etc.

How Has This Been Tested?

Added several integration tests which are failing at main. I also manually tested e2e with the some of the samples by using OpenTelemetry httpx instrumentation (I can share screenshots).

Tests failures at main
═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ inline-snapshot ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Fix snapshots ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── tests/test_context_propagation.py ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ @@ -83,7 +83,7 @@                                                                                                                                                                                                                                                                                                                                           │
│                                                                                                                                                                                                                                                                                                                                                             │
│              result = await client.call_tool(name="my_tool")                                                                                                                                                                                                                                                                                                │
│                                                                                                                                                                                                                                                                                                                                                             │
│              assert isinstance(result, types.CallToolResult)                                                                                                                                                                                                                                                                                                │
│ -            assert result.content == snapshot([types.TextContent(text="client_value")])                                                                                                                                                                                                                                                                    │
│ +            assert result.content == snapshot([types.TextContent(text="initial")])                                                                                                                                                                                                                                                                         │
│                                                                                                                                                                                                                                                                                                                                                             │
│                                                                                                                                                                                                                                                                                                                                                             │
│  class ContextVarMiddleware(BaseHTTPMiddleware):  # pragma: lax no cover                                                                                                                                                                                                                                                                                    │
│ @@ -127,7 +127,7 @@                                                                                                                                                                                                                                                                                                                                         │
│                                                                                                                                                                                                                                                                                                                                                             │
│          ):                                                                                                                                                                                                                                                                                                                                                 │
│              transport.client_header_value = "expected_value"                                                                                                                                                                                                                                                                                               │
│              result = await client.call_tool("my_tool")                                                                                                                                                                                                                                                                                                     │
│ -            assert result.content == snapshot([types.TextContent(text="from middleware CLIENT_HEADER=expected_value")])                                                                                                                                                                                                                                    │
│ +            assert result.content == snapshot([types.TextContent(text="from middleware CLIENT_HEADER=initial")])                                                                                                                                                                                                                                           │
│                                                                                                                                                                                                                                                                                                                                                             │
│                                                                                                                                                                                                                                                                                                                                                             │
│  @pytest.mark.anyio                                                                                                                                                                                                                                                                                                                                         │
│ @@ -142,7 +142,7 @@                                                                                                                                                                                                                                                                                                                                         │
│                                                                                                                                                                                                                                                                                                                                                             │
│          ):                                                                                                                                                                                                                                                                                                                                                 │
│              with set_test_contextvar("client_value_list"):                                                                                                                                                                                                                                                                                                 │
│                  await client.list_tools()                                                                                                                                                                                                                                                                                                                  │
│ -                assert transport.captured_context_var == snapshot("client_value_list")                                                                                                                                                                                                                                                                     │
│ +                assert transport.captured_context_var == snapshot("initial")                                                                                                                                                                                                                                                                               │
│                                                                                                                                                                                                                                                                                                                                                             │
│              with set_test_contextvar("client_value_call_tool"):                                                                                                                                                                                                                                                                                            │
│                  await client.call_tool("my_tool")                                                                                                                                                                                                                                                                                                          │
│ @@ -167,7 +167,7 @@                                                                                                                                                                                                                                                                                                                                         │
│                                                                                                                                                                                                                                                                                                                                                             │
│          ) as client:                                                                                                                                                                                                                                                                                                                                       │
│              transport.client_header_value = "expected_value"                                                                                                                                                                                                                                                                                               │
│              result = await client.call_tool("my_tool")                                                                                                                                                                                                                                                                                                     │
│ -            assert result.content == snapshot([types.TextContent(text="from middleware CLIENT_HEADER=expected_value")])                                                                                                                                                                                                                                    │
│ +            assert result.content == snapshot([types.TextContent(text="from middleware CLIENT_HEADER=initial")])                                                                                                                                                                                                                                           │
│                                                                                                                                                                                                                                                                                                                                                             │
│                                                                                                                                                                                                                                                                                                                                                             │
│  @pytest.mark.anyio                                                                                                                                                                                                                                                                                                                                         │
│ @@ -187,7 +187,7 @@                                                                                                                                                                                                                                                                                                                                         │
│                                                                                                                                                                                                                                                                                                                                                             │
│          ) as client:                                                                                                                                                                                                                                                                                                                                       │
│              with set_test_contextvar("client_value_list"):                                                                                                                                                                                                                                                                                                 │
│                  await client.list_tools()                                                                                                                                                                                                                                                                                                                  │
│ -                assert transport.captured_context_var == snapshot("client_value_list")                                                                                                                                                                                                                                                                     │
│ +                assert transport.captured_context_var == snapshot("initial")                                                                                                                                                                                                                                                                               │
│                                                                                                                                                                                                                                                                                                                                                             │
│              with set_test_contextvar("client_value_call_tool"):                                                                                                                                                                                                                                                                                            │
│                  await client.call_tool("my_tool")                                                                                                                                                                                                                                                                                                          │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
These changes are not applied.
Use --inline-snapshot=fix to apply them, or use the interactive mode with --inline-snapshot=review

Breaking Changes

No

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

N/A