The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Revert "Revert "[MCP Gateway] Add protocol headers (#13062)""
Ishaan Jaff1af0743e585b
diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.pyindex 843a9fb0e20..6ab8033bf9e 100644--- a/litellm/experimental_mcp_client/client.py+++ b/litellm/experimental_mcp_client/client.py@@ -17,6 +17,8 @@ from mcp.types import Tool as MCPToolfrom litellm.types.mcp import (MCPAuth,MCPAuthType,+ MCPSpecVersion,+ MCPSpecVersionType,MCPStdioConfig,MCPTransport,MCPTransportType,@@ -44,6 +46,7 @@ class MCPClient:auth_value: Optional[str] = None,timeout: float = 60.0,stdio_config: Optional[MCPStdioConfig] = None,+ protocol_version: MCPSpecVersionType = MCPSpecVersion.jun_2025,):self.server_url: str = server_urlself.transport_type: MCPTransport = transport_type@@ -57,6 +60,7 @@ class MCPClient:self._session_ctx = Noneself._task: Optional[asyncio.Task] = Noneself.stdio_config: Optional[MCPStdioConfig] = stdio_config+ self.protocol_version: MCPSpecVersionType = protocol_version# handle the basic auth value if providedif auth_value:@@ -169,16 +173,18 @@ class MCPClient:def _get_auth_headers(self) -> dict:"""Generate authentication headers based on auth type."""- if not self._mcp_auth_value:- return {}-- if self.auth_type == MCPAuth.bearer_token:- return {"Authorization": f"Bearer {self._mcp_auth_value}"}- elif self.auth_type == MCPAuth.basic:- return {"Authorization": f"Basic {self._mcp_auth_value}"}- elif self.auth_type == MCPAuth.api_key:- return {"X-API-Key": self._mcp_auth_value}- return {}+ headers = {}++ if self._mcp_auth_value:+ if self.auth_type == MCPAuth.bearer_token:+ headers["Authorization"] = f"Bearer {self._mcp_auth_value}"+ elif self.auth_type == MCPAuth.basic:+ headers["Authorization"] = f"Basic {self._mcp_auth_value}"+ elif self.auth_type == MCPAuth.api_key:+ headers["X-API-Key"] = self._mcp_auth_value++ headers["MCP-Protocol-Version"] = self.protocol_version.value+ return headersasync def list_tools(self) -> List[MCPTool]:"""List available tools from the server."""diff --git a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.pyindex cb4aab4bb1d..058f45d7123 100644--- a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py+++ b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py@@ -16,8 +16,9 @@ class MCPAuthenticatedUser(AuthenticatedUser):4. Server-specific authentication headers"""- def __init__(self, user_api_key_auth: UserAPIKeyAuth, mcp_auth_header: Optional[str] = None, mcp_servers: Optional[List[str]] = None, mcp_server_auth_headers: Optional[Dict[str, str]] = None):+ def __init__(self, user_api_key_auth: UserAPIKeyAuth, mcp_auth_header: Optional[str] = None, mcp_servers: Optional[List[str]] = None, mcp_server_auth_headers: Optional[Dict[str, str]] = None, mcp_protocol_version: Optional[str] = None):self.user_api_key_auth = user_api_key_authself.mcp_auth_header = mcp_auth_headerself.mcp_servers = mcp_serversself.mcp_server_auth_headers = mcp_server_auth_headers or {}+ self.mcp_protocol_version = mcp_protocol_versiondiff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.pyindex 0f4acce21f2..d25cf8211ad 100644--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py@@ -28,9 +28,12 @@ class MCPRequestHandler:LITELLM_MCP_SERVERS_HEADER_NAME = SpecialHeaders.mcp_servers.valueLITELLM_MCP_ACCESS_GROUPS_HEADER_NAME = SpecialHeaders.mcp_access_groups.value++ # MCP Protocol Version header+ MCP_PROTOCOL_VERSION_HEADER_NAME = "MCP-Protocol-Version"@staticmethod- async def process_mcp_request(scope: Scope) -> Tuple[UserAPIKeyAuth, Optional[str], Optional[List[str]], Optional[Dict[str, str]]]:+ async def process_mcp_request(scope: Scope) -> Tuple[UserAPIKeyAuth, Optional[str], Optional[List[str]], Optional[Dict[str, str]], Optional[str]]:"""Process and validate MCP request headers from the ASGI scope.This includes:@@ -46,6 +49,7 @@ class MCPRequestHandler:mcp_auth_header: Optional[str] MCP auth header to be passed to the MCP server (deprecated)mcp_servers: Optional[List[str]] List of MCP servers and access groups to usemcp_server_auth_headers: Optional[Dict[str, str]] Server-specific auth headers in format {server_alias: auth_value}+ mcp_protocol_version: Optional[str] MCP protocol version from request headerRaises:HTTPException: If headers are invalid or missing required headers@@ -61,6 +65,9 @@ class MCPRequestHandler:# Get the new server-specific auth headersmcp_server_auth_headers = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)+ # Get MCP protocol version from header+ mcp_protocol_version = headers.get(MCPRequestHandler.MCP_PROTOCOL_VERSION_HEADER_NAME)+# Parse MCP servers from headermcp_servers_header = headers.get(MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME)verbose_logger.debug(f"Raw MCP servers header: {mcp_servers_header}")@@ -82,7 +89,7 @@ class MCPRequestHandler:validated_user_api_key_auth = await user_api_key_auth(api_key=litellm_api_key, request=request)- return validated_user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers+ return validated_user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version@staticmethoddiff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 86a172e802a..9d72755df58 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -172,7 +172,7 @@ class MCPServerManager:server_name=server_name,url=server_config.get("url", None) or "",transport=server_config.get("transport", MCPTransport.http),- spec_version=server_config.get("spec_version", MCPSpecVersion.mar_2025),+ spec_version=server_config.get("spec_version", MCPSpecVersion.jun_2025),auth_type=server_config.get("auth_type", None),alias=alias,)@@ -188,7 +188,7 @@ class MCPServerManager:env=server_config.get("env", None) or {},# TODO: utility fn the default valuestransport=server_config.get("transport", MCPTransport.http),- spec_version=server_config.get("spec_version", MCPSpecVersion.mar_2025),+ spec_version=server_config.get("spec_version", MCPSpecVersion.jun_2025),auth_type=server_config.get("auth_type", None),mcp_info=mcp_info,access_groups=server_config.get("access_groups", None),@@ -284,6 +284,7 @@ class MCPServerManager:user_api_key_auth: Optional[UserAPIKeyAuth] = None,mcp_auth_header: Optional[str] = None,mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,) -> List[MCPTool]:"""List all tools available across all MCP Servers.@@ -292,6 +293,7 @@ class MCPServerManager:user_api_key_auth: User authenticationmcp_auth_header: MCP auth header (deprecated)mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}+ mcp_protocol_version: Optional MCP protocol version from request headerReturns:List[MCPTool]: Combined list of tools from all servers@@ -322,6 +324,7 @@ class MCPServerManager:tools = await self._get_tools_from_server(server=server,mcp_auth_header=server_auth_header,+ mcp_protocol_version=mcp_protocol_version,)list_tools_result.extend(tools)verbose_logger.info(f"Successfully fetched {len(tools)} tools from server {server.name}")@@ -337,13 +340,14 @@ class MCPServerManager:########################################################## Methods that call the upstream MCP servers#########################################################- def _create_mcp_client(self, server: MCPServer, mcp_auth_header: Optional[str] = None) -> MCPClient:+ def _create_mcp_client(self, server: MCPServer, mcp_auth_header: Optional[str] = None, protocol_version: Optional[str] = None) -> MCPClient:"""Create an MCPClient instance for the given server.Args:server (MCPServer): The server configurationmcp_auth_header: MCP auth header to be passed to the MCP server. This is optional and will be used if provided.+ protocol_version: Optional MCP protocol version to use. If not provided, uses server's default.Returns:MCPClient: Configured MCP client instance@@ -368,6 +372,7 @@ class MCPServerManager:auth_value=mcp_auth_header or server.authentication_token,timeout=60.0,stdio_config=stdio_config,+ protocol_version=cast(MCPSpecVersionType, protocol_version or server.spec_version),)else:# For HTTP/SSE transports@@ -378,9 +383,10 @@ class MCPServerManager:auth_type=server.auth_type,auth_value=mcp_auth_header or server.authentication_token,timeout=60.0,+ protocol_version=cast(MCPSpecVersionType, protocol_version or server.spec_version),)- async def _get_tools_from_server(self, server: MCPServer, mcp_auth_header: Optional[str] = None) -> List[MCPTool]:+ async def _get_tools_from_server(self, server: MCPServer, mcp_auth_header: Optional[str] = None, mcp_protocol_version: Optional[str] = None) -> List[MCPTool]:"""Helper method to get tools from a single MCP server with prefixed names.@@ -396,9 +402,12 @@ class MCPServerManager:client = Nonetry:+ # Use protocol version from request if provided, otherwise use server's default+ protocol_version = mcp_protocol_version if mcp_protocol_version else server.spec_versionclient = self._create_mcp_client(server=server,mcp_auth_header=mcp_auth_header,+ protocol_version=protocol_version,)# Create a task for the client operations to ensure proper cancellation handling@@ -473,6 +482,7 @@ class MCPServerManager:user_api_key_auth: Optional[UserAPIKeyAuth] = None,mcp_auth_header: Optional[str] = None,mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,litellm_logging_obj: Optional[Any] = None,) -> CallToolResult:"""@@ -484,6 +494,7 @@ class MCPServerManager:user_api_key_auth: User authenticationmcp_auth_header: MCP auth header (deprecated)mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}+ mcp_protocol_version: Optional MCP protocol version from request headerlitellm_logging_obj: Optional logging object for hook integrationReturns:@@ -548,6 +559,7 @@ class MCPServerManager:client = self._create_mcp_client(server=mcp_server,mcp_auth_header=server_auth_header,+ protocol_version=mcp_protocol_version,)#########################################################diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex b4a3dbc61e1..05ff137f557 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -169,7 +169,7 @@ if MCP_AVAILABLE:List all available tools"""# Get user authentication from context variable- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = get_auth_context()+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = get_auth_context()verbose_logger.debug(f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}")@@ -185,6 +185,7 @@ if MCP_AVAILABLE:mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,)@server.call_tool()@@ -210,7 +211,7 @@ if MCP_AVAILABLE:from litellm.proxy.proxy_server import proxy_config# Validate arguments- user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers = get_auth_context()+ user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers, mcp_protocol_version = get_auth_context()verbose_logger.debug(f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}"@@ -241,6 +242,7 @@ if MCP_AVAILABLE:user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,**data, # for logging)except Exception as e:@@ -262,6 +264,7 @@ if MCP_AVAILABLE:mcp_auth_header: Optional[str],mcp_servers: Optional[List[str]],mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,) -> List[MCPTool]:"""Helper method to fetch tools from MCP servers based on server filtering criteria.@@ -325,6 +328,7 @@ if MCP_AVAILABLE:tools = await global_mcp_server_manager._get_tools_from_server(server=server,mcp_auth_header=server_auth_header,+ mcp_protocol_version=mcp_protocol_version,)all_tools.extend(tools)verbose_logger.debug(f"Successfully fetched {len(tools)} tools from server {server.name}")@@ -342,6 +346,7 @@ if MCP_AVAILABLE:mcp_auth_header: Optional[str] = None,mcp_servers: Optional[List[str]] = None,mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,) -> List[MCPTool]:"""List all available MCP tools.@@ -364,6 +369,7 @@ if MCP_AVAILABLE:mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,)# Get tools from local registry@@ -392,6 +398,7 @@ if MCP_AVAILABLE:user_api_key_auth: Optional[UserAPIKeyAuth] = None,mcp_auth_header: Optional[str] = None,mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,**kwargs: Any) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:"""@@ -439,6 +446,7 @@ if MCP_AVAILABLE:user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,litellm_logging_obj=litellm_logging_obj,)@@ -491,6 +499,7 @@ if MCP_AVAILABLE:user_api_key_auth: Optional[UserAPIKeyAuth] = None,mcp_auth_header: Optional[str] = None,mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,litellm_logging_obj: Optional[Any] = None,) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:"""Handle tool execution for managed server tools"""@@ -500,6 +509,7 @@ if MCP_AVAILABLE:user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,litellm_logging_obj=litellm_logging_obj,)verbose_logger.debug("CALL TOOL RESULT: %s", call_tool_result)@@ -536,15 +546,15 @@ if MCP_AVAILABLE:mcp_servers_from_path = [s.strip() for s in mcp_servers_str.split(",") if s.strip()]if mcp_servers_from_path is not None:- user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers = (+ user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers, mcp_protocol_version = (await MCPRequestHandler.process_mcp_request(scope))mcp_servers = mcp_servers_from_pathelse:- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = (+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = (await MCPRequestHandler.process_mcp_request(scope))- return user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers+ return user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_versionasync def handle_streamable_http_mcp(scope: Scope, receive: Receive, send: Send@@ -552,15 +562,17 @@ if MCP_AVAILABLE:"""Handle MCP requests through StreamableHTTP."""try:path = scope.get("path", "")- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await extract_mcp_auth_context(scope, path)+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = await extract_mcp_auth_context(scope, path)verbose_logger.debug(f"MCP request mcp_servers (header/path): {mcp_servers}")verbose_logger.debug(f"MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}")+ verbose_logger.debug(f"MCP protocol version: {mcp_protocol_version}")# Set the auth context variable for easy access in MCP functionsset_auth_context(user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,)# Ensure session managers are initialized@@ -578,14 +590,16 @@ if MCP_AVAILABLE:"""Handle MCP requests through SSE."""try:path = scope.get("path", "")- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await extract_mcp_auth_context(scope, path)+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = await extract_mcp_auth_context(scope, path)verbose_logger.debug(f"MCP request mcp_servers (header/path): {mcp_servers}")verbose_logger.debug(f"MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}")+ verbose_logger.debug(f"MCP protocol version: {mcp_protocol_version}")set_auth_context(user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,)if not _SESSION_MANAGERS_INITIALIZED:@@ -629,6 +643,7 @@ if MCP_AVAILABLE:mcp_auth_header: Optional[str] = None,mcp_servers: Optional[List[str]] = None,mcp_server_auth_headers: Optional[Dict[str, str]] = None,+ mcp_protocol_version: Optional[str] = None,) -> None:"""Set the UserAPIKeyAuth in the auth context variable.@@ -644,11 +659,12 @@ if MCP_AVAILABLE:mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=mcp_protocol_version,)auth_context_var.set(auth_user)def get_auth_context() -> (- Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]]]+ Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]], Optional[str]]):"""Get the UserAPIKeyAuth from the auth context variable.@@ -664,8 +680,9 @@ if MCP_AVAILABLE:auth_user.mcp_auth_header,auth_user.mcp_servers,auth_user.mcp_server_auth_headers,+ auth_user.mcp_protocol_version,)- return None, None, None, None+ return None, None, None, None, None#################################################################### End of Auth Context Functions #############diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 00922e71483..6fc03a60bee 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -843,7 +843,7 @@ class NewMCPServerRequest(LiteLLMPydanticObjectBase):alias: Optional[str] = Nonedescription: Optional[str] = Nonetransport: MCPTransportType = MCPTransport.sse- spec_version: MCPSpecVersionType = MCPSpecVersion.mar_2025+ spec_version: MCPSpecVersionType = MCPSpecVersion.jun_2025auth_type: Optional[MCPAuthType] = Noneurl: Optional[str] = Nonemcp_info: Optional[MCPInfo] = None@@ -875,7 +875,7 @@ class UpdateMCPServerRequest(LiteLLMPydanticObjectBase):alias: Optional[str] = Nonedescription: Optional[str] = Nonetransport: MCPTransportType = MCPTransport.sse- spec_version: MCPSpecVersionType = MCPSpecVersion.mar_2025+ spec_version: MCPSpecVersionType = MCPSpecVersion.jun_2025auth_type: Optional[MCPAuthType] = Noneurl: Optional[str] = Nonemcp_info: Optional[MCPInfo] = Nonediff --git a/litellm/types/mcp.py b/litellm/types/mcp.pyindex fa7a70a9afc..93db499e689 100644--- a/litellm/types/mcp.py+++ b/litellm/types/mcp.py@@ -24,6 +24,7 @@ class MCPTransport(str, enum.Enum):class MCPSpecVersion(str, enum.Enum):nov_2024 = "2024-11-05"mar_2025 = "2025-03-26"+ jun_2025 = "2025-06-18"class MCPAuth(str, enum.Enum):none = "none"@@ -34,7 +35,7 @@ class MCPAuth(str, enum.Enum):# MCP LiteralsMCPTransportType = Literal[MCPTransport.sse, MCPTransport.http, MCPTransport.stdio]-MCPSpecVersionType = Literal[MCPSpecVersion.nov_2024, MCPSpecVersion.mar_2025]+MCPSpecVersionType = Literal[MCPSpecVersion.nov_2024, MCPSpecVersion.mar_2025, MCPSpecVersion.jun_2025]MCPAuthType = Optional[Literal[MCPAuth.none, MCPAuth.api_key, MCPAuth.bearer_token, MCPAuth.basic]]diff --git a/tests/mcp_tests/test_mcp_client_unit.py b/tests/mcp_tests/test_mcp_client_unit.pyindex e0efea89b3b..dba2bfa1796 100644--- a/tests/mcp_tests/test_mcp_client_unit.py+++ b/tests/mcp_tests/test_mcp_client_unit.py@@ -42,7 +42,7 @@ class TestMCPClientUnitTests:auth_value="test_token")headers = client._get_auth_headers()- assert headers == {"Authorization": "Bearer test_token"}+ assert headers == {"Authorization": "Bearer test_token", "MCP-Protocol-Version": "2025-06-18"}# Basic authclient = MCPClient(@@ -52,7 +52,7 @@ class TestMCPClientUnitTests:)expected_encoded = base64.b64encode("user:pass".encode("utf-8")).decode()headers = client._get_auth_headers()- assert headers == {"Authorization": f"Basic {expected_encoded}"}+ assert headers == {"Authorization": f"Basic {expected_encoded}", "MCP-Protocol-Version": "2025-06-18"}# API keyclient = MCPClient(@@ -61,7 +61,21 @@ class TestMCPClientUnitTests:auth_value="api_key_123")headers = client._get_auth_headers()- assert headers == {"X-API-Key": "api_key_123"}+ assert headers == {"X-API-Key": "api_key_123", "MCP-Protocol-Version": "2025-06-18"}++ # No auth+ client = MCPClient("http://example.com")+ headers = client._get_auth_headers()+ assert headers == {"MCP-Protocol-Version": "2025-06-18"}++ # Custom protocol version+ from litellm.types.mcp import MCPSpecVersion+ client = MCPClient(+ "http://example.com",+ protocol_version=MCPSpecVersion.mar_2025+ )+ headers = client._get_auth_headers()+ assert headers == {"MCP-Protocol-Version": "2025-03-26"}@pytest.mark.asyncio@patch('litellm.experimental_mcp_client.client.streamablehttp_client')@@ -88,7 +102,7 @@ class TestMCPClientUnitTests:# Verify transport was created with auth headerscall_args = mock_transport.call_args- assert call_args[1]['headers'] == {"Authorization": "Bearer test_token"}+ assert call_args[1]['headers'] == {"Authorization": "Bearer test_token", "MCP-Protocol-Version": "2025-06-18"}# Verify session was initializedmock_session_instance.initialize.assert_called_once()@@ -164,6 +178,63 @@ class TestMCPClientUnitTests:arguments={"arg1": "value1"})+ def test_protocol_version_header_extraction(self):+ """Test that MCP protocol version header is correctly extracted from requests."""+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler++ # Mock scope with headers+ mock_scope = {+ "type": "http",+ "method": "GET",+ "path": "/test",+ "headers": [+ (b"authorization", b"Bearer test_token"),+ (b"mcp-protocol-version", b"2025-06-18"),+ (b"content-type", b"application/json"),+ ]+ }++ # Mock the user_api_key_auth function+ with patch('litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth') as mock_auth:+ mock_auth.return_value = MagicMock()++ # Call process_mcp_request+ import asyncio+ result = asyncio.run(MCPRequestHandler.process_mcp_request(mock_scope))++ # Verify the protocol version is extracted+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = result++ assert mcp_protocol_version == "2025-06-18"++ def test_protocol_version_header_missing(self):+ """Test that MCP protocol version header is None when not provided."""+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler++ # Mock scope without protocol version header+ mock_scope = {+ "type": "http",+ "method": "GET",+ "path": "/test",+ "headers": [+ (b"authorization", b"Bearer test_token"),+ (b"content-type", b"application/json"),+ ]+ }++ # Mock the user_api_key_auth function+ with patch('litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth') as mock_auth:+ mock_auth.return_value = MagicMock()++ # Call process_mcp_request+ import asyncio+ result = asyncio.run(MCPRequestHandler.process_mcp_request(mock_scope))++ # Verify the protocol version is None+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = result++ assert mcp_protocol_version is None+if __name__ == "__main__":pytest.main([__file__, "-v"])\ No newline at end of filediff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.pyindex 17faccbfc89..6038d19ecce 100644--- a/tests/mcp_tests/test_mcp_server.py+++ b/tests/mcp_tests/test_mcp_server.py@@ -720,7 +720,7 @@ async def test_get_tools_from_mcp_servers():mock_manager_2 = AsyncMock()mock_manager_2.get_allowed_mcp_servers = AsyncMock(return_value=["server1_id", "server2_id"])mock_manager_2.get_mcp_server_by_id = mock_get_server_by_id- mock_manager_2._get_tools_from_server = AsyncMock(side_effect=lambda server, mcp_auth_header=None:+ mock_manager_2._get_tools_from_server = AsyncMock(side_effect=lambda server, mcp_auth_header=None, mcp_protocol_version=None:[mock_tool_1] if server.server_id == "server1_id" else [mock_tool_2])with patch('litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager', mock_manager_2):@@ -1199,3 +1199,39 @@ def test_add_server_prefix_to_tool_name():assert result == "-send_email"+async def test_mcp_protocol_version_passed_to_client():+ """Test that MCP protocol version from request is correctly passed to MCPClient."""++ # Create a test manager+ test_manager = MCPServerManager()++ # Mock MCPClient+ mock_client = AsyncMock()+ mock_client.list_tools = AsyncMock(return_value=[])+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=None)++ def mock_client_constructor(*args, **kwargs):+ # Verify that the protocol version from request is used+ if 'protocol_version' in kwargs:+ assert kwargs['protocol_version'] == "2025-03-26"+ return mock_client++ with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):+ # Load a test server+ test_manager.load_servers_from_config({+ "test_server": {+ "url": "https://test-server.com/mcp",+ "transport": "http",+ "description": "Test Server"+ }+ })++ # Call list_tools with a specific protocol version from request+ await test_manager.list_tools(mcp_protocol_version="2025-03-26")++ # Verify the client was created with the correct protocol version+ mock_client.__aenter__.assert_called()++diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.pyindex e0d0992f968..2249b9a6fa9 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py@@ -250,7 +250,7 @@ class TestMCPRequestHandler:side_effect=mock_user_api_key_auth,) as mock_auth:# Call the method- auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = await MCPRequestHandler.process_mcp_request(scope)# Assert the resultsassert auth_result.api_key == expected_api_key@@ -260,6 +260,7 @@ class TestMCPRequestHandler:assert mcp_server_auth_headers == expected_server_auth_headers# For these tests, mcp_servers should be Noneassert mcp_servers is None+ assert mcp_protocol_version is None@pytest.mark.parametrize("headers,expected_result",@@ -418,12 +419,14 @@ class TestMCPRequestHandler:mock_user_api_key_auth.return_value = mock_auth_result# Call the method- auth_result, mcp_auth_header, mcp_servers_result, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers_result, mcp_server_auth_headers, mcp_protocol_version = await MCPRequestHandler.process_mcp_request(scope)assert auth_result == mock_auth_resultassert mcp_auth_header == expected_result["mcp_auth"]assert mcp_servers_result == expected_result["mcp_servers"]# For these tests, mcp_server_auth_headers should be emptyassert mcp_server_auth_headers == {}+ # For these tests, mcp_protocol_version should be None+ assert mcp_protocol_version is Noneclass TestMCPCustomHeaderName:@@ -582,13 +585,14 @@ class TestMCPCustomHeaderName:side_effect=mock_user_api_key_auth,) as mock_auth:# Call the method- auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = await MCPRequestHandler.process_mcp_request(scope)# Assert the resultsassert auth_result.api_key == "test-api-key"assert mcp_auth_header == "custom-auth-token"assert mcp_servers is Noneassert mcp_server_auth_headers == {}+ assert mcp_protocol_version is None# Verify the mock was calledmock_auth.assert_called_once()@@ -739,15 +743,14 @@ class TestMCPAccessGroupsE2E:side_effect=mock_user_api_key_auth,) as mock_auth:# Call the method- auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = await MCPRequestHandler.process_mcp_request(scope)# Assert the resultsassert auth_result.api_key == "test-api-key"assert mcp_auth_header is None- assert mcp_servers is None- # The access groups header should not be parsed as a server auth header- # It should be handled separately by the access groups parsing logic+ assert mcp_servers is None # x-mcp-access-groups is not parsed as mcp_serversassert mcp_server_auth_headers == {}+ assert mcp_protocol_version is None# Verify the mock was calledmock_auth.assert_called_once()@@ -783,13 +786,14 @@ class TestMCPAccessGroupsE2E:side_effect=mock_user_api_key_auth,) as mock_auth:# Call the method- auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = await MCPRequestHandler.process_mcp_request(scope)# Assert the resultsassert auth_result.api_key == "test-api-key"assert mcp_auth_header is Noneassert mcp_servers == ["server1", "dev_group", "server2"]assert mcp_server_auth_headers == {}+ assert mcp_protocol_version is None# Verify the mock was calledmock_auth.assert_called_once()@@ -806,7 +810,7 @@ def test_mcp_path_based_server_segregation(monkeypatch):async def dummy_handle_request(scope, receive, send):"""Dummy handler for testing"""# Get auth context- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = get_auth_context()+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = get_auth_context()# Capture the MCP servers for testingcaptured_mcp_servers["servers"] = mcp_serversdiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.pyindex 7097bd0d283..d67e22b6d3b 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py@@ -100,7 +100,7 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():working_server if server_id == "working_server" else failing_server)- async def mock_get_tools_from_server(server, mcp_auth_header=None):+ async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):if server.name == "working_server":# Working server returns toolstool1 = MagicMock()@@ -131,7 +131,8 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():user_api_key_auth=user_api_key_auth,mcp_auth_header=None,mcp_servers=None,- mcp_server_auth_headers=mcp_server_auth_headers+ mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=None)# Verify that tools from the working server are returned@@ -176,7 +177,7 @@ async def test_get_tools_from_mcp_servers_handles_all_servers_failing():failing_server1 if server_id == "failing_server1" else failing_server2)- async def mock_get_tools_from_server(server, mcp_auth_header=None):+ async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):# All servers failraise Exception(f"Server {server.name} connection failed")@@ -199,7 +200,8 @@ async def test_get_tools_from_mcp_servers_handles_all_servers_failing():user_api_key_auth=user_api_key_auth,mcp_auth_header=None,mcp_servers=None,- mcp_server_auth_headers=mcp_server_auth_headers+ mcp_server_auth_headers=mcp_server_auth_headers,+ mcp_protocol_version=None)# Verify that empty list is returneddiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.pyindex e8c5a7965e2..35571e61c71 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py@@ -110,7 +110,7 @@ class TestMCPServerManager:manager.get_mcp_server_by_id = MagicMock(side_effect=lambda x: server1 if x == "github" else server2)# Mock _get_tools_from_server to return different results- async def mock_get_tools_from_server(server, mcp_auth_header=None):+ async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):if server.name == "github":tool1 = MagicMock()tool1.name = "github_tool_1"@@ -157,7 +157,7 @@ class TestMCPServerManager:manager.get_mcp_server_by_id = MagicMock(return_value=server)# Mock _get_tools_from_server- async def mock_get_tools_from_server(server, mcp_auth_header=None):+ async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):assert mcp_auth_header == "legacy-token" # Should use legacy headertool = MagicMock()tool.name = "github_tool_1"@@ -190,7 +190,7 @@ class TestMCPServerManager:manager.get_mcp_server_by_id = MagicMock(return_value=server)# Mock _get_tools_from_server- async def mock_get_tools_from_server(server, mcp_auth_header=None):+ async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):assert mcp_auth_header == "server-specific-token" # Should use server-specific headertool = MagicMock()tool.name = "github_tool_1"@@ -223,7 +223,7 @@ class TestMCPServerManager:manager.get_mcp_server_by_id = MagicMock(return_value=server)# Mock _get_tools_from_server- async def mock_get_tools_from_server(server, mcp_auth_header=None):+ async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):assert mcp_auth_header == "server-specific-token" # Should use server-specific header via server_nametool = MagicMock()tool.name = "github_tool_1"diff --git a/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx b/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsxindex 8076a154738..7d0d36347f3 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx@@ -348,7 +348,8 @@ const CreateMCPServer: React.FC<CreateMCPServerProps> = ({rules={[{ required: true, message: "Please select a spec version" }]}><Select placeholder="Select MCP version" className="rounded-lg" size="large">- <Select.Option value="2025-03-26">2025-03-26 (Latest)</Select.Option>+ <Select.Option value="2025-06-18">2025-06-18 (Latest)</Select.Option>+ <Select.Option value="2025-03-26">2025-03-26</Select.Option><Select.Option value="2024-11-05">2024-11-05</Select.Option></Select></Form.Item>diff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_edit.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_edit.tsxindex 21df847e878..37a766c2cfc 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_edit.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_edit.tsx@@ -180,7 +180,8 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({ mcpServer, accessToken, o</Form.Item><Form.Item label="MCP Version" name="spec_version" rules={[{ required: true }]}><Select>- <Select.Option value="2025-03-26">2025-03-26 (Latest)</Select.Option>+ <Select.Option value="2025-06-18">2025-06-18 (Latest)</Select.Option>+ <Select.Option value="2025-03-26">2025-03-26</Select.Option><Select.Option value="2024-11-05">2024-11-05</Select.Option></Select></Form.Item>