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): exclude gateway credentials from guardrail bearers (#45897)
joshua-berri541e3ed5305a
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.pyindex 2c4c942ebeb..18b7c279606 100644--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py@@ -1546,6 +1546,31 @@ class MCPRequestHandler:authorization: Final = next((value for key, value in headers.items() if key.lower() == "authorization"), "")return SecretStr(authorization[len("bearer ") :]) if authorization.lower().startswith("bearer ") else None+ @staticmethod+ def get_guardrail_bearer_token(headers: Headers, auth: UserAPIKeyAuth) -> SecretStr | None:+ from litellm.proxy._experimental.mcp_server.utils import (+ _custom_litellm_key_header_name, # pyright: ignore[reportPrivateUsage] # reuse the shared credential-header setting+ )++ bearer: Final = MCPRequestHandler.get_incoming_bearer_token(headers)+ if bearer is None:+ return None+ value: Final = bearer.get_secret_value()+ if MCPRequestHandler._is_gateway_admission_credential(value):+ return None+ if MCPRequestHandler._is_caller_admission_key(+ value, auth.api_key+ ) or MCPRequestHandler._is_caller_admission_key(hash_token(value), auth.api_key):+ return None+ admitted_credential: Final = MCPRequestHandler.caller_admission_credential(+ headers,+ auth,+ custom_key_header_name=_custom_litellm_key_header_name(),+ )+ if not auth.jwt_claims and MCPRequestHandler._is_caller_admission_key(value, admitted_credential):+ return None+ return bearer+@staticmethoddef get_oauth2_headers_from_headers(headers: Headers) -> dict[str, str]:"""diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.pyindex 38f526bcd13..38d9ca52abb 100644--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py@@ -412,7 +412,7 @@ if MCP_AVAILABLE:raw_headers=virtual_raw_headers,litellm_logging_obj=virtual_logging_obj,guardrail_context=MCPRequestContext.resolve_guardrail_context(virtual_data),- incoming_bearer_token=MCPRequestHandler.get_incoming_bearer_token(request.headers),+ incoming_bearer_token=MCPRequestHandler.get_guardrail_bearer_token(request.headers, user_api_key_dict),)except Exception as e:virtual_request_data: Final = virtual_processor.data@@ -1346,7 +1346,9 @@ if MCP_AVAILABLE:litellm_logging_obj=data.get("litellm_logging_obj"),guardrail_context=MCPRequestContext.resolve_guardrail_context(data),requested_server_id=canonical_server_id,- incoming_bearer_token=MCPRequestHandler.get_incoming_bearer_token(request.headers),+ incoming_bearer_token=MCPRequestHandler.get_guardrail_bearer_token(+ request.headers, user_api_key_dict+ ),)result: Final = complete_call_tool_result(executed, WireCompat.LEGACY)except Exception as e:diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex d299f470f12..1916a19a2c4 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -855,7 +855,7 @@ if MCP_AVAILABLE:wire_compat_for(ctx.protocol_version),ctx.protocol_version,incoming_bearer_token=(- MCPRequestHandler.get_incoming_bearer_token(request.headers)+ MCPRequestHandler.get_guardrail_bearer_token(request.headers, auth)if isinstance(request, StarletteRequest)else None),diff --git a/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.pyindex 9f717f522c0..6254b1bc44c 100644--- a/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py+++ b/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py@@ -10814,3 +10814,39 @@ async def test_admission_request_body_serves_stashed_peek_callable():{"type": "http", "method": "POST", "path": "/mcp", "headers": []})assert await without_peek.body() == b"{}"++[email protected]("bearer,api_key,claims,explicit_key,expected", [+ (None, "sk-key", None, None, None),+ ("sk-key", "sk-key", None, None, None),+ ("sk-key", "sk-key", {"sub": "previous-jwt"}, "sk-key", None),+ ("caller.jwt.assertion", "sk-key", {"sub": "caller"}, None, "caller.jwt.assertion"),+ ("caller.jwt.assertion", None, {"sub": "caller"}, None, "caller.jwt.assertion"),+ ("upstream", "sk-key", None, "sk-key", "upstream"),+ ("llm_session_test", None, {"sub": "caller"}, None, None),+ ("llm_srefresh_test", None, {"sub": "caller"}, None, None),+ ("opaque-master", "litellm_proxy_master_key", None, None, None),+])+def test_guardrail_bearer_preserves_identity_without_exposing_gateway_credentials(+ bearer: str | None, api_key: str | None, claims: dict[str, str] | None,+ explicit_key: str | None, expected: str | None,+) -> None:+ headers: Final = Headers({+ **({"Authorization": f"Bearer {bearer}"} if bearer is not None else {}),+ **({"x-litellm-api-key": explicit_key} if explicit_key else {}),+ })+ token: Final = MCPRequestHandler.get_guardrail_bearer_token(+ headers, UserAPIKeyAuth(api_key=api_key, jwt_claims=claims),+ )+ assert (token.get_secret_value() if token is not None else None) == expected+++def test_guardrail_bearer_respects_custom_admission_header(monkeypatch: pytest.MonkeyPatch) -> None:+ from litellm.proxy.proxy_server import general_settings++ monkeypatch.setitem(general_settings, "litellm_key_header_name", "x-gateway-key")+ token: Final = MCPRequestHandler.get_guardrail_bearer_token(+ Headers({"x-gateway-key": "opaque-master", "authorization": "Bearer opaque-master"}),+ UserAPIKeyAuth(api_key="litellm_proxy_master_key"),+ )+ assert token is Nonediff --git a/tests/unit/proxy/_experimental/mcp_server/test_operations.py b/tests/unit/proxy/_experimental/mcp_server/test_operations.pyindex 32a7c3fbe58..dcc4eb1a570 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_operations.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_operations.py@@ -71,7 +71,7 @@ async def test_mapped_caller_bearer_reaches_agent_evaluation("headers": [] if verdict == "missing" else [(b"authorization", f"Bearer {bearer}".encode())],})auth: Final = UserAPIKeyAuth(- api_key="stored-key-hash", user_id="mapped-caller",+ api_key="stored-key-hash", user_id="mapped-caller", jwt_claims={"sub": "mapped-caller"},object_permission={"object_permission_id": "mapped", "mcp_servers": ["guarded"], "mcp_tool_search_enabled": mode == "virtual"},)oauth, raw, _, _ = MCPRequestHandler.scrub_gateway_admission_credentials(@@ -1552,3 +1552,41 @@ def test_discovery_extra_headers_exclude_gateway_admission_key(header_name: str)assert auth_header is Noneassert extra_headers == {"X-Tenant": "tenant-control"}assert raw_headers == {"x-litellm-api-key": caller_key, "x-tenant": "tenant-control"}++[email protected]("request_kind", ["absent", "non_starlette", "without_bearer", "admission_key"])+async def test_guardrail_context_never_recovers_a_previous_request_bearer(+ _mcp_request_ctx: Callable[..., ServerRequestContext], request_kind: str, monkeypatch: pytest.MonkeyPatch,+) -> None:+ from mcp.server.auth.middleware.auth_context import auth_context_var+ from starlette.requests import Request+ from litellm.proxy._experimental.mcp_server import server as gateway++ request: Final = (+ None if request_kind == "absent" else object() if request_kind == "non_starlette" else Request({+ "type": "http", "method": "POST", "path": "/mcp",+ "headers": [(b"authorization", b"Bearer sk-current-key")] if request_kind == "admission_key" else [],+ })+ )+ previous: Final = auth_context_var.set(None)+ try:+ gateway.set_auth_context(+ UserAPIKeyAuth(api_key="sk-current-key"),+ raw_headers={"authorization": "Bearer previous.caller.assertion"},+ )+ capture: Final = _CatalogHookCapture()+ monkeypatch.setattr(litellm, "callbacks", [capture])+ async with gateway._legacy_operation_context(_mcp_request_ctx(request=request), trace=False) as context:+ await operations.global_mcp_server_manager.pre_call_tool_check(+ name="echo", arguments={}, server_name="guarded",+ user_api_key_auth=context.user_api_key_auth,+ proxy_logging_obj=ProxyLogging(user_api_key_cache=UserApiKeyCache()),+ server=MCPServer(server_id="guarded", name="guarded", transport=MCPTransport.http, allow_all_keys=True),+ raw_headers=dict(context.raw_headers or {}),+ incoming_bearer_token=context.incoming_bearer_token,+ )+ assert capture.data is not None+ assert capture.data["incoming_bearer_token"] is None+ finally:+ auth_context_var.reset(previous)diff --git a/tests/unit/proxy/_experimental/mcp_server/test_rest_endpoints.py b/tests/unit/proxy/_experimental/mcp_server/test_rest_endpoints.pyindex fc61ec66b30..2a04c8cda2a 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_rest_endpoints.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_rest_endpoints.py@@ -4862,3 +4862,70 @@ async def test_saved_preview_protocol_omission_and_explicit_edits(assert result == {"protocol_version": expected}assert saved.protocol_version == "2025-11-25"assert payload.mcp_info == metadata++[email protected]("virtual", [False, True])[email protected]("bearer,claims,expected", [+ ("sk-guardrail-admission", None, None),+ ("caller.jwt.assertion", {"sub": "caller"}, "caller.jwt.assertion"),+ ("upstream-token", None, "upstream-token"),+])+async def test_rest_guardrail_bearer_excludes_admission_key(+ monkeypatch: pytest.MonkeyPatch, virtual: bool,+ bearer: str, claims: dict[str, str] | None, expected: str | None,+) -> None:+ import litellm+ from litellm.caching.dual_cache import DualCache+ from litellm.integrations.custom_logger import CustomLogger+ from litellm.proxy._experimental.mcp_server.tool_registry import global_mcp_tool_registry++ observed: Final[asyncio.Queue[object]] = asyncio.Queue()++ class CaptureBearer(CustomLogger):+ async def async_pre_call_hook(+ self, user_api_key_dict: UserAPIKeyAuth, cache: DualCache,+ data: dict[str, object], call_type: str,+ ) -> None:+ if call_type == "call_mcp_tool" and "incoming_bearer_token" in data:+ observed.put_nowait(data["incoming_bearer_token"])++ async def echo() -> str:+ return "guarded-result"++ auth: Final = UserAPIKeyAuth(+ api_key="sk-guardrail-admission", jwt_claims=claims,+ object_permission={"object_permission_id": "guarded", "mcp_servers": ["guarded"], "mcp_tool_search_enabled": virtual},+ )+ managed: Final = MCPServer(+ server_id="guarded", name="guarded", transport=MCPTransport.http,+ spec_path="/catalog.yaml", allow_all_keys=True,+ )+ monkeypatch.setitem(rest_endpoints.global_mcp_server_manager.registry, managed.server_id, managed)+ monkeypatch.setattr(litellm, "callbacks", [CaptureBearer()])+ global_mcp_tool_registry.register_tool(+ name="guarded-echo", description="Echo", input_schema={"type": "object"}, handler=echo,+ )+ headers: Final = {"authorization": f"Bearer {bearer}", **(+ {} if claims else {"x-litellm-api-key": "sk-guardrail-admission"}+ )}+ payload: Final = {+ "server_id": "guarded", "name": "mcp_tool_call" if virtual else "guarded-echo",+ "arguments": {"tool_name": "guarded-echo", "arguments": {}} if virtual else {},+ }+ try:+ result: Final = await rest_endpoints.call_tool_rest_api(+ _build_request(headers, path="/mcp-rest/tools/call", json_body=payload),+ user_api_key_dict=auth,+ )+ assert result.is_error is False+ assert observed.qsize() == 1+ assert observed.get_nowait() == expected+ if claims is None:+ list_headers: Final = rest_endpoints._extract_mcp_headers_from_request(+ _build_request(headers), auth,+ )[2]+ authorization: Final = list_headers.get("authorization", "")+ assert (authorization.removeprefix("Bearer ") or None) == expected+ finally:+ global_mcp_tool_registry.unregister_tools_with_prefix("guarded-")