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): bound MCP client requests with a session read timeout (#36675)
Yassin Kortama01b421ce9b1
diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.pyindex d474291f1cb..7bd0a847ad8 100644--- a/litellm/experimental_mcp_client/client.py+++ b/litellm/experimental_mcp_client/client.py@@ -6,10 +6,11 @@ import asyncioimport base64import osfrom collections.abc import Awaitable, Callable, Generator+from datetime import timedeltafrom typing import Any, Final, TypeVarimport httpx-from mcp import ClientSession, ReadResourceResult, Resource, StdioServerParameters+from mcp import ClientSession, McpError, ReadResourceResult, Resource, StdioServerParametersfrom mcp.client.sse import sse_clientfrom mcp.client.stdio import stdio_client@@ -69,6 +70,29 @@ def _first_non_cancelled_cause(exc: BaseException) -> BaseException | None:return None+_SDK_READ_TIMEOUT_CODE: Final = int(httpx.codes.REQUEST_TIMEOUT)+"""The code the MCP SDK puts on its own elapsed read timeout, an HTTP status in a field that+otherwise carries JSON-RPC error codes."""+++def _as_read_timeout(exc: BaseException) -> TimeoutError | None:+ """The session read timeout elapsing, re-expressed as a ``TimeoutError``, or ``None``.++ The SDK reports its own elapsed read timeout as ``McpError`` carrying an HTTP status code in a+ field that otherwise holds JSON-RPC error codes, and it relays an upstream's JSON-RPC error+ through that same class and field. The numeric code alone therefore cannot separate the two, and+ an upstream answering with application code 408 would be reported as a gateway timeout it never+ caused. The SDK raises its own from inside an ``except TimeoutError``, so the elapsed timeout is+ on the context chain, while a relayed error is built from a received message and has no such+ chain; that is the discriminator.+ """+ if not isinstance(exc, McpError) or exc.error.code != _SDK_READ_TIMEOUT_CODE:+ return None+ if not isinstance(exc.__context__, TimeoutError):+ return None+ return TimeoutError(exc.error.message)++TSessionResult = TypeVar("TSessionResult")@@ -347,7 +371,14 @@ class MCPClient:session_kwargs["elicitation_callback"] = self._elicitation_callbackif self._logging_callback is not None:session_kwargs["logging_callback"] = self._logging_callback- session_ctx: Final = ClientSession(read_stream, write_stream, **session_kwargs)+ # The SDK drops a response stream that ends without a JSON-RPC reply, so nothing else+ # ever fails the request.+ session_ctx: Final = ClientSession(+ read_stream,+ write_stream,+ read_timeout_seconds=timedelta(seconds=self.timeout),+ **session_kwargs,+ )session: Final = await session_ctx.__aenter__()try:init_result: Final = await session.initialize()@@ -390,7 +421,16 @@ class MCPClient:self._last_initialize_instructions = Nonetransport_ctx, http_client = self._create_transport_context()return await self._execute_session_operation(transport_ctx, operation)- except Exception:+ except Exception as e:+ read_timeout: Final = _as_read_timeout(e)+ if read_timeout is not None:+ verbose_logger.warning(+ "MCP client timed out after %ss waiting for %s to answer; the server accepted the "+ "request and ended its response stream without a JSON-RPC reply",+ self.timeout,+ self.server_url or "stdio",+ )+ raise read_timeout from e_log: Final = verbose_logger.debug if quiet_on_error else verbose_logger.warning_log("MCP client run_with_session failed for %s", self.server_url or "stdio")raisediff --git a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py b/tests/test_litellm/experimental_mcp_client/test_mcp_client.pyindex 8e6fa35b452..7beb1c43a94 100644--- a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py+++ b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py@@ -3,8 +3,21 @@ import osimport sysfrom unittest.mock import AsyncMock, MagicMock, patch+import anyioimport httpximport pytest+from mcp import McpError+from mcp.shared.message import SessionMessage+from mcp.types import (+ LATEST_PROTOCOL_VERSION,+ ErrorData,+ Implementation,+ InitializeResult,+ JSONRPCError,+ JSONRPCMessage,+ JSONRPCResponse,+ ServerCapabilities,+)# Add the parent directory to the path so we can import litellmsys.path.insert(0, "../../../")@@ -12,8 +25,13 @@ sys.path.insert(0, "../../../")import litellm.experimental_mcp_client.client as mcp_client_modulefrom litellm.experimental_mcp_client.client import (MCPClient,+ _as_read_timeout,_first_non_cancelled_cause,)+from litellm.proxy._experimental.mcp_server.faults.list_outcomes import (+ classify_list_exception,+ list_fault_http_status,+)from litellm.types.mcp import MCPAuth, MCPStdioConfig, MCPTransport@@ -701,3 +719,171 @@ async def test_run_with_session_quiet_on_error_demotes_warning_to_debug():assert any("run_with_session failed" in m for m in warning_msgs), ("the default path must keep the operator-visible warning")+++class _ScriptedUpstream:+ """An in-memory MCP upstream that answers ``initialize`` and then follows one script for+ ``tools/list``.++ ``answer=None`` ends the response stream without a JSON-RPC reply, which is what a+ streamable-HTTP upstream does when its SSE stream closes early: the SDK drops the message and+ the request is never resolved and never fails. Anything else is sent back as that JSON-RPC+ error, the shape an upstream application uses to report its own failure.+ """++ def __init__(self, tools_list_error: ErrorData | None = None):+ self._tools_list_error = tools_list_error+ self._to_client_tx, self._to_client_rx = anyio.create_memory_object_stream(10)+ self._from_client_tx, self._from_client_rx = anyio.create_memory_object_stream(10)+ self._task_group = None++ async def __aenter__(self):+ self._task_group = anyio.create_task_group()+ await self._task_group.__aenter__()+ self._task_group.start_soon(self._serve)+ return self._to_client_rx, self._from_client_tx++ async def __aexit__(self, *_exc_info):+ self._task_group.cancel_scope.cancel()+ return await self._task_group.__aexit__(None, None, None)++ async def _send(self, message):+ await self._to_client_tx.send(SessionMessage(JSONRPCMessage(message)))++ async def _serve(self):+ async for session_message in self._from_client_rx:+ request = session_message.message.root+ method = getattr(request, "method", None)+ if method == "initialize":+ result = InitializeResult(+ protocolVersion=LATEST_PROTOCOL_VERSION,+ capabilities=ServerCapabilities(),+ serverInfo=Implementation(name="scripted-upstream", version="1.0.0"),+ )+ await self._send(+ JSONRPCResponse(+ jsonrpc="2.0",+ id=request.id,+ result=result.model_dump(by_alias=True, mode="json", exclude_none=True),+ )+ )+ elif method == "tools/list" and self._tools_list_error is not None:+ await self._send(JSONRPCError(jsonrpc="2.0", id=request.id, error=self._tools_list_error))+++class _ScriptedClient(MCPClient):+ """An MCPClient whose transport is a scripted in-memory upstream instead of a real connection,+ so the real ``ClientSession`` and its real timeout machinery are what run."""++ def __init__(self, *, timeout: float, tools_list_error: ErrorData | None = None):+ super().__init__(server_url="http://upstream.local/mcp", timeout=timeout)+ self._upstream = _ScriptedUpstream(tools_list_error=tools_list_error)++ def _create_transport_context(self):+ return self._upstream, None+++async def test_list_tools_fails_on_its_own_timeout_when_the_upstream_never_answers():+ """An upstream that accepts the request and never answers must fail the client's own timeout.++ Without a session read timeout the request waits forever, so discovery only ends when an outer+ cancel scope kills it. That is the reported symptom: a cancelled list_tools, no tools, and a+ fault that blames the gateway. The outer guard here is 20x the client timeout, so a run that+ reaches it proves nothing bounded the request.++ The classification is asserted here, off a real ``ClientSession`` running its real read timeout,+ rather than off a hand-built exception. A hand-built fixture encodes what we currently believe+ the SDK raises and would keep passing after the SDK stopped raising it, at which point the+ translation would quietly stop matching and the fault would silently downgrade to ``internal``.+ Driving the real path makes an SDK bump that breaks the discriminator fail loudly instead.+ """+ client = _ScriptedClient(timeout=0.5)++ started = asyncio.get_running_loop().time()+ with pytest.raises(TimeoutError) as exc_info:+ await asyncio.wait_for(client.list_tools(raise_on_error=True), timeout=10)+ elapsed = asyncio.get_running_loop().time() - started++ assert elapsed < 5, f"the request must end on the client's own 0.5s timeout, took {elapsed:.2f}s"++ fault = classify_list_exception(exc_info.value)+ assert fault.tag == "timeout", "an upstream that stopped answering must not be classified as the gateway's fault"+ assert list_fault_http_status(fault) == 504+++async def test_upstream_json_rpc_error_408_is_not_reported_as_a_client_timeout():+ """The SDK reports its own elapsed read timeout and relays an upstream JSON-RPC error through+ the same exception class and the same numeric field, and JSON-RPC error codes are a different+ namespace from HTTP status codes. An upstream answering with application code 408 must keep+ travelling as ``McpError`` so it is never blamed on the gateway as a 504.++ This is the other half of the pair: the same real transport and the same real session, so one+ mechanism pins both directions.+ """+ client = _ScriptedClient(+ timeout=30,+ tools_list_error=ErrorData(code=int(httpx.codes.REQUEST_TIMEOUT), message="re-authenticate and retry"),+ )++ with pytest.raises(McpError) as exc_info:+ await asyncio.wait_for(client.list_tools(raise_on_error=True), timeout=10)++ assert not isinstance(exc_info.value, TimeoutError), "an upstream application error is not a gateway timeout"+ assert exc_info.value.error.code == int(httpx.codes.REQUEST_TIMEOUT)++ fault = classify_list_exception(exc_info.value)+ assert fault.tag != "timeout", "an upstream's own application error must never be reported as a gateway timeout"+ assert list_fault_http_status(fault) != 504+++def _raise_mcp_error_while_handling_a_timeout(code: int, message: str) -> McpError:+ """An ``McpError`` carrying the context chain it would have if it were raised while a+ ``TimeoutError`` was in flight, which is how the SDK raises its own read timeout."""+ try:+ try:+ raise TimeoutError()+ except TimeoutError:+ raise McpError(ErrorData(code=code, message=message))+ except McpError as raised:+ return raised+++def test_as_read_timeout_separates_the_sdk_timeout_from_a_relayed_upstream_error():+ """Neither signal alone is enough. The code alone cannot separate the SDK's own timeout from an+ upstream JSON-RPC error that happens to use 408, and the context chain alone cannot separate it+ from any other relayed error that surfaces while a timeout is being handled, so both must hold.+ """+ timeout_code = int(httpx.codes.REQUEST_TIMEOUT)++ translated = _as_read_timeout(_raise_mcp_error_while_handling_a_timeout(timeout_code, "Timed out while waiting"))+ assert isinstance(translated, TimeoutError)+ assert str(translated) == "Timed out while waiting"++ relayed_408 = McpError(ErrorData(code=timeout_code, message="upstream said 408"))+ assert _as_read_timeout(relayed_408) is None, "an upstream 408 with no elapsed timeout is not our timeout"++ relayed_other = _raise_mcp_error_while_handling_a_timeout(-32603, "upstream internal error")+ assert _as_read_timeout(relayed_other) is None, "a non-timeout code is not our timeout, whatever the chain"++ assert _as_read_timeout(McpError(ErrorData(code=-32603, message="boom"))) is None+ assert _as_read_timeout(RuntimeError("not an McpError")) is None+++async def test_read_timeout_logs_an_actionable_line_that_quiet_on_error_cannot_demote():+ """The reported failure surfaced only as "MCP Client list_tools was cancelled", which names+ neither the server nor the elapsed budget. An upstream that stops answering is always+ operator-actionable, so this line stays at warning even for callers that own the exception."""+ client = _ScriptedClient(timeout=0.5)++ with patch.object(mcp_client_module, "verbose_logger") as mock_log:+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(client.list_tools(raise_on_error=True), timeout=10)++ warnings = [str(call.args[0]) % tuple(call.args[1:]) for call in mock_log.warning.call_args_list if call.args]+ timeout_lines = [line for line in warnings if "timed out after" in line]+ assert timeout_lines, f"expected an actionable timeout warning, got {warnings}"+ assert "http://upstream.local/mcp" in timeout_lines[0], "the line must name the server that stopped answering"+ assert "0.5s" in timeout_lines[0], "the line must name the budget that elapsed"diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.pyindex cb27e992ecb..64afa52ab55 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py@@ -4,6 +4,8 @@ stay truthful to who failed."""import httpximport pytest+from mcp import McpError+from mcp.types import ErrorDatafrom litellm.proxy._experimental.mcp_server.exceptions import (MCPServerListError,@@ -33,6 +35,16 @@ def test_timeout_and_connection_errors_classify_without_status():assert classify_list_exception(ConnectionError()).tag == "unreachable"+def test_upstream_json_rpc_error_code_is_never_read_as_an_http_status():+ """JSON-RPC error codes and HTTP status codes are different namespaces, so an upstream is free+ to answer with application code 408. Classifying that number as a gateway timeout would report+ a 504 the gateway never caused. A client timeout reaches here already expressed as a+ ``TimeoutError``, so this taxonomy never has to read the code to tell them apart."""+ upstream_error = McpError(ErrorData(code=int(httpx.codes.REQUEST_TIMEOUT), message="re-authenticate and retry"))+ assert classify_list_exception(upstream_error).tag != "timeout"+ assert list_fault_http_status(classify_list_exception(upstream_error)) != 504++def test_embedded_upstream_response_status_wins():response = httpx.Response(503, request=httpx.Request("POST", "https://mcp.example.com/mcp"))exc = httpx.HTTPStatusError("boom", request=response.request, response=response)