Coverage for .venv/lib/python3.13/site-packages/litellm/proxy/_experimental/mcp_server/mcp_context.py: 85%

11 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 12:01 +0000

1""" 

2Shared ContextVars for the MCP server layer. 

3 

4Lives in its own module to avoid circular imports between 

5mcp_server_manager.py and server.py. 

6""" 

7 

8from contextvars import ContextVar 

9from typing import TYPE_CHECKING, Final 

10 

11if TYPE_CHECKING: 11 ↛ 12line 11 didn't jump to line 12 because the condition on line 11 was never true

12 from mcp.server.context import ServerRequestContext 

13 

14# The SDK 1.x ``mcp.server.lowlevel.server.request_ctx`` ContextVar was removed in 

15# SDK 2, which hands each request handler a ``ServerRequestContext`` argument 

16# instead. The handlers set this var so downstream helpers (session auth caching, 

17# debug diagnostics, progress forwarding) can reach the same request-scoped state. 

18active_mcp_request_ctx_var: Final[ContextVar["ServerRequestContext | None"]] = ContextVar( 

19 "active_mcp_request_ctx", default=None 

20) 

21 

22 

23def get_active_mcp_request_ctx() -> "ServerRequestContext | None": 

24 return active_mcp_request_ctx_var.get() 

25 

26 

27# Set server-side in proxy_server.py route handlers when a request arrives via 

28# /toolset/{name}/mcp or the toolset fallback in dynamic_mcp_route. 

29# Never populated from client-supplied headers. 

30_mcp_active_toolset_id: Final[ContextVar[str | None]] = ContextVar("_mcp_active_toolset_id", default=None) 

31 

32# Per-request merged InitializeResult.instructions; set in MCP HTTP/SSE handlers. 

33_mcp_gateway_initialize_instructions: Final[ContextVar[str | None]] = ContextVar( 

34 "_mcp_gateway_initialize_instructions", default=None 

35) 

36 

37# Per-request scoped server name; set in MCP HTTP/SSE handlers when the path 

38# identifies exactly one upstream server. Never populated from client-supplied headers. 

39_mcp_gateway_server_name: Final[ContextVar[str | None]] = ContextVar("_mcp_gateway_server_name", default=None) 

40 

41# Set server-side by the /mcp/proxy route. Never populated from client-supplied headers. 

42_mcp_proxy_mode: Final[ContextVar[bool]] = ContextVar("_mcp_proxy_mode", default=False)