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
fix(mcp): paginate optional discovery lists
Joshua Valluru1499d84f5a32
diff --cc litellm/experimental_mcp_client/client.pyindex 46d8823e439,4b456710057..49434befd4e--- a/litellm/experimental_mcp_client/client.py+++ b/litellm/experimental_mcp_client/client.py@@@ -4,57 -4,55 +4,63 @@@ LiteLLM Proxy uses this MCP Client to cimport asyncioimport base64+ import hashlib+ import jsonimport os--from collections.abc import Awaitable, Callable, Generator- from datetime import timedelta- from importlib import metadata- from typing import Any, Final, TypeVar-- import httpx- from mcp import ClientSession, McpError, ReadResourceResult, Resource, StdioServerParameters++from collections.abc import Awaitable, Callable, Generator, Sequence+ from contextlib import AbstractAsyncContextManager+ from functools import partial+ from types import MappingProxyType+ from typing import Any, Final, TypeAlias, TypeVar+++import anyio+ import httpx2+ from httpx2._client import UseClientDefault+ from httpx2._types import AuthTypes+ from mcp import ClientSession, MCPError, ReadResourceResult, Resource, StdioServerParametersfrom mcp.client.sse import sse_clientfrom mcp.client.stdio import stdio_client+ from mcp.client.streamable_http import streamable_http_client+ from mcp.shared._stream_protocols import ReadStream, WriteStream+ from mcp.shared.message import SessionMessage- streamable_http_client: Any | None = None- try:- import mcp.client.streamable_http as streamable_http_module-- streamable_http_client = getattr(streamable_http_module, "streamable_http_client", None)- except ImportError:- pass-- MCP_STREAMABLE_HTTP_REQUIREMENT: Final = "mcp>=1.28.1"+ _TransportStreams: TypeAlias = tuple[+ ReadStream[SessionMessage | Exception],+ WriteStream[SessionMessage],+ ]+ _TransportContext: TypeAlias = AbstractAsyncContextManager[_TransportStreams]- def missing_streamable_http_client_error() -> ImportError:- return ImportError(- f"MCP streamable HTTP transport requires {MCP_STREAMABLE_HTTP_REQUIREMENT}, but the installed "- f"mcp {metadata.version('mcp')} does not provide streamable_http_client. "- "Fix with: pip install 'litellm[mcp]' (or upgrade mcp directly: pip install -U mcp)"- )--- from mcp.types import CallToolRequestParams as MCPCallToolRequestParams- from mcp.types import CallToolResult as MCPCallToolResultfrom mcp.types import (+ METHOD_NOT_FOUND,+ REQUEST_TIMEOUT,GetPromptRequestParams,GetPromptResult,+ ListPromptsResult,+ ListResourcesResult,+ ListResourceTemplatesResult,++ PaginatedRequestParams,++ PaginatedResult,Prompt,ResourceTemplate,+ ServerNotification,TextContent,)+ from mcp.types import CallToolRequestParams as MCPCallToolRequestParams+ from mcp.types import CallToolResult as MCPCallToolResultfrom mcp.types import Tool as MCPToolfrom pydantic import AnyUrlfrom litellm._logging import verbose_logger- from litellm.constants import MCP_CLIENT_TIMEOUT, MCP_NPM_CACHE_DIR- from litellm.experimental_mcp_client.pagination import (- list_all_prompts,- list_all_resource_templates,- list_all_resources,- list_all_tools,-from litellm.constants import MCP_CLIENT_TIMEOUT, MCP_NPM_CACHE_DIR, MCP_TOOL_LISTING_TIMEOUT++from litellm.constants import (++ MCP_CLIENT_TIMEOUT,++ MCP_NPM_CACHE_DIR,++ MCP_TOOL_LISTING_MAX_PAGES,++ MCP_TOOL_LISTING_TIMEOUT,+)+ from litellm.experimental_mcp_client.tools import list_tools_with_paginationfrom litellm.llms.custom_httpx.http_handler import get_ssl_configuration+ from litellm.proxy._experimental.mcp_server.mcp_debug import capture_upstream_error_responsefrom litellm.types.llms.custom_http import VerifyTypesfrom litellm.types.mcp import (MCPAuth,@@@ -152,11 -147,27 +155,29 @@@ def as_mcp_read_timeout(exc: BaseExceptTSessionResult = TypeVar("TSessionResult")++_ListPage = TypeVar("_ListPage", bound=PaginatedResult)++_ListItem = TypeVar("_ListItem")- class MCPSigV4Auth(httpx.Auth):+ class _MCPHTTPClient(httpx2.AsyncClient):+ async def send(+ self,+ request: httpx2.Request,+ *,+ stream: bool = False,+ auth: AuthTypes | UseClientDefault | None = httpx2.USE_CLIENT_DEFAULT,+ follow_redirects: bool | UseClientDefault = httpx2.USE_CLIENT_DEFAULT,+ ) -> httpx2.Response:+ response: Final = await super().send(request, stream=stream, auth=auth, follow_redirects=follow_redirects)+ if request.method == "POST" and response.is_error and response.status_code != 404:+ await response.aclose()+ response.raise_for_status()+ return response+++ class MCPSigV4Auth(httpx2.Auth):"""- httpx Auth class that signs each request with AWS SigV4.+ httpx2 Auth class that signs each request with AWS SigV4.This is used for MCP servers that require AWS SigV4 authentication,such as AWS Bedrock AgentCore MCP servers. httpx calls auth_flow()for every outgoing request, enabling per-request signature computation.@@@ -738,21 -793,32 +803,63 @@@ class MCPClient# Return a default error result instead of raisingreturn self.error_tool_result(e)- async def list_prompts(self) -> list[Prompt]:++ async def _list_optional_pages(++ self,++ fetch_page: Callable[[PaginatedRequestParams | None], Awaitable[_ListPage]],++ items_of: Callable[[_ListPage], Sequence[_ListItem]],++ ) -> list[_ListItem]: # mutable-ok: existing list discovery API++ items: Final[list[_ListItem]] = [] # mutable-ok: bounded iterative page accumulation++ cursors: Final[set[str]] = set() # mutable-ok: constant-time detection of cursor cycles++ cursor: str | None = None # rebind-ok: iterative traversal avoids recursion at the existing page cap++ with anyio.fail_after(max(self.timeout, MCP_TOOL_LISTING_TIMEOUT)):++ for page_index in range(MCP_TOOL_LISTING_MAX_PAGES):++ try:++ page = await fetch_page( # rebind-ok: each SDK page replaces the previous one++ None if cursor is None else PaginatedRequestParams(cursor=cursor)++ )++ except MCPError as error:++ if page_index > 0 and error.error.code == METHOD_NOT_FOUND:++ raise RuntimeError("MCP list operation became unavailable during pagination") from error++ raise++ items.extend(items_of(page))++ if not page.next_cursor:++ return items++ if page.next_cursor in cursors:++ raise RuntimeError("MCP list pagination repeated a cursor")++ cursors.add(page.next_cursor)++ cursor = page.next_cursor++ raise RuntimeError(f"MCP list pagination exceeded {MCP_TOOL_LISTING_MAX_PAGES} pages")+++ async def list_prompts(self, *, raise_on_error: bool = False) -> list[Prompt]:"""List available prompts from the server."""verbose_logger.debug("MCP client listing tools from %s", self.server_url or "stdio")- async def _list_prompts_operation(session: ClientSession) -> tuple[Prompt, ...]:- return await list_all_prompts(session, self.server_url or "stdio")+ async def _list_prompts_operation(session: ClientSession) -> ListPromptsResult:+ capabilities: Final = session.server_capabilities+ if capabilities is not None and capabilities.prompts is None:+ return ListPromptsResult(prompts=[])+ try:- return await session.list_prompts()++ return ListPromptsResult(++ prompts=await self._list_optional_pages(++ lambda params: session.list_prompts(params=params), lambda page: page.prompts++ )++ )+ except MCPError as error:+ if error.error.code != METHOD_NOT_FOUND:+ raise+ verbose_logger.debug(+ "MCP client list_prompts is unsupported by %s: %s", self.server_url or "stdio", error+ )+ return ListPromptsResult(prompts=[])try:- prompts: Final = await self.run_with_session(_list_prompts_operation)- prompt_count: Final = len(prompts)- prompt_names: Final = tuple(prompt.name for prompt in prompts)+ result: Final = await self.run_with_session(_list_prompts_operation)+ prompt_count: Final = len(result.prompts)+ prompt_names: Final = [prompt.name for prompt in result.prompts]verbose_logger.info(- "MCP client listed %s prompts from %s: %s", prompt_count, self.server_url or "stdio", prompt_names+ "MCP client listed %s tools from %s: %s", prompt_count, self.server_url or "stdio", prompt_names)- return list(prompts)+ return result.promptsexcept asyncio.CancelledError:verbose_logger.warning("MCP client list_prompts was cancelled")raise@@@ -819,13 -887,24 +928,28 @@@"""List available resources from the server."""verbose_logger.debug("MCP client listing resources from %s", self.server_url or "stdio")- async def _list_resources_operation(session: ClientSession) -> tuple[Resource, ...]:- return await list_all_resources(session, self.server_url or "stdio")+ async def _list_resources_operation(session: ClientSession) -> ListResourcesResult:+ capabilities: Final = session.server_capabilities+ if capabilities is not None and capabilities.resources is None:+ return ListResourcesResult(resources=[])+ try:- return await session.list_resources()++ return ListResourcesResult(++ resources=await self._list_optional_pages(++ lambda params: session.list_resources(params=params), lambda page: page.resources++ )++ )+ except MCPError as error:+ if error.error.code != METHOD_NOT_FOUND:+ raise+ verbose_logger.debug(+ "MCP client list_resources is unsupported by %s: %s", self.server_url or "stdio", error+ )+ return ListResourcesResult(resources=[])try:- resources: Final = await self.run_with_session(_list_resources_operation)- resource_count: Final = len(resources)- resource_names: Final = tuple(resource.name for resource in resources)+ result: Final = await self.run_with_session(_list_resources_operation)+ resource_count: Final = len(result.resources)+ resource_names: Final = [resource.name for resource in result.resources]verbose_logger.info("MCP client listed %s resources from %s: %s", resource_count, self.server_url or "stdio", resource_names)@@@ -855,13 -936,24 +981,29 @@@"""List available resource templates from the server."""verbose_logger.debug("MCP client listing resource templates from %s", self.server_url or "stdio")- async def _list_resource_templates_operation(session: ClientSession) -> tuple[ResourceTemplate, ...]:- return await list_all_resource_templates(session, self.server_url or "stdio")+ async def _list_resource_templates_operation(session: ClientSession) -> ListResourceTemplatesResult:+ capabilities: Final = session.server_capabilities+ if capabilities is not None and capabilities.resources is None:+ return ListResourceTemplatesResult(resource_templates=[]) # mutable-ok: MCP result payload+ try:- return await session.list_resource_templates()++ return ListResourceTemplatesResult(++ resource_templates=await self._list_optional_pages(++ lambda params: session.list_resource_templates(params=params),++ lambda page: page.resource_templates,++ )++ )+ except MCPError as error:+ if error.error.code != METHOD_NOT_FOUND:+ raise+ verbose_logger.debug(+ "MCP client list_resource_templates is unsupported by %s: %s", self.server_url or "stdio", error+ )+ return ListResourceTemplatesResult(resource_templates=[]) # mutable-ok: MCP result payloadtry:- resource_templates: Final = await self.run_with_session(_list_resource_templates_operation)- resource_template_count: Final = len(resource_templates)- resource_template_names: Final = tuple(resource_template.name for resource_template in resource_templates)+ result: Final = await self.run_with_session(_list_resource_templates_operation)+ resource_template_count: Final = len(result.resource_templates)+ resource_template_names: Final = [resource_template.name for resource_template in result.resource_templates]verbose_logger.info("MCP client listed %s resource templates from %s: %s",resource_template_count,diff --cc tests/test_litellm/experimental_mcp_client/test_mcp_client.pyindex 3f501d3859a,4b698f1258d..6c20ef135ba--- a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py+++ b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py@@@ -1327,3 -1422,778 +1422,1036 @@@ def test_a_differently_cased_injected_hheaders = client._get_auth_headers()assert [v for k, v in headers.items() if k.lower() == "esb-oauth"] == ["Bearer minted-token"]assert headers["X-Trace"] == "keep"+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("content_type", "body", "expected_type"),+ [+ ("text/html", b"<html>secret-page</html>", MCPError),+ ("application/json", b"secret-invalid-json", MCPError),+ ("application/json", b"", MCPError),+ ("application/json", b'{"secret":"invalid-rpc"}', MCPError),+ ("application/json", b'{"jsonrpc":"2.0","id":0}', MCPError),+ ("application/json", b'{"jsonrpc":"2.0","id":0,"result":{"secret":"bad-schema"}}', ValidationError),+ ],+ )+ async def test_invalid_http_response_surfaces_without_waiting_for_timeout(+ content_type: str, body: bytes, expected_type: type[Exception]+ ) -> None:+ from litellm.proxy._experimental.mcp_server.rest_endpoints import _connection_error_message++ def respond(request: httpx2.Request) -> httpx2.Response:+ if expected_type is ValidationError:+ return httpx2.Response(200, json={**json.loads(body), "id": json.loads(request.content)["id"]})+ return httpx2.Response(200, headers={"Content-Type": content_type}, content=body)++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http_client:+ client: Final = MCPClient(server_url="https://example.com/mcp", timeout=30)+ with pytest.raises(expected_type) as caught:+ await asyncio.wait_for(+ client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client),+ lambda session: session.list_tools(),+ ),+ timeout=3,+ )++ message: Final = _connection_error_message(caught.value, client.server_url, 30)+ assert "unsupported content type" in message or "invalid MCP response" in message+ assert "secret" not in message+ assert "timed out" not in message+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("status_code", [200, 401, 403, 429, 503])+ async def test_http_response_handler_preserves_success_and_http_errors(status_code: int) -> None:+ def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = json.loads(request.content)+ if "id" not in payload:+ return httpx2.Response(202)+ result: Final = (+ {+ "protocolVersion": payload["params"]["protocolVersion"],+ "capabilities": {},+ "serverInfo": {"name": "test", "version": "1"},+ }+ if payload["method"] == "initialize"+ else {"tools": []}+ )+ return httpx2.Response(status_code, json={"jsonrpc": "2.0", "id": payload["id"], "result": result})++ client: Final = MCPClient(server_url="https://example.com/mcp", timeout=30)+ async with client._create_httpx_client_factory(transport=httpx2.MockTransport(respond))() as http_client:+ operation: Final = client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()+ )+ if status_code == 200:+ result: Final = await asyncio.wait_for(operation, timeout=3)+ assert result.tools == []+ else:+ with pytest.raises(httpx2.HTTPStatusError) as caught:+ await asyncio.wait_for(operation, timeout=3)+ assert caught.value.response.status_code == status_code+++ @pytest.mark.asyncio+ async def test_http_status_check_allows_auth_refresh_before_rejecting() -> None:+ from litellm.proxy._experimental.mcp_server.outbound_credentials.client_credentials import ClientCredentialsBearerAuth++ seen = []++ async def refresh(failed):+ assert failed == "stale"+ return "fresh"++ def respond(request):+ seen.append(request.headers["authorization"])+ return httpx2.Response(401 if len(seen) == 1 else 200, json={"ok": True})++ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ClientCredentialsConfig++ auth = ClientCredentialsBearerAuth("stale", refresh, ClientCredentialsConfig())+ client = MCPClient(server_url="https://example.com/mcp", resolved_auth=auth)+ async with client._create_httpx_client_factory(transport=httpx2.MockTransport(respond))() as http_client:+ response = await http_client.post(client.server_url, json={"method": "tools/list"})+ assert response.status_code == 200+ assert seen == ["Bearer stale", "Bearer fresh"]+++ @pytest.mark.asyncio+ async def test_http_response_handler_preserves_notifications_and_tool_listing() -> None:+ notification: Final = {+ "jsonrpc": "2.0",+ "method": "notifications/message",+ "params": {"level": "info", "data": "Listing tools"},+ }+ logging_callback: Final = AsyncMock()++ def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = json.loads(request.content)+ if "id" not in payload:+ return httpx2.Response(202)+ if payload["method"] == "initialize":+ return httpx2.Response(+ 200,+ json={+ "jsonrpc": "2.0",+ "id": payload["id"],+ "result": {+ "protocolVersion": payload["params"]["protocolVersion"],+ "capabilities": {"logging": {}, "tools": {}},+ "serverInfo": {"name": "test", "version": "1"},+ },+ },+ )+ response: Final = {+ "jsonrpc": "2.0",+ "id": payload["id"],+ "result": {"tools": [{"name": "search", "inputSchema": {"type": "object"}}]},+ }+ return httpx2.Response(+ 200,+ headers={"Content-Type": "text/event-stream"},+ content="".join(f"event: message\ndata: {json.dumps(message)}\n\n" for message in (notification, response)),+ )++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http_client:+ client: Final = MCPClient(server_url="https://example.com/mcp", timeout=30, logging_callback=logging_callback)+ result: Final = await asyncio.wait_for(+ client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()+ ),+ timeout=3,+ )++ assert [tool.name for tool in result.tools] == ["search"]+ logging_callback.assert_awaited_once_with(LoggingMessageNotificationParams(level="info", data="Listing tools"))+++ @pytest.mark.asyncio+ async def test_invalid_tool_list_schema_is_identified_as_an_upstream_response() -> None:+ from litellm.proxy._experimental.mcp_server.rest_endpoints import _connection_error_message++ def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = json.loads(request.content)+ if "id" not in payload:+ return httpx2.Response(202)+ result: Final = (+ {+ "protocolVersion": payload["params"]["protocolVersion"],+ "capabilities": {},+ "serverInfo": {"name": "test", "version": "1"},+ }+ if payload["method"] == "initialize"+ else {"tools": "secret-invalid-tools"}+ )+ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload["id"], "result": result})++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http_client:+ client: Final = MCPClient(server_url="https://example.com/mcp", timeout=30)+ with pytest.raises(ValidationError) as caught:+ await asyncio.wait_for(+ client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client),+ lambda session: session.list_tools(),+ ),+ timeout=3,+ )++ message: Final = _connection_error_message(caught.value, client.server_url, 30)+ assert "invalid MCP response" in message+ assert "secret" not in message+++ class _DiagnosticSSEStream(httpx2.AsyncByteStream):+ def __init__(self, messages: asyncio.Queue[bytes | Exception | None]) -> None:+ self.messages = messages++ async def __aiter__(self) -> AsyncIterator[bytes]:+ yield b"event: endpoint\ndata: /messages\n\n"+ while True:+ message: Final = await self.messages.get()+ if message is None:+ return+ if isinstance(message, Exception):+ raise message+ yield b"event: message\ndata: " + message + b"\n\n"+++ _DIAGNOSTIC_STDIO_SERVER: Final = """+ import json, sys+ mode, failure_method = sys.argv[1:]+ for line in sys.stdin:+ request = json.loads(line)+ if "method" not in request or "id" not in request:+ continue+ if request["method"] == failure_method:+ if mode == "bad-json":+ print("secret-invalid-json", flush=True)+ continue+ if mode == "closed":+ sys.exit(0)+ if mode == "silent":+ print(json.dumps({"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "Waiting"}}), flush=True)+ continue+ if request["method"] == "initialize":+ result = {"protocolVersion": request["params"]["protocolVersion"], "capabilities": {"tools": {}, "logging": {}}, "serverInfo": {"name": "diagnostic", "version": "1"}}+ elif request["method"] == "tools/list":+ print(json.dumps({"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "Listing tools"}}), flush=True)+ print(json.dumps({"jsonrpc": "2.0", "id": "unmatched", "result": {}}), flush=True)+ print(json.dumps({"jsonrpc": "2.0", "id": "server-ping", "method": "ping"}), flush=True)+ result = {"tools": [{"name": "ping", "inputSchema": {"type": "object"}}]}+ else:+ result = {"content": [{"type": "text", "text": "pong"}], "isError": False}+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)+ """+++ def _diagnostic_transport(transport: MCPTransport, mode: str, failure_method: str) -> _TransportContext:+ from mcp import StdioServerParameters+ from mcp.client.sse import sse_client+ from mcp.client.stdio import stdio_client++ if transport == MCPTransport.stdio:+ return stdio_client(+ StdioServerParameters(+ command=sys.executable, args=["-u", "-c", _DIAGNOSTIC_STDIO_SERVER, mode, failure_method]+ )+ )+ messages: Final[asyncio.Queue[bytes | Exception | None]] = asyncio.Queue()++ async def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "GET":+ return httpx2.Response(+ 200, headers={"Content-Type": "text/event-stream"}, stream=_DiagnosticSSEStream(messages)+ )+ payload: Final = json.loads(request.content)+ if "method" not in payload or "id" not in payload:+ return httpx2.Response(202)+ if payload["method"] == failure_method and mode != "ok":+ if mode == "bad-json":+ await messages.put(b"secret-invalid-json")+ elif mode == "io-error":+ await messages.put(httpx2.ReadError("secret-read-error"))+ elif mode == "closed":+ await messages.put(None)+ elif mode == "silent":+ await messages.put(+ b'{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"Waiting"}}'+ )+ return httpx2.Response(202)+ if payload["method"] == "tools/list":+ for message in (+ {+ "jsonrpc": "2.0",+ "method": "notifications/message",+ "params": {"level": "info", "data": "Listing tools"},+ },+ {"jsonrpc": "2.0", "id": "unmatched", "result": {}},+ {"jsonrpc": "2.0", "id": "server-ping", "method": "ping"},+ ):+ await messages.put(json.dumps(message).encode())+ result: Final = (+ {+ "protocolVersion": payload["params"]["protocolVersion"],+ "capabilities": {"tools": {}, "logging": {}},+ "serverInfo": {"name": "diagnostic", "version": "1"},+ }+ if payload["method"] == "initialize"+ else {"tools": [{"name": "ping", "inputSchema": {"type": "object"}}]}+ if payload["method"] == "tools/list"+ else {"content": [{"type": "text", "text": "pong"}], "isError": False}+ )+ await messages.put(json.dumps({"jsonrpc": "2.0", "id": payload["id"], "result": result}).encode())+ return httpx2.Response(202)++ def factory(+ headers: dict[str, str] | None = None,+ timeout: httpx2.Timeout | None = None,+ auth: httpx2.Auth | None = None,+ ) -> httpx2.AsyncClient:+ return httpx2.AsyncClient(transport=httpx2.MockTransport(respond), headers=headers, timeout=timeout, auth=auth)++ return sse_client("https://example.com/sse", httpx_client_factory=factory)+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("transport", [MCPTransport.sse, MCPTransport.stdio])+ @pytest.mark.parametrize("failure_method", ["initialize", "tools/list"])+ async def test_transport_parsing_failure_is_preserved(transport: MCPTransport, failure_method: str) -> None:+ client: Final = MCPClient(server_url="https://example.com/sse", transport_type=transport, timeout=0.2)+ with pytest.raises(ValidationError):+ await asyncio.wait_for(+ client._execute_session_operation(+ _diagnostic_transport(transport, "bad-json", failure_method), lambda session: session.list_tools()+ ),+ timeout=3,+ )+++ @pytest.mark.asyncio+ async def test_sse_read_failure_is_preserved() -> None:+ client: Final = MCPClient(server_url="https://example.com/sse", transport_type=MCPTransport.sse, timeout=0.2)+ with pytest.raises(httpx2.ReadError, match="secret-read-error"):+ await asyncio.wait_for(+ client._execute_session_operation(+ _diagnostic_transport(MCPTransport.sse, "io-error", "tools/list"), lambda session: session.list_tools()+ ),+ timeout=3,+ )+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("transport", [MCPTransport.sse, MCPTransport.stdio])+ @pytest.mark.parametrize("mode", ["ok", "closed", "silent"])+ async def test_transport_completion_and_normal_messages(transport: MCPTransport, mode: str) -> None:+ from mcp import ClientSession+ from litellm.proxy._experimental.mcp_server.rest_endpoints import _connection_error_message++ logging_callback: Final = AsyncMock()+ client: Final = MCPClient(+ server_url="https://example.com/sse", transport_type=transport, timeout=0.2, logging_callback=logging_callback+ )++ async def operation(session: ClientSession) -> CallToolResult:+ tools: Final = await session.list_tools()+ assert [tool.name for tool in tools.tools] == ["ping"]+ return await session.call_tool("ping", {})++ pending: Final = client._execute_session_operation(_diagnostic_transport(transport, mode, "tools/list"), operation)+ if mode == "ok":+ result: Final = await asyncio.wait_for(pending, timeout=3)+ assert result.is_error is False+ assert result.content[0].text == "pong"+ logging_callback.assert_awaited_once_with(LoggingMessageNotificationParams(level="info", data="Listing tools"))+ else:+ with pytest.raises(MCPError) as caught:+ await asyncio.wait_for(pending, timeout=3)+ if mode == "closed":+ assert "connection was closed" in _connection_error_message(caught.value, client.server_url, 0.2)+ else:+ assert isinstance(as_mcp_read_timeout(caught.value), TimeoutError)+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("transport", [MCPTransport.sse, MCPTransport.stdio])+ async def test_transport_cancellation_cleans_up_a_pending_request(transport: MCPTransport) -> None:+ ready: Final = asyncio.Event()++ async def on_log(message: LoggingMessageNotificationParams) -> None:+ if message.data == "Waiting":+ ready.set()++ client: Final = MCPClient(+ server_url="https://example.com/sse", transport_type=transport, timeout=30, logging_callback=on_log+ )+ task: Final = asyncio.create_task(+ client._execute_session_operation(+ _diagnostic_transport(transport, "silent", "tools/list"), lambda session: session.list_tools()+ )+ )+ try:+ await asyncio.wait_for(ready.wait(), timeout=3)+ finally:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=3)+++ class _InterruptedHTTPBody(httpx2.AsyncByteStream):+ async def __aiter__(self) -> AsyncIterator[bytes]:+ yield b'{"jsonrpc":'+ raise httpx2.RemoteProtocolError("secret-incomplete-response")+++ @pytest.mark.asyncio+ async def test_interrupted_http_response_preserves_the_transport_failure() -> None:+ def respond(request: httpx2.Request) -> httpx2.Response:+ return httpx2.Response(200, headers={"Content-Type": "application/json"}, stream=_InterruptedHTTPBody())++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http_client:+ client: Final = MCPClient(server_url="https://example.com/mcp", timeout=30)+ with pytest.raises(httpx2.RemoteProtocolError, match="secret-incomplete-response"):+ await asyncio.wait_for(+ client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client),+ lambda session: session.list_tools(),+ ),+ timeout=3,+ )+++ @pytest.mark.asyncio+ async def test_empty_http_event_stream_uses_the_existing_request_deadline() -> None:+ def respond(request: httpx2.Request) -> httpx2.Response:+ return httpx2.Response(200, headers={"Content-Type": "text/event-stream"}, content=b"")++ async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http_client:+ client: Final = MCPClient(server_url="https://example.com/mcp", timeout=0.2)+ with pytest.raises(MCPError) as caught:+ await asyncio.wait_for(+ client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client),+ lambda session: session.list_tools(),+ ),+ timeout=3,+ )+ assert caught.value.error.code == CONNECTION_CLOSED+ assert "SSE stream ended" in caught.value.error.message+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("method", ("prompts/list", "resources/list", "resources/templates/list"))+ @pytest.mark.parametrize(+ "outcome",+ (+ "absent",+ "other_capability",+ "supported",+ "method_not_found",+ "internal_error",+ "unauthorized",+ "timeout",+ "initialize_not_found",+ ),+ )+ @pytest.mark.parametrize("raise_on_error", (False, True))+ async def test_optional_discovery_capabilities_and_errors(+ method: str, outcome: str, caplog: pytest.LogCaptureFixture, raise_on_error: bool+ ) -> None:+ import logging+ from unittest.mock import Mock++ from mcp.types import JSONRPCRequest++ capability: Final = "prompts" if method == "prompts/list" else "resources"+ field: Final = {+ "prompts/list": "prompts",+ "resources/list": "resources",+ "resources/templates/list": "resourceTemplates",+ }[method]+ advertised: Final = "resources" if capability == "prompts" else "prompts"+ entry: Final = {+ "prompts/list": {"name": "example"},+ "resources/list": {"name": "example", "uri": "test://example"},+ "resources/templates/list": {"name": "example", "uriTemplate": "test://{name}"},+ }[method]++ def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)+ if not isinstance(payload, JSONRPCRequest):+ return httpx2.Response(202)+ if outcome == "initialize_not_found":+ return httpx2.Response(+ 200,+ json={+ "jsonrpc": "2.0",+ "id": payload.id,+ "error": {"code": -32601, "message": "Initialization rejected"},+ },+ )+ if payload.method == "initialize":+ return httpx2.Response(+ 200,+ json={+ "jsonrpc": "2.0",+ "id": payload.id,+ "result": {+ "protocolVersion": payload.params["protocolVersion"],+ "capabilities": {}+ if outcome == "absent"+ else {advertised if outcome == "other_capability" else capability: {}},+ "serverInfo": {"name": "discovery", "version": "1"},+ },+ },+ )+ if outcome == "timeout":+ raise httpx2.ReadTimeout("Optional list timed out", request=request)+ if outcome == "unauthorized":+ return httpx2.Response(401)+ if outcome in ("method_not_found", "internal_error", "absent", "other_capability"):+ return httpx2.Response(+ 200,+ json={+ "jsonrpc": "2.0",+ "id": payload.id,+ "error": {+ "code": -32603 if outcome == "internal_error" else -32601,+ "message": "Optional list rejected",+ },+ },+ )+ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": {field: [entry]}})++ responder: Final = Mock(side_effect=respond)+ caplog.set_level(logging.DEBUG, logger="LiteLLM")+ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp")+ operation: Final = {+ "prompts/list": client.list_prompts,+ "resources/list": client.list_resources,+ "resources/templates/list": client.list_resource_templates,+ }[method]+ if raise_on_error and outcome in ("internal_error", "unauthorized", "timeout", "initialize_not_found"):+ with pytest.raises((MCPError, httpx2.HTTPError)):+ await operation(raise_on_error=True)+ return+ result: Final = await operation(raise_on_error=raise_on_error)++ requests: Final = tuple(+ _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content)+ for call in responder.call_args_list+ if call.args[0].method == "POST"+ )+ assert sum(isinstance(request, JSONRPCRequest) and request.method == method for request in requests) == (+ 0 if outcome in ("absent", "other_capability", "initialize_not_found") else 1+ )+ assert [item.name for item in result] == (["example"] if outcome == "supported" else [])+ failures: Final = tuple(+ record for record in caplog.records if record.name == "LiteLLM" and record.levelno >= logging.WARNING+ )+ if outcome in ("internal_error", "unauthorized", "timeout", "initialize_not_found"):+ assert any(record.levelno == logging.ERROR and "failed" in record.message for record in failures)+ else:+ assert failures == ()+ if outcome == "method_not_found":+ assert any(+ record.levelno == logging.DEBUG and "Optional list rejected" in record.message for record in caplog.records+ )+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("supports_first", (True, False))+ async def test_optional_discovery_uses_each_sessions_capabilities(supports_first: bool) -> None:+ from unittest.mock import Mock++ from mcp.types import JSONRPCRequest++ capabilities: Final = iter(({"resources": {}}, {}) if supports_first else ({}, {"resources": {}}))++ def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)+ if not isinstance(payload, JSONRPCRequest):+ return httpx2.Response(202)+ result: Final = (+ {+ "protocolVersion": payload.params["protocolVersion"],+ "capabilities": next(capabilities),+ "serverInfo": {"name": "changing", "version": "1"},+ }+ if payload.method == "initialize"+ else {"resources": [{"name": "example", "uri": "test://example"}]}+ )+ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": result})++ responder: Final = Mock(side_effect=respond)+ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp")+ first: Final = await client.list_resources()+ second: Final = await client.list_resources()++ assert [item.name for item in first] == (["example"] if supports_first else [])+ assert [item.name for item in second] == ([] if supports_first else ["example"])+ requests: Final = tuple(+ _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content)+ for call in responder.call_args_list+ if call.args[0].method == "POST"+ )+ assert sum(isinstance(request, JSONRPCRequest) and request.method == "resources/list" for request in requests) == 1+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("method", ("prompts/list", "resources/list", "resources/templates/list"))+ async def test_optional_discovery_preserves_cancellation(method: str) -> None:+ from mcp.types import JSONRPCRequest++ ready: Final = asyncio.Event()+ pending: Final = asyncio.Event()++ async def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)+ if not isinstance(payload, JSONRPCRequest):+ return httpx2.Response(202)+ if payload.method == "initialize":+ return httpx2.Response(+ 200,+ json={+ "jsonrpc": "2.0",+ "id": payload.id,+ "result": {+ "protocolVersion": payload.params["protocolVersion"],+ "capabilities": {"resources": {}, "prompts": {}},+ "serverInfo": {"name": "pending", "version": "1"},+ },+ },+ )++ if not (payload.params or {}).get("cursor"):++ field: Final = {++ "prompts/list": "prompts",++ "resources/list": "resources",++ "resources/templates/list": "resourceTemplates",++ }[method]++ return httpx2.Response(++ 200, json={"jsonrpc": "2.0", "id": payload.id, "result": {field: [], "nextCursor": "pending-page"}}++ )+ ready.set()+ await pending.wait()+ return httpx2.Response(202)++ client: Final = _MockTransportClient(respond, server_url="https://example.com/mcp")+ operation: Final = {+ "prompts/list": client.list_prompts,+ "resources/list": client.list_resources,+ "resources/templates/list": client.list_resource_templates,+ }[method]+ task: Final = asyncio.create_task(operation())+ try:+ await asyncio.wait_for(ready.wait(), timeout=3)+ finally:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=3)++[email protected]("method", ("prompts/list", "resources/list", "resources/templates/list"))[email protected]("session_id", (None, "pagination-session"))[email protected]("empty_middle", (False, True))++async def test_optional_discovery_collects_all_pages(method: str, session_id: str | None, empty_middle: bool) -> None:++ from mcp.types import Prompt, PromptArgument, Resource, ResourceTemplate++++ field: Final = {++ "prompts/list": "prompts",++ "resources/list": "resources",++ "resources/templates/list": "resourceTemplates",++ }[method]++ entries: Final = tuple(++ {++ "prompts/list": Prompt(++ name=f"item-{index}",++ description="prompt description",++ arguments=[PromptArgument(name="query", required=True)],++ ),++ "resources/list": Resource(++ name=f"item-{index}",++ uri=f"test://item/{index}",++ mime_type="text/plain",++ description="resource description",++ ),++ "resources/templates/list": ResourceTemplate(++ name=f"item-{index}", uri_template=f"test://item/{index}/{{query}}", mime_type="text/plain"++ ),++ }[method]++ for index in range(5)++ )++++ def respond(request: httpx2.Request) -> httpx2.Response:++ if request.method == "GET":++ return httpx2.Response(405)++ if request.method == "DELETE":++ return httpx2.Response(200)++ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)++ if not isinstance(payload, JSONRPCRequest):++ return httpx2.Response(202)++ if payload.method == "initialize":++ return httpx2.Response(++ 200,++ headers={"mcp-session-id": session_id} if session_id else {},++ json={++ "jsonrpc": "2.0",++ "id": payload.id,++ "result": {++ "protocolVersion": payload.params["protocolVersion"],++ "capabilities": {"prompts": {}, "resources": {}},++ "serverInfo": {"name": "paged", "version": "1"},++ },++ },++ )++ assert payload.method == method++ assert request.headers.get("mcp-session-id") == session_id++ cursor: Final = (payload.params or {}).get("cursor")++ assert cursor in (None, "opaque:/second+page", "opaque:/last+page")++ page: Final = (++ entries[:3] if cursor is None else (() if empty_middle and cursor == "opaque:/second+page" else entries[3:])++ )++ next_cursor: Final = (++ "opaque:/second+page"++ if cursor is None++ else "opaque:/last+page"++ if empty_middle and cursor == "opaque:/second+page"++ else ""++ )++ return httpx2.Response(++ 200,++ json={++ "jsonrpc": "2.0",++ "id": payload.id,++ "result": {++ field: [item.model_dump(mode="json", by_alias=True) for item in page],++ "nextCursor": next_cursor,++ },++ },++ )++++ responder: Final = Mock(side_effect=respond)++ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp")++ operation: Final = {++ "prompts/list": client.list_prompts,++ "resources/list": client.list_resources,++ "resources/templates/list": client.list_resource_templates,++ }[method]++ assert await operation(raise_on_error=True) == list(entries)++ requests: Final = tuple(++ _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content)++ for call in responder.call_args_list++ if call.args[0].method == "POST"++ )++ assert sum(isinstance(request, JSONRPCRequest) and request.method == "initialize" for request in requests) == 1++ assert tuple(++ (request.params or {}).get("cursor")++ for request in requests++ if isinstance(request, JSONRPCRequest) and request.method == method++ ) == ((None, "opaque:/second+page", "opaque:/last+page") if empty_middle else (None, "opaque:/second+page"))++ assert sum(call.args[0].method == "DELETE" for call in responder.call_args_list) == (1 if session_id else 0)++++[email protected]("method", ("prompts/list", "resources/list", "resources/templates/list"))++ "failure", ("repeat", "cycle", "cap", "method_not_found", "internal_error", "unauthorized", "deadline")++)[email protected]("strict", (False, True))++async def test_optional_discovery_rejects_incomplete_walks(++ method: str, failure: str, strict: bool, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture++) -> None:++ monkeypatch.setattr(mcp_client_module, "MCP_TOOL_LISTING_MAX_PAGES", 3 if failure == "cycle" else 2, raising=False)++ monkeypatch.setattr(mcp_client_module, "MCP_TOOL_LISTING_TIMEOUT", 0.05)++ field: Final = {++ "prompts/list": "prompts",++ "resources/list": "resources",++ "resources/templates/list": "resourceTemplates",++ }[method]++ entry: Final = {++ "prompts/list": {"name": "first"},++ "resources/list": {"name": "first", "uri": "test://first"},++ "resources/templates/list": {"name": "first", "uriTemplate": "test://{name}"},++ }[method]++ cancelled: Final = asyncio.Event()++++ async def respond(request: httpx2.Request) -> httpx2.Response:++ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)++ if not isinstance(payload, JSONRPCRequest):++ return httpx2.Response(202)++ if payload.method == "initialize":++ return httpx2.Response(++ 200,++ json={++ "jsonrpc": "2.0",++ "id": payload.id,++ "result": {++ "protocolVersion": payload.params["protocolVersion"],++ "capabilities": {"prompts": {}, "resources": {}},++ "serverInfo": {"name": "interrupted", "version": "1"},++ },++ },++ )++ assert payload.method == method++ cursor: Final = (payload.params or {}).get("cursor")++ if cursor is not None:++ if failure == "deadline":++ try:++ await asyncio.Event().wait()++ finally:++ cancelled.set()++ if failure == "unauthorized":++ return httpx2.Response(401)++ if failure in ("method_not_found", "internal_error"):++ return httpx2.Response(++ 200,++ json={++ "jsonrpc": "2.0",++ "id": payload.id,++ "error": {++ "code": -32601 if failure == "method_not_found" else -32603,++ "message": "Later page unavailable",++ },++ },++ )++ next_cursor: Final = (++ "private-cursor-2" if cursor == "private-cursor-1" and failure != "repeat" else "private-cursor-1"++ )++ return httpx2.Response(++ 200, json={"jsonrpc": "2.0", "id": payload.id, "result": {field: [entry], "nextCursor": next_cursor}}++ )++++ responder: Final = AsyncMock(side_effect=respond)++ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp", timeout=0.2)++ operation: Final = {++ "prompts/list": client.list_prompts,++ "resources/list": client.list_resources,++ "resources/templates/list": client.list_resource_templates,++ }[method]++ if strict:++ error_type: Final = {++ "internal_error": MCPError,++ "unauthorized": httpx2.HTTPStatusError,++ "deadline": TimeoutError,++ }.get(failure, RuntimeError)++ with pytest.raises(error_type):++ await operation(raise_on_error=True)++ else:++ assert await operation() == []++ assert len(++ tuple(++ payload++ for call in responder.call_args_list++ if isinstance(payload := _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content), JSONRPCRequest)++ and payload.method == method++ )++ ) == (3 if failure == "cycle" else 2)++ assert "private-cursor" not in caplog.text++ if failure == "deadline":++ assert cancelled.is_set()++++[email protected]("method", ("prompts/list", "resources/list", "resources/templates/list"))++async def test_optional_discovery_allows_exhaustion_at_page_cap(method: str, monkeypatch: pytest.MonkeyPatch) -> None:++ monkeypatch.setattr(mcp_client_module, "MCP_TOOL_LISTING_MAX_PAGES", 2, raising=False)++ field: Final = {++ "prompts/list": "prompts",++ "resources/list": "resources",++ "resources/templates/list": "resourceTemplates",++ }[method]++++ def respond(request: httpx2.Request) -> httpx2.Response:++ payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)++ if not isinstance(payload, JSONRPCRequest):++ return httpx2.Response(202)++ if payload.method == "initialize":++ result: Final = {++ "protocolVersion": payload.params["protocolVersion"],++ "capabilities": {"prompts": {}, "resources": {}},++ "serverInfo": {"name": "empty-pages", "version": "1"},++ }++ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": result})++ assert payload.method == method++ return httpx2.Response(++ 200,++ json={++ "jsonrpc": "2.0",++ "id": payload.id,++ "result": {field: [], "nextCursor": None if (payload.params or {}).get("cursor") else "last-page"},++ },++ )++++ responder: Final = Mock(side_effect=respond)++ client: Final = _MockTransportClient(responder, server_url="https://example.com/mcp")++ operation: Final = {++ "prompts/list": client.list_prompts,++ "resources/list": client.list_resources,++ "resources/templates/list": client.list_resource_templates,++ }[method]++ assert await operation(raise_on_error=True) == []++ assert (++ sum(++ isinstance(payload := _JSONRPC_MESSAGE_ADAPTER.validate_json(call.args[0].content), JSONRPCRequest)++ and payload.method == method++ for call in responder.call_args_list++ )++ == 2++ )++++ def test_client_import_before_proxy_credentials_succeeds_in_fresh_process():+ import subprocess++ result = subprocess.run(+ [sys.executable, "-c", "import litellm.experimental_mcp_client.client; from litellm.proxy._experimental.mcp_server.mcp_server_manager import MCPServerManager; print(MCPServerManager.__name__)"],+ capture_output=True, text=True, timeout=60, check=False,+ )+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "MCPServerManager"+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("resolved", (False, True))+ async def test_discovery_auth_fingerprint_tracks_effective_credentials(resolved: bool) -> None:+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import StaticHeaderAuth++ def client(token: str) -> MCPClient:+ return MCPClient(+ server_url="https://example.com/mcp",+ auth_type=MCPAuth.api_key,+ auth_value=None if resolved else token,+ resolved_auth=StaticHeaderAuth(token) if resolved else None,+ )++ original: Final = await client("private-original-credential").discovery_auth_fingerprint()+ repeated: Final = await client("private-original-credential").discovery_auth_fingerprint()+ replaced: Final = await client("private-replaced-credential").discovery_auth_fingerprint()+ assert original == repeated+ assert original != replaced+ assert len(original) == 64+ assert "private-original-credential" not in original+++ @pytest.mark.asyncio+ async def test_request_auth_preview_uses_the_same_effective_headers_as_egress() -> None:+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import StaticHeaderAuth++ client: Final = MCPClient(+ server_url="https://upstream.example/mcp", auth_type=MCPAuth.bearer_token,+ resolved_auth=StaticHeaderAuth("Bearer resolved"), extra_headers={"X-Trace": "trace"},+ )+ request: Final = await client.prepare_request_auth()+ assert request.method == "POST"+ assert str(request.url) == "https://upstream.example/mcp"+ assert request.headers["Authorization"] == "Bearer resolved"+ assert request.headers["X-Trace"] == "trace"+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("rpc_error", [False, True])+ async def test_expired_session_preserves_sdk_error_and_next_operation_reinitializes(rpc_error: bool) -> None:+ from mcp.types import INVALID_REQUEST, METHOD_NOT_FOUND++ requests = []++ def respond(request: httpx2.Request) -> httpx2.Response:+ if request.method != "POST":+ return httpx2.Response(405)+ payload = json.loads(request.content)+ if "id" not in payload:+ return httpx2.Response(202)+ requests.append((payload["method"], request.headers.get("mcp-session-id")))+ if payload["method"] == "initialize":+ return httpx2.Response(200, headers={"mcp-session-id": f"session-{len(requests)}"}, json={+ "jsonrpc": "2.0", "id": payload["id"], "result": {+ "protocolVersion": "2025-06-18", "capabilities": {},+ "serverInfo": {"name": "expiry-test", "version": "1"},+ },+ })+ if len(requests) == 2:+ if rpc_error:+ return httpx2.Response(404, json={+ "jsonrpc": "2.0", "id": payload["id"],+ "error": {"code": METHOD_NOT_FOUND, "message": "Tool catalog unavailable"},+ })+ return httpx2.Response(404)+ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload["id"], "result": {"tools": []}})++ client = MCPClient(server_url="https://example.com/mcp", timeout=3)+ async with client._create_httpx_client_factory(transport=httpx2.MockTransport(respond))() as http_client:+ with pytest.raises(MCPError) as caught:+ await client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()+ )+ assert caught.value.error.code == (METHOD_NOT_FOUND if rpc_error else INVALID_REQUEST)+ assert caught.value.error.message == ("Tool catalog unavailable" if rpc_error else "Session terminated")+ result = await client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()+ )+ assert result.tools == []+ assert requests == [("initialize", None), ("tools/list", "session-1"), ("initialize", None), ("tools/list", "session-3")]+++ @pytest.mark.asyncio+ async def test_404_before_session_initialization_preserves_method_not_found() -> None:+ from mcp.types import METHOD_NOT_FOUND++ client = MCPClient(server_url="https://example.com/mcp", timeout=3)+ transport = httpx2.MockTransport(lambda request: httpx2.Response(404))+ async with client._create_httpx_client_factory(transport=transport)() as http_client:+ with pytest.raises(MCPError) as caught:+ await client._execute_session_operation(+ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()+ )+ assert caught.value.error.code == METHOD_NOT_FOUND+ assert caught.value.error.message == "Not Found"+++ @pytest.mark.parametrize("missing_module", ("mcp", "httpx2", "mcp.types", "openai.types.chat"))+ def test_public_mcp_import_missing_dependency(missing_module: str) -> None:+ with patch.dict(sys.modules):+ for name in tuple(sys.modules):+ if name.startswith(("litellm.experimental_mcp_client", "mcp.", "mcp_types.")) or name == "mcp":+ del sys.modules[name]+ with patch.dict(sys.modules, {missing_module: None}):+ with pytest.raises(ImportError) as caught:+ importlib.import_module("litellm.experimental_mcp_client.client")++ if missing_module in ("mcp", "httpx2"):+ assert "pip install 'litellm[mcp]'" in str(caught.value)+ assert isinstance(caught.value.__cause__, ModuleNotFoundError)+ assert caught.value.__cause__.name == missing_module+ else:+ assert isinstance(caught.value, ModuleNotFoundError)+ assert caught.value.name == missing_module+ assert caught.value.__cause__ is None+ assert "litellm[mcp]" not in str(caught.value)+++ def test_public_mcp_import_preserves_incompatible_sdk_error() -> None:+ with patch.dict(sys.modules):+ for name in tuple(sys.modules):+ if name.startswith("litellm.experimental_mcp_client"):+ del sys.modules[name]+ with patch.dict(sys.modules, {"mcp": ModuleType("mcp")}):+ with pytest.raises(ImportError, match="cannot import name 'ClientSession'") as caught:+ importlib.import_module("litellm.experimental_mcp_client.client")++ assert not isinstance(caught.value, ModuleNotFoundError)+ assert caught.value.__cause__ is None+ assert "litellm[mcp]" not in str(caught.value)diff --cc tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.pyindex 5508259273d,9140ac61f1a..7418cf67e5f--- 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@@@ -11004,5 -11855,2223 +11855,2253 @@@ class TestOpenApiHandlerRelaysUpstreamAwith patch.object(global_mcp_tool_registry, "get_tool", return_value=tool):result = await manager._call_openapi_tool_handler(self._server(), "list_reports", {})- assert result.isError is True+ assert result.is_error is Trueassert "upstream returned HTTP 503" in result.content[0].text+++ class TestConfigServerIdPinning:+ """config.yaml servers may pin ``server_id`` so permission grants survive connection edits."""++ @staticmethod+ def _config(**overrides: object) -> dict[str, dict[str, object]]:+ return {+ "docs_server": {+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ **overrides,+ }+ }++ @pytest.mark.asyncio+ async def test_derived_id_churns_when_connection_fields_change(self, config_only_mcp_manager_factory):+ """The behavior the pin exists to escape: editing the url mints a brand-new id."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(self._config())+ before = next(iter(manager.config_mcp_servers))++ manager.config_mcp_servers.clear()+ await manager.load_servers_from_config(self._config(url="https://prod.example.com/mcp"))+ after = next(iter(manager.config_mcp_servers))++ assert before != after++ @pytest.mark.asyncio+ async def test_pinned_id_survives_url_transport_auth_and_alias_edits(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(self._config(server_id="docs-prod-1"))+ assert list(manager.config_mcp_servers) == ["docs-prod-1"]+ assert manager.config_mcp_servers["docs-prod-1"].server_id == "docs-prod-1"++ manager.config_mcp_servers.clear()+ await manager.load_servers_from_config(+ self._config(+ server_id="docs-prod-1",+ url="https://prod.example.com/mcp",+ transport=MCPTransport.sse,+ auth_type=MCPAuth.bearer_token,+ alias="docs",+ )+ )++ assert list(manager.config_mcp_servers) == ["docs-prod-1"]+ assert manager.config_mcp_servers["docs-prod-1"].url == "https://prod.example.com/mcp"++ @pytest.mark.asyncio+ async def test_absent_server_id_keeps_the_derived_hash(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(self._config())++ derived = manager._generate_stable_server_id(+ server_name="docs_server",+ url="https://example.com/mcp",+ transport=MCPTransport.http,+ auth_type=None,+ alias=None,+ )+ assert list(manager.config_mcp_servers) == [derived]++ @pytest.mark.asyncio+ @pytest.mark.parametrize("bad_value", ["", " ", 123, True, ["docs-prod-1"]])+ async def test_blank_or_non_string_server_id_is_rejected(self, config_only_mcp_manager_factory, bad_value: Any):+ manager = config_only_mcp_manager_factory()++ with pytest.raises(ValueError, match="server_id must be a non-empty string"):+ await manager.load_servers_from_config(self._config(server_id=bad_value))++ @pytest.mark.asyncio+ async def test_two_servers_pinning_the_same_id_are_rejected(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()+ config: Dict[str, Any] = {+ "docs_server": {"url": "https://a.example.com/mcp", "server_id": "shared-id"},+ "wiki_server": {"url": "https://b.example.com/mcp", "server_id": "shared-id"},+ }++ with pytest.raises(ValueError, match="already used by MCP server 'docs_server'"):+ await manager.load_servers_from_config(config)++ @pytest.mark.asyncio+ async def test_pinned_id_colliding_with_a_derived_id_is_rejected(self, config_only_mcp_manager_factory):+ """A pin that lands on another entry's derived hash collides just as hard."""+ manager = config_only_mcp_manager_factory()+ derived = manager._generate_stable_server_id(+ server_name="docs_server",+ url="https://a.example.com/mcp",+ transport=MCPTransport.http,+ auth_type=None,+ alias=None,+ )+ config: Dict[str, Any] = {+ "docs_server": {"url": "https://a.example.com/mcp", "transport": MCPTransport.http},+ "wiki_server": {"url": "https://b.example.com/mcp", "server_id": derived},+ }++ with pytest.raises(ValueError, match="already used by MCP server 'docs_server'"):+ await manager.load_servers_from_config(config)++ @pytest.mark.asyncio+ async def test_pinned_id_colliding_with_a_db_backed_server_is_rejected(self, config_only_mcp_manager_factory):+ """get_registry() is ``config | registry``, so the db row would hide the config server.++ The registry is seeded by hand because on a real startup the config loads before the+ database does, so this check only fires on a later reload. The startup ordering is covered+ by ``test_db_row_arriving_on_a_pinned_config_id_warns``; the warning there is not redundant.+ """+ manager = config_only_mcp_manager_factory()+ manager.registry["db-uuid-1"] = MCPServer(+ server_id="db-uuid-1",+ name="db_server",+ transport=MCPTransport.http,+ url="https://db.example.com/mcp",+ )++ with pytest.raises(ValueError, match="belongs to a database-backed MCP server"):+ await manager.load_servers_from_config(self._config(server_id="db-uuid-1"))++ @pytest.mark.asyncio+ async def test_derived_id_matching_a_db_backed_server_is_not_rejected(self, config_only_mcp_manager_factory):+ """Only a pinned id is an authoring error; a hash collision must not fail startup."""+ manager = config_only_mcp_manager_factory()+ derived = manager._generate_stable_server_id(+ server_name="docs_server",+ url="https://example.com/mcp",+ transport=MCPTransport.http,+ auth_type=None,+ alias=None,+ )+ manager.registry[derived] = MCPServer(+ server_id=derived,+ name="db_server",+ transport=MCPTransport.http,+ url="https://db.example.com/mcp",+ )++ await manager.load_servers_from_config(self._config())++ assert derived in manager.config_mcp_servers++ @pytest.mark.asyncio+ async def test_pinned_id_is_stripped_of_surrounding_whitespace(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(self._config(server_id=" docs-prod-1 "))++ assert list(manager.config_mcp_servers) == ["docs-prod-1"]++ @staticmethod+ async def _reload_with_db_server(manager: MCPServerManager, server_id: str, db_name: str = "db_server") -> None:+ row = LiteLLM_MCPServerTable(+ server_id=server_id,+ server_name=db_name,+ alias=db_name,+ url="https://db.example.com/mcp",+ transport=MCPTransport.http,+ )+ raw_row = MagicMock()+ raw_row.model_dump.return_value = row.model_dump()+ repository = MagicMock()+ repository.table.find_many = AsyncMock(return_value=[raw_row])+ built = MCPServer(+ server_id=server_id,+ name=db_name,+ server_name=db_name,+ url="https://db.example.com/mcp",+ transport=MCPTransport.http,+ )+ with (+ patch( # test-quality-ok: the db reload path has no seam but its own repository+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerRepository",+ return_value=repository,+ ),+ patch( # test-quality-ok: same, the prisma client is fetched inside the reload+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",+ return_value=MagicMock(),+ ),+ patch.object(manager, "build_mcp_server_from_table", new=AsyncMock(return_value=built)),+ ):+ await manager.reload_servers_from_database()++ @pytest.mark.asyncio+ async def test_db_row_arriving_on_a_pinned_config_id_warns(self, config_only_mcp_manager_factory, caplog):+ """The db row loads after config on startup, so the config server is hidden then, not at load."""+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="docs-prod-1"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "docs-prod-1")++ assert any("docs-prod-1" in m and "database entry takes precedence" in m for m in caplog.messages)+ assert manager.get_registry()["docs-prod-1"].url == "https://db.example.com/mcp"++ @pytest.mark.asyncio+ async def test_db_row_with_a_distinct_id_does_not_warn(self, config_only_mcp_manager_factory, caplog):+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="docs-prod-1"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "db-uuid-1")++ assert all("database entry takes precedence" not in m for m in caplog.messages)+ assert set(manager.get_registry()) == {"docs-prod-1", "db-uuid-1"}++ @pytest.mark.asyncio+ async def test_pinned_id_matching_another_entrys_server_name_is_rejected(self, config_only_mcp_manager_factory):+ """expand_permission_list resolves against registry keys first, so this steals the grants."""+ manager = config_only_mcp_manager_factory()++ with pytest.raises(ValueError, match="server_name or alias of MCP server 'wiki_server'"):+ await manager.load_servers_from_config(+ {+ "wiki_server": {"url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ "docs_server": {+ "server_id": "wiki_server",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ }+ )++ @pytest.mark.asyncio+ async def test_pinned_id_matching_another_entrys_alias_is_rejected(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ with pytest.raises(ValueError, match="server_name or alias of MCP server 'wiki_server'"):+ await manager.load_servers_from_config(+ {+ "wiki_server": {+ "alias": "wiki",+ "url": "https://wiki.example.com/mcp",+ "transport": MCPTransport.http,+ },+ "docs_server": {+ "server_id": "wiki",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ }+ )++ @pytest.mark.asyncio+ async def test_pinning_a_servers_own_name_is_allowed(self, config_only_mcp_manager_factory):+ """The most natural pin an operator writes; it resolves to the same server either way."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(self._config(server_id="docs_server"))++ assert list(manager.config_mcp_servers) == ["docs_server"]++ @pytest.mark.asyncio+ async def test_pinning_a_servers_own_alias_is_allowed(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(self._config(alias="docs", server_id="docs"))++ assert list(manager.config_mcp_servers) == ["docs"]++ @pytest.mark.asyncio+ @pytest.mark.parametrize("aliasing_entry_first", [True, False])+ async def test_pinning_own_name_that_is_another_entrys_alias_is_rejected(self, config_only_mcp_manager_factory, aliasing_entry_first: bool):+ """A grant naming 'docs_server' reaches both servers unpinned; the pin would narrow it to one."""+ manager = config_only_mcp_manager_factory()+ wiki = (+ "wiki_server",+ {"alias": "docs_server", "url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ )+ docs = (+ "docs_server",+ {"server_id": "docs_server", "url": "https://example.com/mcp", "transport": MCPTransport.http},+ )++ with pytest.raises(ValueError, match="server_name or alias of MCP server 'wiki_server'"):+ await manager.load_servers_from_config(dict((wiki, docs) if aliasing_entry_first else (docs, wiki)))++ @pytest.mark.asyncio+ async def test_pinning_own_name_that_is_another_entrys_mapped_alias_is_rejected(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ with pytest.raises(ValueError, match="server_name or alias of MCP server 'wiki_server'"):+ await manager.load_servers_from_config(+ {+ "wiki_server": {"url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ "docs_server": {+ "server_id": "docs_server",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ },+ mcp_aliases={"docs_server": "wiki_server"},+ )++ @pytest.mark.asyncio+ async def test_pinning_own_alias_shared_with_a_later_entry_is_rejected(self, config_only_mcp_manager_factory):+ """Nothing rejects duplicate aliases, so the first entry's pin would answer the second's grants."""+ manager = config_only_mcp_manager_factory()++ with pytest.raises(ValueError, match="server_name or alias of MCP server 'docs_server'"):+ await manager.load_servers_from_config(+ {+ "wiki_server": {+ "alias": "shared",+ "server_id": "shared",+ "url": "https://wiki.example.com/mcp",+ "transport": MCPTransport.http,+ },+ "docs_server": {+ "alias": "shared",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ }+ )++ @pytest.mark.asyncio+ async def test_own_name_pin_resolves_grants_like_the_unpinned_name(self, config_only_mcp_manager_factory):+ """The negative control: a sole-owner self-pin must keep loading and answer the same grants."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ {+ "wiki_server": {"alias": "wiki", "url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ "docs_server": {+ "server_id": "docs_server",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ }+ )+ wiki_id = next(sid for sid, server in manager.config_mcp_servers.items() if server.alias == "wiki")++ assert manager.expand_permission_list(["docs_server"]) == ["docs_server"]+ assert manager.expand_permission_list(["wiki"]) == [wiki_id]++ @pytest.mark.asyncio+ async def test_derived_id_is_not_checked_against_names(self, config_only_mcp_manager_factory):+ """Unpinned configs must keep loading; only a pinned id can be an authoring error."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ {+ "wiki_server": {"url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ "docs_server": {"url": "https://example.com/mcp", "transport": MCPTransport.http},+ }+ )++ assert len(manager.config_mcp_servers) == 2++ @pytest.mark.asyncio+ async def test_shadow_warning_is_not_repeated_on_every_reload(self, config_only_mcp_manager_factory, caplog):+ """reload_servers_from_database runs on the config-reload timer; one warning, not one a tick."""+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="docs-prod-1"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "docs-prod-1")+ first_round = [m for m in caplog.messages if "database entry takes precedence" in m]+ await self._reload_with_db_server(manager, "docs-prod-1")+ second_round = [m for m in caplog.messages if "database entry takes precedence" in m]++ assert len(first_round) == 1+ assert second_round == first_round++ @pytest.mark.asyncio+ async def test_shadow_warning_fires_again_when_the_shadowed_set_changes(self, config_only_mcp_manager_factory, caplog):+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="docs-prod-1"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "docs-prod-1")+ await self._reload_with_db_server(manager, "db-uuid-1")+ await self._reload_with_db_server(manager, "docs-prod-1")++ assert len([m for m in caplog.messages if "database entry takes precedence" in m]) == 2++ @pytest.mark.asyncio+ async def test_pinned_id_matching_a_mapped_alias_is_rejected(self, config_only_mcp_manager_factory):+ """An alias can also arrive from litellm_settings.mcp_aliases; it is reserved just the same."""+ manager = config_only_mcp_manager_factory()++ with pytest.raises(ValueError, match="server_name or alias of MCP server 'wiki_server'"):+ await manager.load_servers_from_config(+ {+ "wiki_server": {"url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ "docs_server": {+ "server_id": "wiki",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ },+ {"wiki": "wiki_server"},+ )++ @pytest.mark.asyncio+ async def test_pinning_a_servers_own_mapped_alias_is_allowed(self, config_only_mcp_manager_factory):+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ self._config(server_id="docs"),+ {"docs": "docs_server"},+ )++ assert list(manager.config_mcp_servers) == ["docs"]++ @pytest.mark.asyncio+ async def test_mapped_alias_for_an_unknown_server_reserves_nothing(self, config_only_mcp_manager_factory):+ """A dangling mcp_aliases entry is never applied, so it must not fail an unrelated pin."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ self._config(server_id="wiki"),+ {"wiki": "a_server_that_does_not_exist"},+ )++ assert list(manager.config_mcp_servers) == ["wiki"]++ @pytest.mark.asyncio+ async def test_config_id_that_is_a_db_server_name_warns(self, config_only_mcp_manager_factory, caplog):+ """The mirror of the shadow case: here the config entry captures the db server's grants."""+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="db_server"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "db-uuid-1")++ assert any("db_server" in m and "name or alias of a database-backed" in m for m in caplog.messages)++ @pytest.mark.asyncio+ async def test_capture_warning_is_not_repeated_on_every_reload(self, config_only_mcp_manager_factory, caplog):+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="db_server"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "db-uuid-1")+ await self._reload_with_db_server(manager, "db-uuid-1")++ assert len([m for m in caplog.messages if "name or alias of a database-backed" in m]) == 1++ @pytest.mark.asyncio+ async def test_config_id_unrelated_to_db_names_does_not_warn(self, config_only_mcp_manager_factory, caplog):+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="docs-prod-1"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "db-uuid-1")++ assert all("name or alias of a database-backed" not in m for m in caplog.messages)++ @pytest.mark.asyncio+ async def test_mapped_alias_for_a_server_with_its_own_alias_reserves_nothing(self, config_only_mcp_manager_factory):+ """load_servers_from_config ignores the mapping when the entry sets alias, so it is free."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ {+ "wiki_server": {+ "alias": "wiki_prod",+ "url": "https://wiki.example.com/mcp",+ "transport": MCPTransport.http,+ },+ "docs_server": {+ "server_id": "wiki",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ },+ {"wiki": "wiki_server"},+ )++ assert "wiki" in manager.config_mcp_servers+ assert len(manager.config_mcp_servers) == 2++ @pytest.mark.asyncio+ async def test_only_the_first_mapped_alias_for_a_server_is_reserved(self, config_only_mcp_manager_factory):+ """Only the first mapping is applied, so pinning the second one must still load."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ {+ "wiki_server": {"url": "https://wiki.example.com/mcp", "transport": MCPTransport.http},+ "docs_server": {+ "server_id": "wiki_two",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ },+ {"wiki_one": "wiki_server", "wiki_two": "wiki_server"},+ )++ assert "wiki_two" in manager.config_mcp_servers++ @pytest.mark.asyncio+ async def test_invalid_name_is_reported_before_any_entry_body_is_read(self, config_only_mcp_manager_factory):+ """The identifier index walks every entry up front, so a bad name must still fail on the name."""+ with pytest.raises(Exception, match="Server name cannot contain"):+ await config_only_mcp_manager_factory().load_servers_from_config({"my-server": None})++ @pytest.mark.asyncio+ async def test_a_shadowing_db_server_reports_only_the_shadow_warning(self, config_only_mcp_manager_factory, caplog):+ """The db row wins the id outright, so the capture message would contradict the shadow one."""+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(self._config(server_id="db_server"))++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "db_server")++ assert any("database entry takes precedence" in m for m in caplog.messages)+ assert all("name or alias of a database-backed" not in m for m in caplog.messages)+ assert manager.get_registry()["db_server"].url == "https://db.example.com/mcp"++ @pytest.mark.asyncio+ async def test_an_explicitly_blank_alias_still_blocks_the_mapping(self, config_only_mcp_manager_factory):+ """The loader only consults mcp_aliases when the key is absent, so a blank alias frees it."""+ manager = config_only_mcp_manager_factory()++ await manager.load_servers_from_config(+ {+ "wiki_server": {+ "alias": "",+ "url": "https://wiki.example.com/mcp",+ "transport": MCPTransport.http,+ },+ "docs_server": {+ "server_id": "wiki",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ },+ {"wiki": "wiki_server"},+ )++ assert "wiki" in manager.config_mcp_servers+ assert manager.config_mcp_servers["wiki"].url == "https://example.com/mcp"++ @pytest.mark.asyncio+ async def test_a_row_that_shadows_one_id_still_reports_capturing_another(self, config_only_mcp_manager_factory, caplog):+ """Skipping is per identifier, not per row, so the second collision is not lost."""+ manager = config_only_mcp_manager_factory()+ await manager.load_servers_from_config(+ {+ "docs_server": {+ "server_id": "shadow_x",+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ },+ "wiki_server": {+ "server_id": "capture_y",+ "url": "https://wiki.example.com/mcp",+ "transport": MCPTransport.http,+ },+ }+ )++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ await self._reload_with_db_server(manager, "shadow_x", db_name="capture_y")++ assert any("shadow_x" in m and "database entry takes precedence" in m for m in caplog.messages)+ assert any("capture_y" in m and "name or alias of a database-backed" in m for m in caplog.messages)+++ class TestLitellmAdmissionKeyIsNeverTheSubjectToken:+ """The bearer that admitted the request as a LiteLLM key must not be sent to the IdP as the+ RFC 8693 subject_token (or ID-JAG assertion). Only ``x-litellm-api-key`` disambiguates: with it+ present, ``Authorization`` is the caller's own identity token and is exchanged as before."""++ _ADMISSION_KEY: Final = "sk-litellm-virtual-key"+ _USER_TOKEN: Final = "user-idp-jwt"++ @staticmethod+ def _token_exchange_server(server_id: str) -> MCPServer:+ return MCPServer(+ server_id=server_id,+ name=f"{server_id}-server",+ url="https://up.example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2_token_exchange,+ token_exchange_endpoint="https://idp.example.com/token",+ client_id="cid",+ client_secret="csec",+ )++ @staticmethod+ def _id_jag_server(server_id: str) -> MCPServer:+ return MCPServer(+ server_id=server_id,+ name=f"{server_id}-server",+ url="https://up.example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2_id_jag,+ client_id="cid",+ client_secret="csec",+ token_exchange_endpoint="https://idp.example.com/token",+ id_jag_resource_token_endpoint="https://resource-as.example.com/token",+ )++ @staticmethod+ def _recording_provider() -> MagicMock:+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import StaticHeaderAuth+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok++ provider: Final = MagicMock()+ provider.resolve_credentials = AsyncMock(+ return_value=Ok(StaticHeaderAuth("Bearer MINTED", header_name="Authorization"))+ )+ return provider++ @staticmethod+ def _subjects_seen_by(provider: MagicMock) -> list[str | None]:+ return [+ call.args[0].inbound_token.get_secret_value() if call.args[0].inbound_token else None+ for call in provider.resolve_credentials.call_args_list+ ]++ @staticmethod+ def _manager_with_recording_client() -> MCPServerManager:+ manager: Final = MCPServerManager()+ client: Final = AsyncMock()+ client.call_tool = AsyncMock(return_value=CallToolResult(content=[], isError=False))+ client.list_prompts = AsyncMock(return_value=[])+ client.read_resource = AsyncMock(return_value=ReadResourceResult(contents=[]))+ manager._create_mcp_client = AsyncMock(return_value=client)+ return manager++ @staticmethod+ def _subject_token_given_to_client(manager: MCPServerManager) -> str | None:+ return manager._create_mcp_client.call_args.kwargs["subject_token"]++ async def _call_tool_subject(self, server: MCPServer, oauth2_headers, raw_headers, user_api_key_auth):+ manager: Final = self._manager_with_recording_client()+ await manager._call_regular_mcp_tool(+ mcp_server=server,+ original_tool_name="tool",+ arguments={},+ tasks=[],+ mcp_auth_header=None,+ mcp_server_auth_headers=None,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ proxy_logging_obj=None,+ user_api_key_auth=user_api_key_auth,+ )+ return self._subject_token_given_to_client(manager)++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type", [MCPAuth.oauth2_token_exchange, MCPAuth.oauth2_id_jag])+ async def test_tools_call_with_only_the_litellm_key_has_no_subject(self, auth_type):+ server = (+ self._token_exchange_server("te-call")+ if auth_type == MCPAuth.oauth2_token_exchange+ else self._id_jag_server("jag-call")+ )+ subject_token = await self._call_tool_subject(+ server,+ oauth2_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ raw_headers={"authorization": f"Bearer {self._ADMISSION_KEY}"},+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert subject_token is None++ @pytest.mark.asyncio+ async def test_rest_tools_call_with_only_the_litellm_key_has_no_subject(self):+ """The REST facade passes no oauth2_headers; the bearer is reached through raw_headers only."""+ subject_token = await self._call_tool_subject(+ self._token_exchange_server("te-rest"),+ oauth2_headers=None,+ raw_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert subject_token is None++ @pytest.mark.asyncio+ async def test_tools_call_exchanges_the_user_token_when_x_litellm_api_key_admits(self):+ subject_token = await self._call_tool_subject(+ self._token_exchange_server("te-split"),+ oauth2_headers={"Authorization": f"Bearer {self._USER_TOKEN}"},+ raw_headers={+ "X-LiteLLM-API-Key": f"Bearer {self._ADMISSION_KEY}",+ "authorization": f"Bearer {self._USER_TOKEN}",+ },+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert subject_token == self._USER_TOKEN++ @pytest.mark.asyncio+ async def test_tools_call_with_an_empty_x_litellm_api_key_has_no_subject(self):+ """Admission ignores an empty ``x-litellm-api-key`` and validates ``Authorization`` instead."""+ subject_token = await self._call_tool_subject(+ self._token_exchange_server("te-empty-header"),+ oauth2_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ raw_headers={"x-litellm-api-key": "", "authorization": f"Bearer {self._ADMISSION_KEY}"},+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert subject_token is None++ @pytest.mark.asyncio+ async def test_tools_call_with_the_same_litellm_key_in_both_headers_has_no_subject(self):+ subject_token = await self._call_tool_subject(+ self._token_exchange_server("te-same-key"),+ oauth2_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ raw_headers={+ "x-litellm-api-key": self._ADMISSION_KEY,+ "authorization": f"Bearer {self._ADMISSION_KEY}",+ },+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert subject_token is None++ @pytest.mark.asyncio+ async def test_tools_call_with_a_different_litellm_key_in_authorization_has_no_subject(self):+ """A second ``sk-`` virtual key next to ``x-litellm-api-key`` is still a gateway credential."""+ subject_token = await self._call_tool_subject(+ self._token_exchange_server("te-second-key"),+ oauth2_headers={"Authorization": "Bearer sk-another-virtual-key"},+ raw_headers={+ "x-litellm-api-key": f"Bearer {self._ADMISSION_KEY}",+ "authorization": "Bearer sk-another-virtual-key",+ },+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert subject_token is None++ @pytest.mark.asyncio+ async def test_tools_call_exchanges_the_bearer_when_jwt_admission_left_api_key_unset(self):+ subject_token = await self._call_tool_subject(+ self._token_exchange_server("te-jwt"),+ oauth2_headers={"Authorization": f"Bearer {self._USER_TOKEN}"},+ raw_headers={"authorization": f"Bearer {self._USER_TOKEN}"},+ user_api_key_auth=UserAPIKeyAuth(api_key=None, user_id="alice"),+ )+ assert subject_token == self._USER_TOKEN++ @pytest.mark.asyncio+ async def test_tools_list_with_only_the_litellm_key_has_no_subject(self):+ manager: Final = self._manager_with_recording_client()+ manager._fetch_tools_with_timeout = AsyncMock(return_value=[])+ await manager._get_tools_from_server(+ server=self._token_exchange_server("te-list-key"),+ oauth2_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ raw_headers={"authorization": f"Bearer {self._ADMISSION_KEY}"},+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ )+ assert self._subject_token_given_to_client(manager) is None++ @pytest.mark.asyncio+ async def test_prompts_list_with_only_the_litellm_key_has_no_subject(self):+ manager: Final = self._manager_with_recording_client()+ await manager.get_prompts_from_server(+ server=self._token_exchange_server("te-prompts-key"),+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ raw_headers={"authorization": f"Bearer {self._ADMISSION_KEY}"},+ )+ assert self._subject_token_given_to_client(manager) is None++ @pytest.mark.asyncio+ async def test_resource_read_with_only_the_litellm_key_has_no_subject(self):+ manager: Final = self._manager_with_recording_client()+ await manager.read_resource_from_server(+ server=self._token_exchange_server("te-read-key"),+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ url=AnyUrl("file:///notes.txt"),+ raw_headers={"authorization": f"Bearer {self._ADMISSION_KEY}"},+ )+ assert self._subject_token_given_to_client(manager) is None++ @pytest.mark.asyncio+ async def test_resource_read_exchanges_the_user_token_when_x_litellm_api_key_admits(self):+ manager: Final = self._manager_with_recording_client()+ await manager.read_resource_from_server(+ server=self._token_exchange_server("te-read-split"),+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ url=AnyUrl("file:///notes.txt"),+ raw_headers={+ "x-litellm-api-key": f"Bearer {self._ADMISSION_KEY}",+ "authorization": f"Bearer {self._USER_TOKEN}",+ },+ )+ assert self._subject_token_given_to_client(manager) == self._USER_TOKEN++ @pytest.mark.asyncio+ async def test_openapi_call_never_hands_the_litellm_key_to_the_exchanger(self):+ provider: Final = self._recording_provider()+ manager = MCPServerManager(cred_provider=provider)+ server = MCPServer(+ server_id="te-openapi",+ name="te_openapi",+ server_name="te_openapi",+ url=None,+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2_token_exchange,+ token_exchange_endpoint="https://idp.example.com/token",+ client_id="cid",+ client_secret="csec",+ spec_path="https://api.example.com/openapi.json",+ )+ user_auth = UserAPIKeyAuth(api_key="hashed-key", user_id="alice")++ await manager.resolve_openapi_upstream_auth(+ mcp_server=server,+ oauth2_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ raw_headers={"authorization": f"Bearer {self._ADMISSION_KEY}"},+ mcp_auth_header=None,+ user_api_key_auth=user_auth,+ forwarded_headers=None,+ )+ await manager.resolve_openapi_upstream_auth(+ mcp_server=server,+ oauth2_headers={"Authorization": f"Bearer {self._USER_TOKEN}"},+ raw_headers={+ "x-litellm-api-key": f"Bearer {self._ADMISSION_KEY}",+ "authorization": f"Bearer {self._USER_TOKEN}",+ },+ mcp_auth_header=None,+ user_api_key_auth=user_auth,+ forwarded_headers=None,+ )+ assert self._subjects_seen_by(provider) == [None, self._USER_TOKEN]++ @pytest.mark.asyncio+ async def test_preflight_challenges_instead_of_exchanging_the_litellm_key(self):+ provider: Final = self._recording_provider()+ manager = MCPServerManager(cred_provider=provider)++ with pytest.raises(HTTPException) as exc_info:+ await manager.preflight_token_exchange(+ server=self._token_exchange_server("te-preflight-key"),+ oauth2_headers={"Authorization": f"Bearer {self._ADMISSION_KEY}"},+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ raw_headers={"authorization": f"Bearer {self._ADMISSION_KEY}"},+ )+ assert exc_info.value.status_code == 401+ headers = exc_info.value.headers or {}+ assert "resource_metadata" in (headers.get("WWW-Authenticate") or headers.get("www-authenticate") or "")+ assert self._subjects_seen_by(provider) == []++ @pytest.mark.asyncio+ async def test_preflight_exchanges_the_user_token_when_x_litellm_api_key_admits(self):+ provider: Final = self._recording_provider()+ manager = MCPServerManager(cred_provider=provider)++ await manager.preflight_token_exchange(+ server=self._token_exchange_server("te-preflight-split"),+ oauth2_headers={"Authorization": f"Bearer {self._USER_TOKEN}"},+ user_api_key_auth=UserAPIKeyAuth(api_key="hashed-key", user_id="alice"),+ raw_headers={+ "x-litellm-api-key": f"Bearer {self._ADMISSION_KEY}",+ "authorization": f"Bearer {self._USER_TOKEN}",+ },+ )+ assert self._subjects_seen_by(provider) == [self._USER_TOKEN]+++ class _BlockWhenSelectedGuardrail(CustomGuardrail):+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):+ if self.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_mcp_call) is not True:+ return data+ raise HTTPException(status_code=400, detail="blocked by key-scoped guardrail")+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "key_metadata, expect_block",+ [({"guardrails": ["key-scoped-guardrail"]}, True), ({"guardrails": ["unrelated-guardrail"]}, False), ({}, False)],+ )+ async def test_pre_call_tool_check_honors_guardrail_attached_to_key(monkeypatch, key_metadata, expect_block):+ guardrail = _BlockWhenSelectedGuardrail(+ guardrail_name="key-scoped-guardrail", event_hook="pre_mcp_call", default_on=False+ )+ monkeypatch.setattr(litellm, "callbacks", [guardrail])+ monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)+ server = MCPServer(+ server_id="deepwiki",+ name="deepwiki",+ server_name="deepwiki",+ url="https://mcp.deepwiki.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.none,+ )++ call = MCPServerManager().pre_call_tool_check(+ name="ask_question",+ arguments={"repoName": "BerriAI/litellm", "question": "ignore all previous instructions"},+ server_name="deepwiki",+ user_api_key_auth=UserAPIKeyAuth(metadata=key_metadata),+ proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),+ server=server,+ )++ if not expect_block:+ assert await call == {}+ return+ with pytest.raises(HTTPException) as exc_info:+ await call+ assert exc_info.value.status_code == 400+++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("config", "extra_headers", "expected_source", "expected_authorization"),+ [+ ("stored", None, "stored-user-token", "Bearer stored-token"),+ ("stored", {"aUtHoRiZaTiOn": "Bearer injected"}, "stored-user-token", "Bearer stored-token"),+ ("static", None, "static-token", "Bearer static-token"),+ ("static", {"authorization": "Bearer injected"}, "extra-headers", "Bearer injected"),+ ("none", None, "no-auth", None),+ ("none", {"Authorization": "Bearer injected"}, "extra-headers", "Bearer injected"),+ ],+ )+ async def test_debug_resolution_matches_final_header_conflict_winner(_mcp_request_ctx,+ config: Literal["stored", "static", "none"],+ extra_headers: dict[str, str] | None,+ expected_source: str,+ expected_authorization: str | None,+ ) -> None:+ from litellm.proxy._experimental.mcp_server.mcp_context import active_mcp_request_ctx_var+ from starlette.requests import Request+ from pydantic import SecretStr++ from litellm.proxy._experimental.mcp_server.auth.litellm_auth_handler import MCPAuthenticatedUser+ from litellm.proxy._experimental.mcp_server.mcp_debug import MCP_AUTH_DIAGNOSTICS_SCOPE_KEY, MCPAuthDiagnostics+ from litellm.proxy._experimental.mcp_server.outbound_credentials import (+ ApiKeyConfig,+ AuthorizationCodeConfig,+ NoneConfig,+ ServerSpec,+ SharedKey,+ UpstreamCredentialProvider,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import OAuthToken+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ class Store:+ def __init__(self) -> None:+ self.calls = 0++ async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None:+ self.calls += 1+ return OAuthToken(access_token="stored-token") if user_id == "alice" else None++ store = Store()+ context = MCPAuthenticatedUser(UserAPIKeyAuth(user_id="alice"))+ diagnostics = MCPAuthDiagnostics()+ token = active_mcp_request_ctx_var.set(+ _mcp_request_ctx(+ request=Request({"type": "http", MCP_AUTH_DIAGNOSTICS_SCOPE_KEY: diagnostics}),+ )+ )+ selected = {+ "stored": AuthorizationCodeConfig(),+ "static": ApiKeyConfig(key_source=SharedKey(value=SecretStr("static-token"))),+ "none": NoneConfig(),+ }[config]+ try:+ auth, remaining = await MCPServerManager()._resolve_v2_auth(+ server=MCPServer(+ server_id="s",+ name="s",+ transport="http",+ url="https://up.example/mcp",+ static_headers={"Authorization": "Bearer configured"},+ ),+ spec=ServerSpec(server_id="s", resource="https://up.example/mcp", config=selected),+ provider=UpstreamCredentialProvider(oauth_token_store=store),+ subject_token=None,+ user_api_key_auth=context.user_api_key_auth,+ extra_headers=extra_headers,+ )+ request = httpx.Request("GET", "https://up.example/mcp", headers=remaining)+ if auth is not None:+ next(auth.auth_flow(request))+ assert diagnostics.resolution() == expected_source+ assert request.headers.get("Authorization") == expected_authorization+ assert store.calls == (1 if config == "stored" else 0)+ finally:+ active_mcp_request_ctx_var.reset(token)+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("transport", ["http", "stdio"])+ async def test_debug_reports_legacy_signing_and_non_http_transport(_mcp_request_ctx, transport: Literal["http", "stdio"]) -> None:+ from litellm.proxy._experimental.mcp_server.mcp_context import active_mcp_request_ctx_var+ from starlette.requests import Request++ from litellm.proxy._experimental.mcp_server.mcp_debug import MCP_AUTH_DIAGNOSTICS_SCOPE_KEY, MCPAuthDiagnostics+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ diagnostics = MCPAuthDiagnostics()+ token = active_mcp_request_ctx_var.set(+ _mcp_request_ctx(+ request=Request({"type": "http", MCP_AUTH_DIAGNOSTICS_SCOPE_KEY: diagnostics}),+ )+ )+ try:+ server = MCPServer(+ server_id="signed",+ name="signed",+ transport=transport,+ url="https://up.example/mcp",+ auth_type="aws_sigv4",+ aws_access_key_id="AKIDEXAMPLE",+ aws_secret_access_key="test-signing-secret",+ aws_region_name="us-east-1",+ aws_service_name="execute-api",+ command="python",+ args=["-c", "pass"],+ )+ client = await MCPServerManager()._create_mcp_client(server)+ if transport == "stdio":+ assert diagnostics.resolution() == "not-applicable"+ else:+ assert diagnostics.resolution() == "aws-sigv4"+ request = httpx.Request("POST", "https://up.example/mcp", content=b"{}")+ next(client._aws_auth.auth_flow(request))+ assert request.headers["Authorization"].startswith("AWS4-HMAC-SHA256 ")+ assert "Credential=AKIDEXAMPLE/" in request.headers["Authorization"]+ finally:+ active_mcp_request_ctx_var.reset(token)+++ @pytest.mark.asyncio+ async def test_temporary_server_discovery_reuses_resolved_metadata_without_publishing() -> None:+ manager: Final = MCPServerManager()+ server: Final = MCPServer(+ server_id="temporary-oauth-discovery", name="temporary", url="https://idp.example.com/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.true_passthrough,+ )+ manager._set_oauth_discovery_deferred(server.server_id, True)+ metadata: Final = MCPOAuthMetadata(+ authorization_url="https://idp.example.com/authorize", token_url="https://idp.example.com/token",+ registration_url="https://idp.example.com/register",+ )+ with patch.object(manager, "_discover_oauth_metadata_for_server", AsyncMock(return_value=metadata)) as discovery:+ resolved: Final = await manager.ensure_oauth_metadata_discovered(server)+ repeated: Final = await manager.ensure_oauth_metadata_discovered(server)+ assert resolved.authorization_url == metadata.authorization_url+ assert resolved.token_url == metadata.token_url+ assert resolved.registration_url == metadata.registration_url+ assert repeated is resolved+ assert server.server_id not in manager.registry+ assert server.server_id not in manager.config_mcp_servers+ discovery.assert_awaited_once()+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type", [MCPAuth.oauth2, MCPAuth.true_passthrough])+ async def test_repeated_stale_oauth_discovery_is_bounded(auth_type: MCPAuth) -> None:+ manager: Final = MCPServerManager()+ server: Final = MCPServer(+ server_id="repeated-stale", name="stale", url="https://idp.example.com/mcp",+ transport=MCPTransport.http, auth_type=auth_type, oauth2_flow="authorization_code",+ )+ manager.registry[server.server_id] = server+ manager._set_oauth_discovery_deferred(server.server_id, True)+ metadata: Final = MCPOAuthMetadata(+ authorization_url="https://idp.example.com/authorize", token_url="https://idp.example.com/token",+ )+ with (+ patch.object(manager, "_discover_oauth_metadata_for_server", AsyncMock(return_value=metadata)) as discovery,+ patch.object(manager, "_publish_resolved_oauth_server", return_value=None),+ ):+ if auth_type == MCPAuth.true_passthrough:+ assert await manager.ensure_oauth_metadata_discovered(server) is server+ else:+ with pytest.raises(HTTPException) as exc:+ await manager.ensure_oauth_metadata_discovered(server)+ assert exc.value.status_code == 503+ assert "changed repeatedly" in str(exc.value.detail)+ assert discovery.await_count == 2+++ @pytest.mark.asyncio+ async def test_stale_discovery_falls_back_to_resolved_registered_server() -> None:+ manager: Final = MCPServerManager()+ original: Final = MCPServer(+ server_id="resolved-replacement", name="replacement", url="https://old.example.com/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.oauth2, oauth2_flow="authorization_code",+ )+ replacement: Final = original.model_copy(update={+ "url": "https://new.example.com/mcp", "authorization_url": "https://new.example.com/authorize",+ "token_url": "https://new.example.com/token",+ })+ manager.registry[original.server_id] = replacement+ assert await manager._rejoin_oauth_metadata_discovery(original, retry_stale=False) is replacement+++ def test_stale_discovery_cannot_overwrite_new_registered_server() -> None:+ manager: Final = MCPServerManager()+ original: Final = MCPServer(+ server_id="stale-publication", name="publication", url="https://old.example.com/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.oauth2,+ )+ manager._set_oauth_discovery_deferred(original.server_id, True)+ original_slot: Final = manager._oauth_discovery_slot(original.server_id)+ assert original_slot is not None+ replacement: Final = original.model_copy(update={"url": "https://new.example.com/mcp"})+ manager.registry[original.server_id] = replacement+ manager._set_oauth_discovery_deferred(original.server_id, True)+ assert manager._publish_resolved_oauth_server(original, original_slot.generation) is None+ assert manager.registry[original.server_id] is replacement+++ @pytest.mark.asyncio+ async def test_temporary_oauth_discovery_expires_without_more_requests() -> None:+ manager: Final = MCPServerManager()+ server: Final = MCPServer(+ server_id="expiring-session", name="temporary", url="https://idp.example.com/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.true_passthrough,+ authorization_url="https://idp.example.com/authorize", token_url="https://idp.example.com/token",+ )+ manager._set_oauth_discovery_deferred(server.server_id, True)+ resolved: Final = await manager.ensure_oauth_metadata_discovered(server)+ assert manager._oauth_discovery_slot(server.server_id) is not None+ loop: Final = asyncio.get_running_loop()+ expired: Final = loop.create_future()+ with patch.object(loop, "time", return_value=loop.time() + 301):+ loop.call_later(0, expired.set_result, None)+ await expired+ assert resolved.authorization_url == server.authorization_url+ assert manager._oauth_discovery_slot(server.server_id) is None+++ def test_old_temporary_discovery_expiry_preserves_replacement() -> None:+ manager: Final = MCPServerManager()+ manager._set_oauth_discovery_deferred("reused-session", True)+ old_slot: Final = manager._oauth_discovery_slot("reused-session")+ assert old_slot is not None+ manager._set_oauth_discovery_deferred("reused-session", True)+ replacement: Final = manager._oauth_discovery_slot("reused-session")+ manager._expire_temporary_oauth_discovery("reused-session", old_slot.generation)+ assert manager._oauth_discovery_slot("reused-session") is replacement+ assert replacement is not None+ manager._expire_temporary_oauth_discovery("reused-session", replacement.generation)+ assert manager._oauth_discovery_slot("reused-session") is None+ manager._expire_temporary_oauth_discovery("reused-session", replacement.generation)+ assert manager._oauth_discovery_slot("reused-session") is None+++ @pytest.mark.asyncio+ async def test_openapi_health_coalesces_concurrent_checks_and_reuses_results(respx_mock, monkeypatch):+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ manager = MCPServerManager()+ server = MCPServer(+ server_id="coalesced",+ name="coalesced",+ transport=MCPTransport.http,+ spec_path="https://93.184.216.34/coalesced.json",+ auth_type=MCPAuth.none,+ )+ manager.registry = {server.server_id: server}+ started = asyncio.Event()+ release = asyncio.Event()++ async def serve(request):+ started.set()+ await release.wait()+ return httpx.Response(200, json={"paths": {}})++ route = respx_mock.get(server.spec_path).mock(side_effect=serve)+ tasks = [asyncio.create_task(manager.health_check_server(server.server_id)) for _ in range(4)]+ await asyncio.wait_for(started.wait(), timeout=1)+ release.set()+ results = await asyncio.gather(*tasks)+ cached = await manager.health_check_server(server.server_id)+ assert [result.status for result in results] == ["healthy"] * 4+ assert cached.status == "healthy"+ assert {result.last_health_check for result in [*results, cached]} == {results[0].last_health_check}+ assert route.call_count == 1+++ @pytest.mark.asyncio+ async def test_openapi_health_cache_expires_at_thirty_seconds(respx_mock, monkeypatch):+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _OpenAPIHealthProbe++ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ clock = iter([0.0, 29.0, 30.0, 30.0])+ probe = _OpenAPIHealthProbe("https://93.184.216.34/expiry.json", clock=clock.__next__)+ route = respx_mock.get(probe.spec_path).mock(+ side_effect=[+ httpx.Response(200, json={"paths": {}}),+ httpx.Response(503),+ ]+ )+ first = await probe.check()+ assert first[0] == "healthy"+ assert await probe.check() == first+ refreshed = await probe.check()+ assert refreshed[0] == "unhealthy"+ assert refreshed[1] == "OpenAPI specification request failed (HTTP 503)"+ assert refreshed[2] >= first[2]+ assert route.call_count == 2+++ @pytest.mark.asyncio+ async def test_openapi_health_reports_size_limit_as_unknown_and_caches_failure(respx_mock, monkeypatch):+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ manager = MCPServerManager()+ server = MCPServer(+ server_id="oversized",+ name="oversized",+ transport=MCPTransport.http,+ spec_path="https://93.184.216.34/large.json",+ auth_type=MCPAuth.none,+ )+ manager.registry = {server.server_id: server}+ route = respx_mock.get(server.spec_path).respond(200, headers={"content-length": str(12 * 1024 * 1024)})+ result = await manager.health_check_server(server.server_id)+ cached = await manager.health_check_server(server.server_id)+ assert result.status == "unknown"+ assert result.health_check_error == "OpenAPI specification probe refused: Response exceeds the configured size limit"+ assert cached.health_check_error == result.health_check_error+ assert cached.last_health_check == result.last_health_check+ assert route.call_count == 1+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("already_waiting", [False, True])+ async def test_openapi_health_cancellation_does_not_poison_cache(respx_mock, monkeypatch, already_waiting):+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ manager = MCPServerManager()+ server = MCPServer(+ server_id="cancelled-cache", name="cancelled-cache", transport=MCPTransport.http,+ spec_path="https://93.184.216.34/cancelled-cache.json", auth_type=MCPAuth.none,+ )+ manager.registry = {server.server_id: server}+ started = asyncio.Event()+ attempts = []++ async def serve(request):+ attempts.append(request.url)+ if not started.is_set():+ started.set()+ await asyncio.Event().wait()+ return httpx.Response(200, json={"paths": {}})++ route = respx_mock.get(server.spec_path).mock(side_effect=serve)+ leader = asyncio.create_task(manager.health_check_server(server.server_id))+ await asyncio.wait_for(started.wait(), timeout=1)+ follower = asyncio.create_task(manager.health_check_server(server.server_id)) if already_waiting else None+ await asyncio.sleep(0)+ leader.cancel()+ cancelled = await leader+ assert cancelled.status == "unknown"+ assert cancelled.health_check_error == "OpenAPI specification check was cancelled"+ recovered = await follower if follower is not None else await manager.health_check_server(server.server_id)+ assert recovered.status == "healthy"+ assert recovered.health_check_error is None+ cached = await manager.health_check_server(server.server_id)+ assert cached.last_health_check == recovered.last_health_check+ assert cached.status == "healthy"+ assert len(attempts) == 2+ assert route.call_count == 1+++ class _DiscoveryClock:+ def __init__(self) -> None:+ self.now = 0.0++ def __call__(self) -> float:+ return self.now+++ from pydantic import TypeAdapter+ from mcp.types import JSONRPCMessage++ _JSONRPC_ADAPTER = TypeAdapter(JSONRPCMessage)+++ @contextlib.contextmanager+ def _mcp_upstream(respond):+ """Drive the SDK's streamable-HTTP transport off an httpx2 MockTransport; respx only sees httpx."""+ from litellm.experimental_mcp_client.client import MCPClient++ def make_client(self, *args, **kwargs):+ return httpx2.AsyncClient(+ transport=httpx2.MockTransport(respond),+ headers=kwargs.get("headers"),+ auth=kwargs.get("auth") or self._resolved_auth or self._aws_auth,+ )++ with (+ patch.object( # test-quality-ok: respx cannot intercept httpx2; inject MockTransport through the client factory+ MCPClient, "_create_httpx_client_factory", lambda self: functools.partial(make_client, self)+ )+ ):+ yield+++ class _DiscoveryUpstream:+ def __init__(self) -> None:+ self.requests: tuple[tuple[str, str], ...] = ()+ self.outcome = "supported"+ self.entered = asyncio.Event()+ self.release = asyncio.Event()+ self.release.set()++ async def respond(self, request: httpx2.Request) -> httpx2.Response:+ from mcp.types import JSONRPCRequest++ if request.method == "DELETE":+ return httpx2.Response(200)+ payload: Final = _JSONRPC_ADAPTER.validate_json(request.content)+ if not isinstance(payload, JSONRPCRequest):+ return httpx2.Response(202)+ self.requests = (*self.requests, (payload.method, request.headers.get("authorization", "")))+ if payload.method == "initialize":+ return httpx2.Response(+ 200,+ json={+ "jsonrpc": "2.0",+ "id": payload.id,+ "result": {+ "protocolVersion": "2025-03-26",+ "serverInfo": {"name": "discovery", "version": "1"},+ "capabilities": {} if self.outcome == "unsupported" else {"prompts": {}, "resources": {}},+ },+ },+ )+ self.entered.set()+ await self.release.wait()+ if self.outcome == "failure":+ return httpx2.Response(503)++ if self.outcome == "paged_failure" and (payload.params or {}).get("cursor"):++ return httpx2.Response(503)+ if self.outcome == "cancelled":+ raise asyncio.CancelledError()+ if self.outcome == "rejected":+ return httpx2.Response(+ 200, json={"jsonrpc": "2.0", "id": payload.id, "error": {"code": -32601, "message": "Unsupported"}}+ )+ result: Final = {+ "prompts/list": {"prompts": [{"name": "example", "description": "original"}]},+ "resources/list": {"resources": [{"name": "example", "uri": "test://example", "description": "original"}]},+ "resources/templates/list": {+ "resourceTemplates": [{"name": "example", "uriTemplate": "test://{name}", "description": "original"}]+ },+ "tools/list": {"tools": []},+ }[payload.method]- return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": result})++ continuation: Final = (++ {"nextCursor": "last-page"}++ if self.outcome in ("paged", "paged_failure") and not (payload.params or {}).get("cursor")++ else {}++ )++ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": {**result, **continuation}})++ @property+ def initializes(self) -> int:+ return sum(method == "initialize" for method, _auth in self.requests)+++ def _discovery_server() -> MCPServer:+ return MCPServer(server_id="discovery", name="discovery", url="https://discovery.example/mcp", transport=MCPTransport.http)+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("kind", ("prompts", "resources", "templates"))+ async def test_discovery_cache_reuses_raw_results_and_expires(kind: str) -> None:+ import respx++ clock: Final = _DiscoveryClock()+ manager: Final = MCPServerManager(discovery_clock=clock)+ upstream: Final = _DiscoveryUpstream()+ operation: Final = {+ "prompts": manager.get_prompts_from_server,+ "resources": manager.get_resources_from_server,+ "templates": manager.get_resource_templates_from_server,+ }[kind]+ server: Final = _discovery_server()+ with _mcp_upstream(upstream.respond):+ first: Final = await operation(server, None)+ assert len(first) == 1+ assert first[0].name == "discovery-example"+ first[0].description = "caller changed it"+ second: Final = await operation(server, None, add_prefix=False)+ assert second[0].name == "example"+ assert second[0].description == "original"+ assert upstream.initializes == 1+ clock.now = 59.999+ assert (await operation(server, None))[0].name == "discovery-example"+ assert upstream.initializes == 1+ clock.now = 60.001+ assert (await operation(server, None))[0].name == "discovery-example"+ assert upstream.initializes == 2+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("kind", ("prompts", "resources", "templates"))+ @pytest.mark.parametrize("outcome", ("unsupported", "rejected", "failure"))+ async def test_discovery_cache_empty_results_and_failures(kind: str, outcome: str) -> None:+ import respx++ manager: Final = MCPServerManager()+ upstream: Final = _DiscoveryUpstream()+ upstream.outcome = outcome+ operation: Final = {+ "prompts": manager.get_prompts_from_server,+ "resources": manager.get_resources_from_server,+ "templates": manager.get_resource_templates_from_server,+ }[kind]+ with _mcp_upstream(upstream.respond):+ assert await operation(_discovery_server(), None) == []+ assert await operation(_discovery_server(), None) == []+ assert upstream.initializes == (2 if outcome == "failure" else 1)+ if outcome == "failure":+ upstream.outcome = "supported"+ assert (await operation(_discovery_server(), None))[0].name == "discovery-example"+ assert upstream.initializes == 3++[email protected]("kind", ("prompts", "resources", "templates"))++async def test_discovery_cache_retries_failed_pagination_before_caching_complete_list(kind: str) -> None:++ manager: Final = MCPServerManager()++ upstream: Final = _DiscoveryUpstream()++ upstream.outcome = "paged_failure"++ operation: Final = {++ "prompts": manager.get_prompts_from_server,++ "resources": manager.get_resources_from_server,++ "templates": manager.get_resource_templates_from_server,++ }[kind]++ with _mcp_upstream(upstream.respond):++ assert await operation(_discovery_server(), None) == []++ assert upstream.initializes == 1++ upstream.outcome = "paged"++ recovered: Final = await operation(_discovery_server(), None)++ assert [item.name for item in recovered] == ["discovery-example", "discovery-example"]++ assert upstream.initializes == 2++ requests_after_recovery: Final = upstream.requests++ assert await operation(_discovery_server(), None) == recovered++ assert upstream.requests == requests_after_recovery+++++ @pytest.mark.asyncio+ async def test_discovery_cache_isolates_forwarded_credentials_and_shares_static_auth() -> None:+ import respx++ manager: Final = MCPServerManager()+ upstream: Final = _DiscoveryUpstream()+ server: Final = _discovery_server()+ first_user: Final = UserAPIKeyAuth(user_id="first")+ second_user: Final = UserAPIKeyAuth(user_id="second")+ with _mcp_upstream(upstream.respond):+ for user in (first_user, second_user):+ assert len(await manager.get_prompts_from_server(server, user)) == 1+ assert upstream.initializes == 1+ for credential in ("first-secret", "second-secret", "first-secret"):+ assert (+ len(+ await manager.get_prompts_from_server(+ server, first_user, extra_headers={"Authorization": credential}+ )+ )+ == 1+ )+ assert upstream.initializes == 3+ assert {auth for method, auth in upstream.requests if method == "prompts/list"} == {+ "",+ "first-secret",+ "second-secret",+ }+++ @pytest.mark.asyncio+ async def test_discovery_cache_coalesces_and_survives_waiter_cancellation() -> None:+ import respx++ manager: Final = MCPServerManager()+ upstream: Final = _DiscoveryUpstream()+ upstream.release.clear()+ with _mcp_upstream(upstream.respond):+ tasks: Final = tuple(+ asyncio.create_task(manager.get_prompts_from_server(_discovery_server(), None)) for _ in range(10)+ )+ await asyncio.wait_for(upstream.entered.wait(), timeout=5)+ tasks[0].cancel()+ with pytest.raises(asyncio.CancelledError):+ await tasks[0]+ upstream.release.set()+ results: Final = await asyncio.wait_for(asyncio.gather(*tasks[1:]), timeout=5)+ assert all(result[0].name == "discovery-example" for result in results)+ assert upstream.initializes == 1+ assert results[0][0] is not results[1][0]+ assert (await manager.get_prompts_from_server(_discovery_server(), None))[0].name == "discovery-example"+ assert upstream.initializes == 1+++ @pytest.mark.asyncio+ async def test_discovery_cache_invalidation_during_fetch_does_not_repopulate_old_results() -> None:+ import respx++ manager: Final = MCPServerManager()+ upstream: Final = _DiscoveryUpstream()+ upstream.release.clear()+ with _mcp_upstream(upstream.respond):+ task: Final = asyncio.create_task(manager.get_prompts_from_server(_discovery_server(), None))+ await asyncio.wait_for(upstream.entered.wait(), timeout=5)+ manager._invalidate_discovery_lists("discovery")+ upstream.release.set()+ assert (await task)[0].name == "discovery-example"+ assert len(await manager.get_prompts_from_server(_discovery_server(), None)) == 1+ assert upstream.initializes == 2+ manager._invalidate_discovery_lists("discovery")+ assert len(await manager.get_prompts_from_server(_discovery_server(), None)) == 1+ assert upstream.initializes == 3+++ @pytest.mark.asyncio+ async def test_discovery_cache_can_be_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ import respx++ monkeypatch.setenv("LITELLM_MCP_DISCOVERY_CACHE_TTL", "0")+ manager: Final = MCPServerManager()+ upstream: Final = _DiscoveryUpstream()+ with _mcp_upstream(upstream.respond):+ assert len(await manager.get_prompts_from_server(_discovery_server(), None)) == 1+ assert len(await manager.get_prompts_from_server(_discovery_server(), None)) == 1+ assert upstream.initializes == 2+++ @pytest.mark.parametrize("value,expected", (("invalid", 60.0), ("nan", 60.0), ("inf", 60.0), ("-1", 60.0), ("12.5", 12.5)))+ def test_discovery_cache_ttl_validation(value: str, expected: float, monkeypatch: pytest.MonkeyPatch) -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _mcp_discovery_cache_ttl++ monkeypatch.setenv("LITELLM_MCP_DISCOVERY_CACHE_TTL", value)+ assert _mcp_discovery_cache_ttl() == expected+++ @pytest.mark.parametrize("auth_type", (MCPAuth.oauth2, MCPAuth.oauth2_token_exchange, MCPAuth.oauth2_id_jag))+ def test_discovery_cache_keys_isolate_user_dependent_auth(auth_type: MCPAuth) -> None:+ manager: Final = MCPServerManager()+ server: Final = _discovery_server().model_copy(update={"auth_type": auth_type})+ first: Final = manager._discovery_key(server, UserAPIKeyAuth(user_id="first"), None, None, None, None)+ second: Final = manager._discovery_key(server, UserAPIKeyAuth(user_id="second"), None, None, None, None)+ anonymous: Final = manager._discovery_key(server, None, None, None, None, None)+ assert len({first, second, anonymous}) == 3+ assert "first" not in str(first)+ assert "second" not in str(second)+++ @pytest.mark.asyncio+ async def test_discovery_cache_retries_cancelled_fetches() -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _DiscoveryCache++ cache: Final = _DiscoveryCache[Prompt](60, _DiscoveryClock(), TypeAdapter(tuple[Prompt, ...]))++ async def cancelled() -> list[Prompt]:+ raise asyncio.CancelledError()++ async def supported() -> list[Prompt]:+ return [Prompt(name="recovered")]++ with pytest.raises(asyncio.CancelledError):+ await cache.get(("server", None), cancelled)+ assert [item.name for item in await cache.get(("server", None), supported)] == ["recovered"]+++ @pytest.mark.asyncio+ async def test_discovery_cache_cancels_fetch_when_last_waiter_leaves() -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _DiscoveryCache++ cache: Final = _DiscoveryCache[Prompt](60, _DiscoveryClock(), TypeAdapter(tuple[Prompt, ...]))+ entered: Final = asyncio.Event()+ stopped: Final = asyncio.Event()+ release: Final = asyncio.Event()++ async def fetch() -> list[Prompt]:+ entered.set()+ try:+ await release.wait()+ return [Prompt(name="result")]+ finally:+ stopped.set()++ tasks: Final = tuple(asyncio.create_task(cache.get(("server", None), fetch)) for _ in range(3))+ await asyncio.wait_for(entered.wait(), timeout=5)+ for task in tasks:+ task.cancel()+ outcomes: Final = await asyncio.gather(*tasks, return_exceptions=True)+ assert all(isinstance(outcome, asyncio.CancelledError) for outcome in outcomes)+ try:+ await asyncio.wait_for(stopped.wait(), timeout=1)+ finally:+ release.set()+++ @pytest.mark.asyncio+ async def test_discovery_cache_bounds_detached_fetches_without_dropping_results() -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _DiscoveryCache++ cache: Final = _DiscoveryCache[Prompt](60, _DiscoveryClock(), TypeAdapter(tuple[Prompt, ...]))+ entered: Final[asyncio.Queue[None]] = asyncio.Queue()+ release: Final = asyncio.Event()++ async def blocked() -> list[Prompt]:+ await entered.put(None)+ await release.wait()+ return [Prompt(name="blocked")]++ tasks: Final = tuple(asyncio.create_task(cache.get((str(index), None), blocked)) for index in range(1024))+ try:+ for _ in tasks:+ await asyncio.wait_for(entered.get(), timeout=5)+ active_tasks: Final = frozenset(asyncio.all_tasks())++ async def overflow() -> list[Prompt]:+ assert frozenset(asyncio.all_tasks()) <= active_tasks+ return [Prompt(name="overflow")]++ result: Final = await cache.get(("overflow", None), overflow)+ assert [item.name for item in result] == ["overflow"]+ finally:+ release.set()+ outcomes: Final = await asyncio.gather(*tasks)+ assert all(result[0].name == "blocked" for result in outcomes)+++ @pytest.mark.asyncio+ async def test_discovery_cache_tracks_resolved_credentials_across_workers() -> None:+ import respx+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import StaticHeaderAuth+ from litellm.proxy._experimental.mcp_server.outbound_credentials.resolver import UpstreamCredentialProvider+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Error, Ok, Result+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import CredError, ServerSpec, Subject++ class CredentialSource(UpstreamCredentialProvider):+ def __init__(self) -> None:+ super().__init__()+ self.token: str | None = "token-a"++ async def resolve_credentials(self, subject: Subject, server: ServerSpec) -> Result[httpx.Auth, CredError]:+ if self.token is None:+ return Error(CredError.of_unauthorized("Credential revoked"))+ return Ok(StaticHeaderAuth("Bearer " + self.token))++ source: Final = CredentialSource()+ managers: Final = (MCPServerManager(cred_provider=source), MCPServerManager(cred_provider=source))+ server: Final = MCPServer(+ server_id="discovery",+ name="discovery",+ url="https://discovery.example/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2,+ oauth2_flow="authorization_code",+ client_id="discovery-client",+ authorization_url="https://discovery.example/authorize",+ token_url="https://discovery.example/token",+ )+ user: Final = UserAPIKeyAuth(user_id="same-user", api_key="same-key")+ upstream: Final = _DiscoveryUpstream()++ async def respond(request: httpx2.Request) -> httpx2.Response:+ response: Final = await upstream.respond(request)+ if '"prompts/list"' not in request.content.decode():+ return response+ from mcp.types import JSONRPCRequest++ payload: Final = _JSONRPC_ADAPTER.validate_json(request.content)+ assert isinstance(payload, JSONRPCRequest)+ name: Final = {"Bearer token-a": "account-a", "Bearer token-b": "account-b"}[request.headers["authorization"]]+ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": {"prompts": [{"name": name}]}})++ with _mcp_upstream(respond):+ for manager in managers:+ assert [item.name for item in await manager.get_prompts_from_server(server, user)] == [+ "discovery-account-a"+ ]+ assert upstream.initializes == 2+ source.token = "token-b"+ for manager in managers:+ assert [item.name for item in await manager.get_prompts_from_server(server, user)] == [+ "discovery-account-b"+ ]+ assert upstream.initializes == 4+ source.token = None+ for manager in managers:+ assert await manager.get_prompts_from_server(server, user) == []+ assert upstream.initializes == 4+++ @pytest.mark.asyncio+ async def test_discovery_resolves_stored_oauth_for_the_requesting_user() -> None:+ import respx+ from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import OAuthToken++ class TokenStore:+ def __init__(self) -> None:+ self.calls: tuple[tuple[str, str], ...] = ()++ async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None:+ self.calls = (*self.calls, (user_id, server_id))+ return OAuthToken(access_token="stored-token")++ async def invalidate(self, user_id: str, server_id: str) -> None:+ return None++ store: Final = TokenStore()+ manager: Final = MCPServerManager(per_user_oauth_token_store=store)+ server: Final = MCPServer(+ server_id="discovery",+ name="discovery",+ url="https://discovery.example/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2,+ oauth2_flow="authorization_code",+ client_id="discovery-client",+ authorization_url="https://discovery.example/authorize",+ token_url="https://discovery.example/token",+ )+ user: Final = UserAPIKeyAuth(user_id="requesting-user")+ upstream: Final = _DiscoveryUpstream()+ with _mcp_upstream(upstream.respond):+ assert len(await manager.get_prompts_from_server(server, user)) == 1+ assert len(await manager.get_prompts_from_server(server, user)) == 1+ assert store.calls == (("requesting-user", "discovery"), ("requesting-user", "discovery"))+ assert upstream.initializes == 1+ assert ("prompts/list", "Bearer stored-token") in upstream.requests+++ @pytest.mark.asyncio+ async def test_discovery_cache_evicts_results_at_capacity() -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _DiscoveryCache++ cache: Final = _DiscoveryCache[Prompt](60, _DiscoveryClock(), TypeAdapter(tuple[Prompt, ...]))++ async def original() -> list[Prompt]:+ return [Prompt(name="original")]++ async def refetched() -> list[Prompt]:+ return [Prompt(name="refetched")]++ for index in range(1025):+ assert (await cache.get((f"server-{index:04}", None), original))[0].name == "original"+ assert (await cache.get(("server-1024", None), refetched))[0].name == "original"+ assert (await cache.get(("server-0000", None), refetched))[0].name == "refetched"+++ @pytest.mark.asyncio+ async def test_discovery_cache_invalidation_preserves_other_servers_and_pending_fetches() -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _DiscoveryCache++ cache: Final = _DiscoveryCache[Prompt](60, _DiscoveryClock(), TypeAdapter(tuple[Prompt, ...]))+ entered: Final = asyncio.Event()+ release: Final = asyncio.Event()++ async def original() -> list[Prompt]:+ return [Prompt(name="original")]++ async def blocked() -> list[Prompt]:+ entered.set()+ await release.wait()+ return [Prompt(name="pending")]++ async def refetched() -> list[Prompt]:+ return [Prompt(name="refetched")]++ assert (await cache.get(("server", None), original))[0].name == "original"+ assert (await cache.get(("server-extra", None), original))[0].name == "original"+ task: Final = asyncio.create_task(cache.get(("other", None), blocked))+ await asyncio.wait_for(entered.wait(), timeout=5)+ cache.invalidate("server")+ release.set()+ assert (await asyncio.wait_for(task, timeout=5))[0].name == "pending"+ assert (await cache.get(("other", None), refetched))[0].name == "pending"+ assert (await cache.get(("server-extra", None), refetched))[0].name == "original"+ assert (await cache.get(("server", None), refetched))[0].name == "refetched"+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("description", ("x" * 96_000, "é" * 40_000), ids=("ascii", "unicode"))+ async def test_discovery_cache_returns_oversized_results_without_retaining_them(description: str) -> None:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _DiscoveryCache++ cache: Final = _DiscoveryCache[Prompt](60, _DiscoveryClock(), TypeAdapter(tuple[Prompt, ...]))+ fetch: Final = AsyncMock(return_value=[Prompt(name="large", description=description)])+ for _ in range(2):+ result: Final = await cache.get(("server", None), fetch)+ assert result[0].description == description+ assert fetch.await_count == 2+++ class TestProtectedCredentialPreparation:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type,credential", [+ (MCPAuth.bearer_token, None),+ (MCPAuth.bearer_token, "Bearer"),+ (MCPAuth.api_key, None),+ (MCPAuth.basic, "Basic"),+ ])+ @pytest.mark.parametrize("dispatch", ["managed", "local"])+ async def test_openapi_dispatch_rejects_unusable_effective_credentials(+ self, tmp_path: Path, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch,+ auth_type: MCPAuthType, credential: str | None, dispatch: str,+ ) -> None:+ from litellm.proxy._experimental.mcp_server.server import _handle_local_mcp_tool+ from litellm.proxy._experimental.mcp_server.utils import add_server_prefix_to_name, get_server_prefix++ spec_path: Final = tmp_path / "openapi.json"+ spec_path.write_text(json.dumps({"openapi": "3.0.0", "info": {"title": "Auth", "version": "1"},+ "paths": {"/echo": {"get": {"operationId": "echo"}}}}))+ server: Final = MCPServer(+ server_id="dispatch-auth", name="dispatch-auth", url="https://upstream.example",+ transport=MCPTransport.http, auth_type=auth_type, authentication_token=credential,+ )+ manager: Final = MCPServerManager()+ await manager._register_openapi_tools(str(spec_path), server, server.url)+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ destination: Final = respx_mock.get("https://upstream.example/echo").respond(200, text="unexpected success")+ result: Final = (+ await manager._call_openapi_tool_handler(server, "echo", {})+ if dispatch == "managed"+ else await _handle_local_mcp_tool(add_server_prefix_to_name("echo", get_server_prefix(server)), {})+ )+ assert result.is_error is True+ assert "requires a usable upstream credential" in result.content[0].text+ assert destination.call_count == 0++ @pytest.mark.asyncio+ @pytest.mark.parametrize("transport", [MCPTransport.http, MCPTransport.sse])+ @pytest.mark.parametrize("client_secret", [None, ""])+ @pytest.mark.parametrize("subject", [None, "caller-subject"])+ async def test_incomplete_obo_rejects_caller_and_static_fallback(+ self, transport: MCPTransport, client_secret: str | None, subject: str | None+ ) -> None:+ server = MCPServer(+ server_id="incomplete-obo", name="incomplete-obo", url="https://upstream.example/mcp",+ transport=transport, auth_type=MCPAuth.oauth2_token_exchange,+ client_id="gateway", client_secret=client_secret,+ token_exchange_endpoint="https://idp.example/token", authentication_token="static-fallback",+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(+ server, mcp_auth_header="Bearer override", subject_token=subject,+ )+ assert exc.value.status_code == (401 if subject is None else 500)+ assert "static-fallback" not in str(exc.value.detail)+ assert "override" not in str(exc.value.detail)++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type", [MCPAuth.api_key, MCPAuth.bearer_token])+ @pytest.mark.parametrize("credential", [None, "", " ", {"X-Trace": "trace"}])+ async def test_static_auth_without_usable_credential_rejects(+ self, auth_type: MCPAuthType, credential: str | dict[str, str] | None+ ) -> None:+ server = MCPServer(+ server_id="empty-static", name="empty-static", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type,+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, mcp_auth_header=credential)+ assert exc.value.status_code == 500+ assert "credential" in str(exc.value.detail).lower()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type,headers", [+ (MCPAuth.api_key, {"X-API-Key": "key"}),+ (MCPAuth.bearer_token, {"Authorization": "Bearer token"}),+ ])+ async def test_static_auth_accepts_actual_forwarded_credential(+ self, auth_type: MCPAuthType, headers: dict[str, str]+ ) -> None:+ server = MCPServer(+ server_id="header-static", name="header-static", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type,+ )+ client = await MCPServerManager()._create_mcp_client(server, extra_headers=headers)+ assert client._get_auth_headers() == headers++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type", [MCPAuth.oauth2_token_exchange])+ async def test_openapi_protected_auth_rejects_missing_credentials(self, auth_type: MCPAuthType) -> None:+ server = MCPServer(+ server_id="openapi-empty", name="openapi-empty", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type,+ token_exchange_endpoint="https://idp.example/token",+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager().resolve_openapi_upstream_auth(+ mcp_server=server, oauth2_headers=None, raw_headers=None, mcp_auth_header=None,+ user_api_key_auth=None, forwarded_headers=None,+ )+ assert exc.value.status_code in (401, 500)++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type,slot,value", [+ (MCPAuth.api_key, "X-API-Key", "token"),+ (MCPAuth.authorization, "Authorization", "opaque-secret-value"),+ (MCPAuth.authorization, "Authorization", "Bearer abc"),+ (MCPAuth.authorization, "Authorization", "Custom abc"),+ ])+ async def test_raw_static_credentials_are_forwarded_unchanged(+ self, auth_type: MCPAuthType, slot: str, value: str,+ ) -> None:+ server = MCPServer(server_id="raw-key", name="raw-key", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type, authentication_token=value)+ client = await MCPServerManager()._create_mcp_client(server)+ assert client._resolved_auth is not None+ request = httpx.Request("GET", server.url)+ flow = client._resolved_auth.auth_flow(request)+ try:+ assert next(flow).headers[slot] == value+ finally:+ flow.close()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", ["Bearer", "basic", "token", "ApiKey", " bEaReR ", "\tTOKEN\t"])+ @pytest.mark.parametrize("source", ["configured", "caller", "forwarded"])+ async def test_raw_authorization_rejects_bare_schemes_before_dispatch(+ self, respx_mock: MockRouter, value: str, source: str,+ ) -> None:+ server: Final = MCPServer(+ server_id="raw-empty", name="raw-empty", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.authorization,+ authentication_token=value if source == "configured" else None,+ )+ destination: Final = respx_mock.route().respond(200)+ with pytest.raises(HTTPException, match="requires a usable upstream credential") as exc:+ await MCPServerManager()._create_mcp_client(+ server, mcp_auth_header=value if source == "caller" else None,+ extra_headers={"Authorization": value} if source == "forwarded" else None,+ )+ assert exc.value.status_code == 500+ assert destination.call_count == 0++ @pytest.mark.asyncio+ async def test_byok_flag_cannot_bypass_incomplete_obo(self) -> None:+ server = MCPServer(server_id="obo-byok", name="obo-byok", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.oauth2_token_exchange, is_byok=True,+ token_exchange_endpoint="https://idp.example/token")+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, mcp_auth_header="Bearer override")+ assert exc.value.status_code == 401++ @pytest.mark.asyncio+ @pytest.mark.parametrize("configured,override", [(None, "Bearer usable"), ("shared", "Bearer usable")])+ async def test_bearer_override_remains_usable(self, configured: str | None, override: str) -> None:+ server = MCPServer(server_id="override", name="override", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.bearer_token, authentication_token=configured)+ client = await MCPServerManager()._create_mcp_client(server, mcp_auth_header=override)+ assert client._get_auth_headers()["Authorization"] == override++ @pytest.mark.asyncio+ @pytest.mark.parametrize("token", [None, "shared"])+ async def test_empty_injected_header_cannot_satisfy_protected_auth(self, token: str | None) -> None:+ server = MCPServer(server_id="empty-header", name="empty-header", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.bearer_token, authentication_token=token)+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, extra_headers={"authorization": " "})+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ async def test_custom_slot_uses_its_actual_credential(self) -> None:+ server = MCPServer(server_id="custom", name="custom", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.api_key,+ upstream_token_header="X-Custom", authentication_token="key")+ client = await MCPServerManager()._create_mcp_client(server, extra_headers={"X-Trace": "trace"})+ assert client._credential_slot == "X-Custom"+ assert await client.discovery_auth_fingerprint()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("static_headers,accepted", [+ ({"apikey": "static-key"}, True),+ ({"apikey": ""}, False),+ ({"X-Tenant": "tenant"}, True),+ ])+ async def test_api_key_carried_by_static_header_passes_fail_closed_check(+ self, static_headers: dict[str, str], accepted: bool+ ) -> None:+ server: Final = MCPServer(+ server_id="static-slot", name="static-slot", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.api_key, static_headers=static_headers,+ )+ if not accepted:+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, extra_headers=dict(static_headers))+ assert exc.value.status_code == 500+ return+ client: Final = await MCPServerManager()._create_mcp_client(server, extra_headers=dict(static_headers))+ request: Final = await client.prepare_request_auth()+ assert all(request.headers[name] == value for name, value in static_headers.items())++ @pytest.mark.asyncio+ @pytest.mark.parametrize("static,forwarded,caller", [+ ({"X-API-Key": "static"}, {"x-api-key": "forwarded"}, None),+ ({}, {"X-API-Key": "forwarded"}, None),+ ({}, None, "ApiKey caller"),+ ({"X-API-Key": "static"}, {"Authorization": ""}, None),+ ])+ async def test_openapi_static_credentials_remain_supported(+ self, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch,+ static: dict[str, str], forwarded: dict[str, str] | None, caller: str | None+ ) -> None:+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (+ _request_auth_header, _request_extra_headers, create_tool_function,+ )+ tool: Final = create_tool_function(+ "/echo", "get", {}, "https://upstream.example", headers=static, auth_type=MCPAuth.api_key,+ )+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ destination: Final = respx_mock.get("https://upstream.example/echo").respond(200, text="authenticated")+ caller_token: Final = _request_auth_header.set(caller)+ extra_token: Final = _request_extra_headers.set(forwarded)+ try:+ assert await tool() == "authenticated"+ sent: Final = destination.calls.last.request.headers+ assert sent.get("x-api-key") == static.get("X-API-Key", (forwarded or {}).get("X-API-Key"))+ if caller:+ assert sent["authorization"] == caller+ assert destination.call_count == 1+ finally:+ _request_auth_header.reset(caller_token)+ _request_extra_headers.reset(extra_token)++ @pytest.mark.asyncio+ async def test_static_resolution_cancellation_closes_flow(self) -> None:+ from collections.abc import AsyncGenerator+ from litellm.experimental_mcp_client.client import MCPClient+ from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import prepare_mcp_client++ class CancelledAuth(httpx.Auth):+ closed = False++ async def async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]:+ try:+ raise asyncio.CancelledError()+ yield request+ finally:+ self.closed = True++ auth = CancelledAuth()+ server = MCPServer(server_id="cancel", name="cancel", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.api_key)+ client = MCPClient(server_url=server.url, auth_type=MCPAuth.api_key, resolved_auth=auth)+ with pytest.raises(asyncio.CancelledError):+ await prepare_mcp_client(server, client)+ assert auth.closed++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type", [MCPAuth.basic, MCPAuth.token, MCPAuth.authorization])+ async def test_other_static_schemes_reject_whitespace_credentials(self, auth_type: MCPAuthType) -> None:+ server = MCPServer(server_id="blank-static", name="blank-static", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type, authentication_token=" ")+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server)+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("header", ["Basic", "Basic @@@", "Other abc", "Basic QmFzaWM=", "Basic bm8tY29sb24="])+ async def test_basic_headers_without_usable_credentials_reject(self, header: str) -> None:+ server = MCPServer(server_id="bad-basic", name="bad-basic", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.basic)+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, extra_headers={"Authorization": header})+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", ["Basic", "Basic ", "basic"])+ @pytest.mark.parametrize("source", ["configured", "caller"])+ async def test_basic_scheme_alone_is_not_a_credential(self, value: str, source: str) -> None:+ server = MCPServer(server_id="basic-scheme", name="basic-scheme", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.basic,+ authentication_token=value if source == "configured" else None)+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, mcp_auth_header=value if source == "caller" else None)+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type,value,default_slot", [+ (MCPAuth.api_key, "fixture-key", "X-API-Key"),+ (MCPAuth.bearer_token, "fixture-key", "Authorization"),+ (MCPAuth.basic, "user:pass", "Authorization"),+ (MCPAuth.token, "fixture-key", "Authorization"),+ (MCPAuth.authorization, "fixture-key", "Authorization"),+ ])+ @pytest.mark.parametrize("source", ["configured", "caller"])+ async def test_usable_credential_survives_an_empty_alternate_header(+ self, auth_type: MCPAuthType, value: str, default_slot: str, source: str+ ) -> None:+ server: Final = MCPServer(+ server_id="alternate", name="alternate", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type, upstream_token_header="X-Custom",+ authentication_token=value if source == "configured" else None,+ )+ empty_slot: Final = default_slot if source == "configured" else "X-Custom"+ selected_slot: Final = "X-Custom" if source == "configured" else default_slot+ client: Final = await MCPServerManager()._create_mcp_client(+ server, mcp_auth_header=value if source == "caller" else None, extra_headers={empty_slot: ""},+ )+ request: Final = await client.prepare_request_auth()+ assert request.headers[selected_slot]+ assert request.headers[empty_slot] == ""++ @pytest.mark.asyncio+ async def test_empty_custom_and_default_headers_do_not_satisfy_auth(self) -> None:+ server: Final = MCPServer(+ server_id="both-empty", name="both-empty", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.api_key, upstream_token_header="X-Custom",+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, extra_headers={"X-Custom": "", "X-API-Key": ""})+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("custom_slot", [None, "X-Custom"])+ @pytest.mark.parametrize("source", ["caller", "forwarded"])+ async def test_api_key_preserves_explicit_authorization_credential(+ self, custom_slot: str | None, source: str+ ) -> None:+ server: Final = MCPServer(+ server_id="caller-auth", name="caller-auth", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.api_key, upstream_token_header=custom_slot,+ )+ headers: Final = {"Authorization": "Bearer caller-credential", "X-API-Key": ""}+ client: Final = await MCPServerManager()._create_mcp_client(+ server, mcp_auth_header=headers if source == "caller" else None,+ extra_headers=headers if source == "forwarded" else None,+ )+ request: Final = await client.prepare_request_auth()+ assert request.headers["Authorization"] == "Bearer caller-credential"+ assert request.headers["X-API-Key"] == ""+ assert custom_slot is None or custom_slot not in request.headers++ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", [+ "", " ", "Bearer", "Basic", "token", "ApiKey",+ "Bearer Bearer", "ApiKey ApiKey", "token token", "bEaReR BEARER", "aPiKeY\tAPIKEY",+ ])+ async def test_api_key_rejects_authorization_without_a_credential(self, value: str) -> None:+ server: Final = MCPServer(+ server_id="caller-empty", name="caller-empty", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.api_key,+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, mcp_auth_header={"Authorization": value})+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", ["no-colon", "Basic bm8tY29sb24="])+ @pytest.mark.parametrize("source", ["configured", "caller"])+ async def test_basic_requires_a_username_password_separator(self, value: str, source: str) -> None:+ server: Final = MCPServer(+ server_id="basic-pair", name="basic-pair", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.basic,+ authentication_token=value if source == "configured" else None,+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, mcp_auth_header=value if source == "caller" else None)+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("value", ["user:pass", "user:", ":pass", ":"])+ async def test_basic_preserves_username_password_pairs(self, value: str) -> None:+ import base64++ server: Final = MCPServer(+ server_id="basic-valid", name="basic-valid", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=MCPAuth.basic, authentication_token=value,+ )+ client: Final = await MCPServerManager()._create_mcp_client(server)+ request: Final = await client.prepare_request_auth()+ scheme, encoded = request.headers["Authorization"].split(" ", 1)+ assert scheme == "Basic"+ assert base64.b64decode(encoded) == value.encode()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type,value", [+ (MCPAuth.bearer_token, "Bearer"), (MCPAuth.bearer_token, "Bearer "), (MCPAuth.bearer_token, "bearer"),+ (MCPAuth.token, "token"), (MCPAuth.token, "token "), (MCPAuth.token, "TOKEN"),+ ])+ @pytest.mark.parametrize("source", ["configured", "caller"])+ async def test_static_scheme_only_input_cannot_hide_behind_rendered_prefix(+ self, auth_type: MCPAuthType, value: str, source: str+ ) -> None:+ server: Final = MCPServer(+ server_id="empty-scheme", name="empty-scheme", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type,+ authentication_token=value if source == "configured" else None,+ )+ with pytest.raises(HTTPException) as exc:+ await MCPServerManager()._create_mcp_client(server, mcp_auth_header=value if source == "caller" else None)+ assert exc.value.status_code == 500++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type,value,expected", [+ (MCPAuth.bearer_token, "token", "Bearer token"),+ (MCPAuth.bearer_token, "Bearertoken", "Bearer Bearertoken"),+ (MCPAuth.token, "tokenish", "token tokenish"),+ ])+ async def test_static_credentials_that_resemble_schemes_remain_usable(+ self, auth_type: MCPAuthType, value: str, expected: str+ ) -> None:+ server: Final = MCPServer(+ server_id="real-token", name="real-token", url="https://upstream.example/mcp",+ transport=MCPTransport.http, auth_type=auth_type, authentication_token=value,+ )+ client: Final = await MCPServerManager()._create_mcp_client(server)+ request: Final = await client.prepare_request_auth()+ assert request.headers["Authorization"] == expected+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("selected", [False, True])+ async def test_request_selected_during_guardrail_runs_concurrently_with_tool(monkeypatch, selected):+ from litellm.responses.mcp.request_context import MCPRequestContext+ from litellm.proxy._experimental.mcp_server import tool_registry++ tool_started = asyncio.Event()+ guardrail_started = asyncio.Event()++ class ObserveDuring(CustomGuardrail):+ async def async_moderation_hook(self, data, user_api_key_dict, call_type):+ if not self.should_run_guardrail(data, GuardrailEventHooks.during_mcp_call):+ return data+ assert data["mcp_tool_name"] == "execute"+ assert data["mcp_arguments"] == {"text": "hello"}+ guardrail_started.set()+ await tool_started.wait()+ return data++ async def upstream(text):+ assert text == "hello"+ tool_started.set()+ if selected:+ await guardrail_started.wait()+ return "executed"++ guardrail = ObserveDuring(guardrail_name="observe", event_hook="during_mcp_call", default_on=False)+ monkeypatch.setattr(litellm, "callbacks", [guardrail])+ registry = tool_registry.MCPToolRegistry()+ registry.register_tool("observer-execute", "Execute", {"type": "object"}, upstream)+ monkeypatch.setattr(tool_registry, "global_mcp_tool_registry", registry)+ manager = MCPServerManager()+ manager.registry = {"observer": MCPServer(+ server_id="observer", name="observer", server_name="observer", transport="http",+ url="https://observer.example/mcp", spec_path="observer.json", auth_type="none",+ )}+ manager.tool_name_to_mcp_server_name_mapping = {"observer-execute": "observer"}+ result = await asyncio.wait_for(manager.call_tool(+ server_name="observer", name="execute", arguments={"text": "hello"},+ user_api_key_auth=UserAPIKeyAuth(), proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),+ guardrail_context=MCPRequestContext.resolve_guardrail_context({"metadata": {"guardrails": ["observe"] if selected else []}}),+ ), timeout=5)+ assert tool_started.is_set()+ assert guardrail_started.is_set() is selected+ assert result.is_error is False+ assert result.content[0].text == "executed"