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
chore: merge current staging for MCP diagnostic compatibility
Joshua Vallurueec7c1e7f84f
diff --cc litellm/proxy/_experimental/mcp_server/mcp_debug.pyindex c608e0a73f0,ff30ef99ebd..07e77856894--- a/litellm/proxy/_experimental/mcp_server/mcp_debug.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_debug.py@@@ -85,23 -100,16 +100,23 @@@ Usage with curl:http://localhost:4000/mcp/atlassian_mcp"""+import asyncioimport json- from collections.abc import AsyncIterator-from collections.abc import Callable, Mapping++from collections.abc import AsyncIterator, Callable, Mapping+from itertools import islice- from typing import TYPE_CHECKING, Final+ from types import MappingProxyType+ from typing import Final+from urllib.parse import parse_qsl, urlencode+import httpx+from pydantic import JsonValue, TypeAdapter, ValidationError+ from starlette.requests import HTTPConnectionfrom starlette.types import Message, Send+from litellm.litellm_core_utils.secret_redaction import REDACTED, redact_stringfrom litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker+from litellm.proxy._experimental.mcp_server.faults.traversal import iter_exception_tree-- if TYPE_CHECKING:- from litellm.types.mcp_server.mcp_server_manager import MCPServer+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import AuthResolution# Header the client sends to opt into debug modeMCP_DEBUG_REQUEST_HEADER: Final = "x-litellm-mcp-debug"diff --cc litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex b6712d68f72,17d3098bf4c..b6e6e6adde5--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@@ -80,7 -81,7 +81,7 @@@ from litellm.proxy._experimental.mcp_seraise_classified_list_failure,upstream_auth_challenge,)- from litellm.proxy._experimental.mcp_server.mcp_debug import describe_upstream_http_failure-from litellm.proxy._experimental.mcp_server.mcp_debug import record_auth_resolution++from litellm.proxy._experimental.mcp_server.mcp_debug import describe_upstream_http_failure, record_auth_resolutionfrom litellm.proxy._experimental.mcp_server.oauth2_token_cache import (MCPPerUserTokenCache,mcp_per_user_token_cache,diff --cc tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_debug.pyindex 8ca9edc1ff9,7d46bb0237a..0ed78fcfc9d--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_debug.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_debug.py@@@ -3,15 -3,17 +3,21 @@@ Tests for MCPDebug — MCP OAuth2 debu"""import asyncio- from unittest.mock import MagicMock+ from typing import Final- import httpximport pytest+ from starlette.types import Message++ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import AuthResolution+++import httpx+from litellm.proxy._experimental.mcp_server.mcp_debug import (MCP_DEBUG_REQUEST_HEADER,MCPDebug,+ describe_upstream_http_failure,+++ MCPAuthDiagnostics,)@@@ -275,192 -206,88 +210,278 @@@ class TestWrapSendWithDebugHeadersassert captured[0] == body_msg+class TestDescribeUpstreamHttpFailure:+ @staticmethod+ def _status_error(*, body: bytes, response_body: bytes | None = None) -> httpx.HTTPStatusError:+ request = httpx.Request(+ "POST",+ "https://upstream.example/apis/mcp",+ headers={"Authorization": "Bearer secret-token-abcdef0123456789", "Content-Type": "application/json" if body.startswith(b"{") else "application/x-www-form-urlencoded"},+ content=body,+ )+ response = (+ httpx.Response(500, request=request, content=response_body)+ if response_body is not None+ else httpx.Response(500, request=request, stream=httpx.ByteStream(b'{"error":"boom"}'))+ )+ return httpx.HTTPStatusError("500", request=request, response=response)++ def test_includes_method_url_status_and_request_body(self):+ exc = self._status_error(+ body=b'{"method":"initialize","jsonrpc":"2.0","id":0}',+ response_body=b'{"error":"boom"}',+ )+ described = describe_upstream_http_failure(exc)+ assert described is not None+ assert "POST https://upstream.example/apis/mcp -> HTTP 500" in described+ assert '{"method":"initialize"' in described+ assert 'response body: {"error":"boom"}' in described++ def test_masks_authorization_header_and_secret_body_fields(self):+ exc = self._status_error(+ body=b"grant_type=client_credentials&client_id=abc&client_secret=super-secret-value-1234",+ response_body=b"{}",+ )+ described = describe_upstream_http_failure(exc)+ assert described is not None+ assert "secret-token-abcdef0123456789" not in described+ assert "super-secret-value-1234" not in described+ assert "client_id=abc" in described+ assert "client_secret=" in described++ def test_reports_unread_streamed_response_body(self):+ described = describe_upstream_http_failure(self._status_error(body=b"{}"))+ assert described is not None+ assert "response body: (not read)" in described++ def test_finds_response_behind_cause_chain(self):+ wrapper = RuntimeError("token minting failed")+ wrapper.__cause__ = self._status_error(body=b"{}", response_body=b'{"error":"invalid_client"}')+ described = describe_upstream_http_failure(wrapper)+ assert described is not None+ assert "invalid_client" in described++ def test_returns_none_without_http_response(self):+ assert describe_upstream_http_failure(ConnectionError("refused")) is None++[email protected]("body", [+ b'{"password":"first second","token":"demo-secret"}',+ b'{"nested":[{"access_token":"first,second"}]}',+ b'client%5Fsecret=first+second&token=demo-secret',+])+def test_failure_log_fully_redacts_structured_secrets(body):+ request = httpx.Request("POST", "https://upstream/mcp?credential=query-secret",+ headers={"X-Custom-Credential": "custom-secret"}, content=body)+ response = httpx.Response(500, request=request, content=body)+ detail = describe_upstream_http_failure(httpx.HTTPStatusError("failure", request=request, response=response))+ assert detail is not None+ for secret in ("first", "second", "demo-secret", "custom-secret", "query-secret"):+ assert secret not in detail+++def test_failure_log_omits_unstructured_body():+ request = httpx.Request("POST", "https://upstream/mcp", content=b"arbitrary-secret")+ response = httpx.Response(500, request=request, content=b"<html>arbitrary-secret</html>")+ detail = describe_upstream_http_failure(httpx.HTTPStatusError("failure", request=request, response=response))+ assert detail is not None+ assert "arbitrary-secret" not in detail+ assert "omitted" in detail++[email protected]("mode", ["error", "large", "timeout", "read_failure", "success", "cancel"])+async def test_error_capture_is_bounded_and_preserves_success_and_cancellation(mode):+ from litellm.proxy._experimental.mcp_server.mcp_debug import capture_upstream_error_response++ class Stream(httpx.AsyncByteStream):+ def __init__(self):+ self.reads = 0++ async def __aiter__(self):+ self.reads += 1+ if mode == "timeout":+ await asyncio.sleep(10)+ if mode == "read_failure":+ raise httpx.ReadError("private-read-error")+ if mode == "cancel":+ raise asyncio.CancelledError+ yield b'{"error":"missing_scope","password":"first second"}' if mode != "large" else b"x" * 20000++ stream = Stream()+ request = httpx.Request("POST", "https://upstream/mcp")+ response = httpx.Response(200 if mode == "success" else 500, request=request, stream=stream)+ if mode == "cancel":+ with pytest.raises(asyncio.CancelledError):+ await capture_upstream_error_response(response)+ return+ await capture_upstream_error_response(response)+ if mode == "success":+ assert stream.reads == 0+ assert await response.aread() == b'{"error":"missing_scope","password":"first second"}'+ return+ detail = describe_upstream_http_failure(httpx.HTTPStatusError("failure", request=request, response=response))+ assert detail is not None+ assert "first" not in detail and "second" not in detail and "private-read-error" not in detail+ expected = {"error": "missing_scope", "large": "capture limit", "timeout": "read failed", "read_failure": "read failed"}+ assert expected[mode] in detail+ if mode == "error":+ assert await response.aread() == b'{"error":"missing_scope","password":"first second"}'++[email protected]("body", [b"", b'"scalar"', b'{"hint":"line1\\nline2"}', b'{"hint":"' + b'x' * 600 + b'"}'])+def test_failure_preview_handles_empty_scalar_control_and_long_bodies(body):+ request = httpx.Request("POST", "https://user:secret@upstream/mcp?key=private#private", content=body)+ response = httpx.Response(500, request=request, content=body)+ detail = describe_upstream_http_failure(httpx.HTTPStatusError("failure", request=request, response=response))+ assert detail is not None+ assert "private" not in detail and "user:secret" not in detail and "\n" not in detail+ if not body:+ assert "(empty)" in detail+ elif body.startswith(b'"'):+ assert "omitted" in detail+ elif len(body) > 512:+ assert "truncated" in detail and len(detail) < 1300+ else:+ assert "line1\\nline2" in detail+++async def test_error_capture_preserves_httpx_auth_retry():+ from litellm.proxy._experimental.mcp_server.mcp_debug import capture_upstream_error_response++ class RetryAuth(httpx.Auth):+ def auth_flow(self, request):+ response = yield request+ if response.status_code == 401:+ request.headers["Authorization"] = "Bearer refreshed"+ yield request++ def upstream(request):+ if request.headers.get("Authorization"):+ return httpx.Response(200, json={"ok": True})+ return httpx.Response(401, json={"error":"expired_token"})++ async with httpx.AsyncClient(transport=httpx.MockTransport(upstream), auth=RetryAuth(),+ event_hooks={"response":[capture_upstream_error_response]}) as client:+ response = await client.get("https://upstream/mcp")+ assert response.status_code == 200 and response.json() == {"ok":True}+ assert response.history[0].json() == {"error":"expired_token"}+++def test_failure_diagnostics_without_request_and_with_streamed_request():+ response = httpx.Response(503)+ exc = httpx.HTTPStatusError("failed", request=httpx.Request("GET", "https://upstream"), response=response)+ assert describe_upstream_http_failure(exc) == "HTTP 503 | request unavailable"+ request = httpx.Request("POST", "https://upstream", content=iter((b"private-body",)))+ response = httpx.Response(503, request=request)+ described = describe_upstream_http_failure(httpx.HTTPStatusError("failed", request=request, response=response))+ assert described is not None and "streamed, not captured" in described and "private-body" not in described++++def test_deep_error_body_is_bounded_without_exposing_nested_values():+ import json+ body = b'{"nested":' * 18 + b'{"password":"hidden-value"}' + b'}' * 18+ request = httpx.Request("POST", "https://upstream/mcp", content=body)+ response = httpx.Response(500, request=request, content=body)+ detail = describe_upstream_http_failure(httpx.HTTPStatusError("failure", request=request, response=response))+ assert detail is not None and "depth limit" in detail and "hidden-value" not in detail+ assert json.loads(detail.split("response body: ")[1])["nested"]++[email protected]("body", [b'client%5Fsecret=first+second&client_id=visible', b'client_secret=first%26second&client_id=visible'])+def test_encoded_form_credentials_are_decoded_before_redaction(body):+ request = httpx.Request("POST", "https://upstream/token", content=body,+ headers={"Content-Type":"application/x-www-form-urlencoded"})+ response = httpx.Response(400, request=request, content=body,+ headers={"Content-Type":"application/x-www-form-urlencoded"})+ detail = describe_upstream_http_failure(httpx.HTTPStatusError("failure", request=request, response=response))+ assert detail is not None and "client_id=visible" in detail+ assert "first" not in detail and "second" not in detail+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("source", tuple(AuthResolution))+ @pytest.mark.parametrize("method", ("GET", "DELETE", "POST"))+ async def test_debug_defers_resolution_until_first_frame_only_for_post(source: AuthResolution, method: str) -> None:+ captured: Final[list[Message]] = []+ diagnostics: Final = MCPAuthDiagnostics()++ async def send(message: Message) -> None:+ captured.append(message)++ wrapped: Final = MCPDebug.wrap_send_with_debug_headers(+ send, diagnostics.headers(), diagnostics.headers, request_method=method+ )+ await wrapped({"type": "http.response.start", "status": 200, "headers": []})+ assert len(captured) == (0 if method == "POST" else 1)+ diagnostics.record("s1", source)+ body: Final[Message] = {"type": "http.response.body", "body": b"data: pong\n\n", "more_body": True}+ await wrapped(body)+ assert dict(captured[0]["headers"])[b"x-mcp-debug-auth-resolution"] == (+ source.value.encode() if method == "POST" else b"unresolved"+ )+ assert captured[1] == body+++ @pytest.mark.asyncio+ async def test_early_stream_frame_reports_unresolved_without_waiting() -> None:+ captured: Final[list[Message]] = []+ diagnostics: Final = MCPAuthDiagnostics()++ async def send(message: Message) -> None:+ captured.append(message)++ wrapped: Final = MCPDebug.wrap_send_with_debug_headers(send, {}, diagnostics.headers, request_method="POST")+ await wrapped({"type": "http.response.start", "status": 200, "headers": []})+ await wrapped({"type": "http.response.body", "body": b": ping\n\n", "more_body": True})+ diagnostics.record("s1", AuthResolution.stored_user_token)+ await wrapped({"type": "http.response.body", "body": b"data: pong\n\n", "more_body": False})+ assert len(captured) == 3+ assert dict(captured[0]["headers"])[b"x-mcp-debug-auth-resolution"] == b"unresolved"+++ def test_diagnostics_keep_requests_separate_and_do_not_collapse_multiple_servers() -> None:+ alice: Final = MCPAuthDiagnostics()+ bob: Final = MCPAuthDiagnostics()+ alice.record("s1", AuthResolution.stored_user_token)+ assert bob.resolution() == "unresolved"+ alice.record("s1", AuthResolution.token_exchange)+ assert alice.resolution() == "token-exchange"+ alice.record("s2", AuthResolution.static_token)+ assert alice.resolution() == "multiple"+ assert alice.headers()["x-mcp-debug-auth-resolutions"] == '{"s1":"token-exchange","s2":"static-token"}'+++ @pytest.mark.asyncio+ async def test_concurrent_mcp_messages_record_on_their_own_http_scope() -> None:+ from unittest.mock import MagicMock++ from mcp.server.lowlevel.server import request_ctx+ from mcp.shared.context import RequestContext+ from starlette.requests import Request++ from litellm.proxy._experimental.mcp_server.mcp_debug import (+ MCP_AUTH_DIAGNOSTICS_SCOPE_KEY,+ record_auth_resolution,+ )++ session: Final = MagicMock()+ first: Final = MCPAuthDiagnostics()+ second: Final = MCPAuthDiagnostics()++ async def record(diagnostics: MCPAuthDiagnostics, source: AuthResolution) -> None:+ context: Final = RequestContext(+ request_id=1, meta=None, session=session, lifespan_context=None,+ request=Request({"type": "http", MCP_AUTH_DIAGNOSTICS_SCOPE_KEY: diagnostics}),+ )+ token: Final = request_ctx.set(context)+ try:+ await asyncio.sleep(0)+ record_auth_resolution("same-server", source)+ finally:+ request_ctx.reset(token)++ await asyncio.gather(record(first, AuthResolution.stored_user_token), record(second, AuthResolution.per_request_header))+ assert first.resolution() == "stored-user-token"+ assert second.resolution() == "per-request-header"