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): attach resolved OAuth credentials to OpenAPI spec_path tool calls
Tin Chi Lo48572c9516ab
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 8f30071eb5d..3e591083ba2 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -610,6 +610,34 @@ def _passthrough_token_from_mcp_auth_header(return None+async def _materialize_auth_headers(auth: httpx.Auth | None) -> dict[str, str] | None:+ """Extract the header a resolved ``httpx.Auth`` would set, as a plain dict, or None.++ OpenAPI tool closures egress through ``AsyncHTTPHandler`` methods that accept headers but no+ ``auth``, so a resolved credential must be materialized into a header value. Driving one step+ of the auth's own flow (against a throwaway request that is never sent) keeps this generic+ across every auth shape without per-class branching; ``header_name`` is the resolver-arm+ convention for "this auth sets a header" (``NoOpAuth`` has none and yields nothing to apply).+ The materialized value is point-in-time: flow behaviors past the first request, like the M2M+ one-shot 401 refetch, do not apply on this arm.+ """+ if auth is None:+ return None+ header_name = getattr(auth, "header_name", None)+ if not isinstance(header_name, str) or not header_name:+ return None+ probe = httpx.Request("GET", "http://localhost/")+ flow = auth.async_auth_flow(probe)+ try:+ first_request = await flow.__anext__()+ except StopAsyncIteration:+ return None+ finally:+ await flow.aclose()+ header_value = first_request.headers.get(header_name)+ return {header_name: header_value} if header_value else None++def _consumes_caller_authorization(server: MCPServer) -> bool:"""True when this server's egress forwards the caller's request-wide ``Authorization`` upstream:the client-forwarded token modes, legacy OAuth pass-through, and legacy upstream-delegated@@ -4705,6 +4733,54 @@ class MCPServerManager:)return oauth2_headers+ async def resolve_openapi_upstream_auth(+ self,+ *,+ mcp_server: MCPServer,+ oauth2_headers: dict[str, str] | None,+ raw_headers: dict[str, str] | None,+ mcp_auth_header: str | dict[str, str] | None,+ user_api_key_auth: UserAPIKeyAuth | None,+ forwarded_headers: dict[str, str] | None,+ ) -> tuple[dict[str, str] | None, dict[str, str] | None]:+ """Resolve the gateway-owned upstream credential for a spec_path (OpenAPI) tool call.++ OpenAPI tools egress through a plain httpx call assembled from ContextVars, never through+ ``_create_mcp_client``, so the v2 resolver graft there does not run for them and a resolved+ credential (authorization_code's stored per-user token, client_credentials' minted M2M+ token, token_exchange's exchanged token, passthrough's forwarded caller token) must be+ materialized into headers here. Returns ``(resolved_auth_headers, forwarded_headers)``:+ the resolved headers are authoritative over every other Authorization source (the same+ rule ``_resolve_v2_auth`` applies on the MCPClient path) and ``forwarded_headers`` comes+ back with any header the resolver claimed already dropped. Unmigrated (v1) servers resolve+ through the stored-token lookup instead, and a missing per-user credential raises the same+ discovery challenge the MCPClient path serves, rather than egressing unauthenticated.+ """+ spec = to_server_spec(mcp_server)+ if spec is None:+ stored_headers = await self._resolve_oauth2_headers_for_tool_call(+ mcp_server, oauth2_headers, user_api_key_auth+ )+ return stored_headers, forwarded_headers++ subject_token: str | None = None+ if isinstance(spec.config, (TokenExchangeConfig, IdJagConfig)):+ subject_token = self._extract_bearer_token(oauth2_headers, raw_headers)+ elif isinstance(spec.config, PassthroughConfig):+ inbound_token, forwarded_headers = _take_forwarded_authorization(forwarded_headers)+ per_server_token = _passthrough_token_from_mcp_auth_header(mcp_auth_header)+ subject_token = per_server_token if per_server_token is not None else inbound_token++ resolved_auth, forwarded_headers = await self._resolve_v2_auth(+ server=mcp_server,+ spec=spec,+ provider=self._cred_provider,+ subject_token=subject_token,+ user_api_key_auth=user_api_key_auth,+ extra_headers=forwarded_headers,+ )+ return await _materialize_auth_headers(resolved_auth), forwarded_headers+async def _gather_openapi_tool_tasks(self,tasks: list[Any],@@ -4813,22 +4889,32 @@ class MCPServerManager:auth_header_value = (_format_byok_openapi_auth_header(mcp_server, mcp_auth_header) if mcp_auth_header else None)- forwarded_headers = _openapi_forwarded_extra_headers(mcp_server, raw_headers, user_api_key_auth)+ resolved_auth_headers, forwarded_headers = await self.resolve_openapi_upstream_auth(+ mcp_server=mcp_server,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ mcp_auth_header=mcp_auth_header,+ user_api_key_auth=user_api_key_auth,+ forwarded_headers=_openapi_forwarded_extra_headers(mcp_server, raw_headers, user_api_key_auth),+ )async def _call_openapi_via_handler():from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (_request_auth_header,_request_extra_headers,+ _request_resolved_auth_headers,)auth_token = _request_auth_header.set(auth_header_value)extra_token = _request_extra_headers.set(forwarded_headers)+ resolved_token = _request_resolved_auth_headers.set(resolved_auth_headers)try:async with self._limit_outbound_concurrency(mcp_server):return await self._call_openapi_tool_handler(mcp_server, name, arguments)finally:_request_auth_header.reset(auth_token)_request_extra_headers.reset(extra_token)+ _request_resolved_auth_headers.reset(resolved_token)tasks.append(asyncio.create_task(_call_openapi_via_handler()))else:diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.pyindex 1ee300be718..0b795057837 100644--- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py+++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py@@ -62,6 +62,14 @@ _request_extra_headers: contextvars.ContextVar[Optional[Dict[str, str]]] = conte"_request_extra_headers", default=None)+# Per-request headers carrying the gateway-resolved upstream credential+# (stored per-user OAuth token, minted M2M token, exchanged OBO token).+# Set from MCPServerManager.resolve_openapi_upstream_auth; authoritative+# over every other Authorization source in _merge_openapi_tool_request_headers.+_request_resolved_auth_headers: contextvars.ContextVar[dict[str, str] | None] = contextvars.ContextVar(+ "_request_resolved_auth_headers", default=None+)+def _sanitize_path_parameter_value(param_value: Any, param_name: str) -> str:"""Ensure path params cannot introduce directory traversal."""@@ -294,10 +302,15 @@ def _merge_openapi_tool_request_headers("""Merge static closure headers with per-request ContextVar overrides.Precedence (highest to lowest):- 1. ``_request_auth_header`` — BYOK override of ``Authorization``- 2. ``static_headers`` — operator-configured headers baked into the+ 1. ``_request_resolved_auth_headers`` — the gateway-resolved upstream+ credential (stored per-user OAuth token, minted M2M token,+ exchanged OBO token). The resolver is authoritative: a BYOK or+ forwarded ``Authorization`` must not shadow it, mirroring+ ``_resolve_v2_auth`` on the MCPClient path+ 2. ``_request_auth_header`` — BYOK override of ``Authorization``+ 3. ``static_headers`` — operator-configured headers baked into thetool closure at registration time- 3. ``_request_extra_headers`` — per-request headers forwarded from+ 4. ``_request_extra_headers`` — per-request headers forwarded fromthe MCP caller (allowlisted by ``MCPServer.extra_headers``)This matches the existing MCP invariant in@@ -323,6 +336,12 @@ def _merge_openapi_tool_request_headers(del effective_headers[existing]effective_headers["Authorization"] = override_auth+ resolved_auth_headers = _request_resolved_auth_headers.get() or {}+ for name, value in resolved_auth_headers.items():+ for existing in [k for k in effective_headers if k.lower() == name.lower()]:+ del effective_headers[existing]+ effective_headers[name] = value+return effective_headersdiff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex a8ab0937124..75faca3c914 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -376,6 +376,7 @@ if MCP_AVAILABLE:from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (_request_auth_header,_request_extra_headers,+ _request_resolved_auth_headers,)from litellm.proxy._experimental.mcp_server.sse_transport import SseServerTransportfrom litellm.proxy._experimental.mcp_server.tool_registry import (@@ -2785,13 +2786,26 @@ if MCP_AVAILABLE:forwarded_headers = {}forwarded_headers[header_name] = value+ resolved_auth_headers: dict[str, str] | None = None+ if mcp_server:+ resolved_auth_headers, forwarded_headers = await global_mcp_server_manager.resolve_openapi_upstream_auth(+ mcp_server=mcp_server,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ mcp_auth_header=mcp_auth_header,+ user_api_key_auth=user_api_key_auth,+ forwarded_headers=forwarded_headers,+ )+_auth_token = _request_auth_header.set(auth_header_value)_extra_token = _request_extra_headers.set(forwarded_headers)+ _resolved_token = _request_resolved_auth_headers.set(resolved_auth_headers)try:local_content = await _handle_local_mcp_tool(name, arguments)finally:_request_auth_header.reset(_auth_token)_request_extra_headers.reset(_extra_token)+ _request_resolved_auth_headers.reset(_resolved_token)response = CallToolResult(content=cast(Any, local_content), isError=False)# Try managed MCP server tool (pass the full prefixed name)diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.pyindex 73486fe0b6a..ca5b7914cca 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_hook_extra_headers.py@@ -1033,3 +1033,89 @@ class TestResolveByokMcpAuthHeader:check_mock.assert_awaited_once_with(server, user_auth)assert result == "caller-header"+++class TestOpenApiResolvedUpstreamAuth:+ """LIT-4629: spec_path servers egress through plain httpx, so the manager's OpenAPI arm must+ materialize the v2-resolved credential into the `_request_resolved_auth_headers` ContextVar;+ before the fix the resolved token never reached the upstream API."""++ def _oauth_server(self, **overrides: Any) -> MCPServer:+ fields: Dict[str, Any] = dict(+ server_id="srv-sheets",+ name="google_sheets",+ server_name="google_sheets",+ url=None,+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2,+ spec_path="https://example.com/sheets-openapi.yaml",+ )+ fields.update(overrides)+ return MCPServer(**fields)++ @pytest.mark.asyncio+ async def test_call_tool_openapi_injects_v2_resolved_token_contextvar(self):+ """The managed spec_path arm resolves the v2 credential and sets the ContextVar; kills+ the mutant that drops the resolve_openapi_upstream_auth call in call_tool."""+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (+ _request_resolved_auth_headers,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (+ StaticHeaderAuth,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok++ manager = MCPServerManager()+ server = self._oauth_server()+ user_auth = UserAPIKeyAuth(user_id="alice", api_key="sk-user")+ captured: Dict[str, Any] = {}++ async def fake_openapi_handler(_server, _name, _arguments):+ captured["resolved"] = _request_resolved_auth_headers.get()+ return MagicMock()++ with patch.object(manager, "_resolve_mcp_server_for_tool_call", return_value=server):+ with patch.object(+ manager._cred_provider,+ "resolve_credentials",+ new=AsyncMock(return_value=Ok(StaticHeaderAuth("Bearer stored-user-token"))),+ ):+ with patch.object(manager, "_call_openapi_tool_handler", side_effect=fake_openapi_handler):+ await manager.call_tool(+ server_name=server.server_name,+ name="get_values",+ arguments={},+ user_api_key_auth=user_auth,+ )++ assert captured["resolved"] == {"Authorization": "Bearer stored-user-token"}+ assert _request_resolved_auth_headers.get() is None++ @pytest.mark.asyncio+ async def test_call_tool_openapi_m2m_missing_token_url_fails_closed(self):+ """A url-less M2M spec server with no token_url must fail with a typed error instead of+ egressing unauthenticated (the pre-#32259 silent failure this arm previously preserved).+ Drives the real adapter/resolver chain: ClientCredentialsConfig with missing grant fields+ resolves to a misconfigured CredError, raised as an HTTPException."""+ from fastapi import HTTPException++ manager = MCPServerManager()+ server = self._oauth_server(+ oauth2_flow="client_credentials",+ client_id="m2m-client",+ client_secret="m2m-secret",+ token_url=None,+ )+ called = AsyncMock()++ with patch.object(manager, "_resolve_mcp_server_for_tool_call", return_value=server):+ with patch.object(manager, "_call_openapi_tool_handler", new=called):+ with pytest.raises(HTTPException):+ await manager.call_tool(+ server_name=server.server_name,+ name="get_values",+ arguments={},+ user_api_key_auth=UserAPIKeyAuth(user_id="alice", api_key="sk-user"),+ )++ called.assert_not_awaited()diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.pyindex 03f91260955..576b9f4f139 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py@@ -8891,3 +8891,48 @@ async def test_resolve_toolset_tool_permissions_single_db_fetch_across_checks():assert first == {"server-a": ["lookup_status"]}assert second == firstlist_toolsets_mock.assert_awaited_once()+++class TestMaterializeAuthHeaders:+ """_materialize_auth_headers drives one step of a resolved httpx.Auth's own flow to turn it+ into a header dict for the OpenAPI egress arm, which sends plain headers and cannot carry an+ httpx.Auth. Generic across auth shapes via the resolver-arm header_name convention."""++ @pytest.mark.asyncio+ async def test_static_header_auth_materializes_its_header(self):+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ _materialize_auth_headers,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (+ StaticHeaderAuth,+ )++ headers = await _materialize_auth_headers(StaticHeaderAuth("Bearer stored-token"))+ assert headers == {"Authorization": "Bearer stored-token"}++ @pytest.mark.asyncio+ async def test_client_credentials_bearer_auth_materializes_bearer(self):+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ _materialize_auth_headers,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.client_credentials import (+ ClientCredentialsBearerAuth,+ )++ async def _refetch(_stale: str):+ return None++ headers = await _materialize_auth_headers(ClientCredentialsBearerAuth("m2m-token", _refetch))+ assert headers == {"Authorization": "Bearer m2m-token"}++ @pytest.mark.asyncio+ async def test_noop_and_none_materialize_to_none(self):+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ _materialize_auth_headers,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (+ NoOpAuth,+ )++ assert await _materialize_auth_headers(None) is None+ assert await _materialize_auth_headers(NoOpAuth()) is Nonediff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.pyindex 39f3c767220..7bcacb3ff4a 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py@@ -17,6 +17,7 @@ import pytestfrom litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (_request_auth_header,_request_extra_headers,+ _request_resolved_auth_headers,_resolve_param_list,_resolve_ref,build_input_schema,@@ -1207,3 +1208,61 @@ class TestRequestExtraHeaders:call_args = async_client.get.call_argsheaders_sent = call_args[1]["headers"]assert "X-TOKEN" not in headers_sent++ @pytest.mark.asyncio+ async def test_resolved_auth_headers_win_over_every_other_authorization_source(self):+ """The gateway-resolved credential (stored per-user OAuth / minted M2M token) is+ authoritative: it must override the BYOK override, static headers, and forwarded caller+ headers on the Authorization name, case-insensitively, mirroring _resolve_v2_auth's rule+ on the MCPClient path. Without this, a spec_path oauth2 server's completed OAuth flow+ stores a token that never reaches the upstream API (LIT-4629)."""+ operation = {}+ func = create_tool_function(+ path="/secure",+ method="get",+ operation=operation,+ base_url="https://api.example.com",+ headers={"authorization": "Bearer static-operator"},+ )++ with patch(GET_ASYNC_CLIENT_TARGET) as mock_client:+ async_client = _create_mock_client("get", "secure-data")+ mock_client.return_value = async_client++ extra_token = _request_extra_headers.set({"Authorization": "Bearer caller-forwarded"})+ auth_token = _request_auth_header.set("Bearer byok-credential")+ resolved_token = _request_resolved_auth_headers.set({"Authorization": "Bearer resolved-oauth"})+ try:+ result = await func()+ finally:+ _request_auth_header.reset(auth_token)+ _request_extra_headers.reset(extra_token)+ _request_resolved_auth_headers.reset(resolved_token)++ assert result == "secure-data"+ headers_sent = async_client.get.call_args[1]["headers"]+ authorization_values = [v for k, v in headers_sent.items() if k.lower() == "authorization"]+ assert authorization_values == ["Bearer resolved-oauth"]++ @pytest.mark.asyncio+ async def test_resolved_auth_headers_not_leaked_between_calls(self):+ """After resetting the resolved-auth ContextVar, subsequent calls send no credential."""+ operation = {}+ func = create_tool_function(+ path="/data",+ method="get",+ operation=operation,+ base_url="https://api.example.com",+ )++ with patch(GET_ASYNC_CLIENT_TARGET) as mock_client:+ async_client = _create_mock_client("get", "ok")+ mock_client.return_value = async_client++ token = _request_resolved_auth_headers.set({"Authorization": "Bearer resolved-oauth"})+ _request_resolved_auth_headers.reset(token)++ await func()++ headers_sent = async_client.get.call_args[1]["headers"]+ assert "Authorization" not in headers_sentdiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.pyindex 3ad01e9c3ec..1e4349c3143 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py@@ -218,3 +218,86 @@ async def test_openapi_local_tool_denied_when_server_not_resolvable():assert exc.value.status_code == 503pre_call.assert_not_awaited()handle_local.assert_not_awaited()+++async def test_openapi_local_tool_injects_resolved_oauth_token():+ """LIT-4629: the local-registry (OpenAPI) dispatch is the primary egress for spec_path+ tools, and before the fix it dropped the gateway-resolved OAuth credential entirely, so a+ user's completed OAuth flow stored a token that never reached the upstream API. The resolved+ credential must land in the `_request_resolved_auth_headers` ContextVar the tool closure+ reads. Kills the mutant that deletes the resolve_openapi_upstream_auth call in server.py."""+ from litellm.proxy._experimental.mcp_server import server as mcp_module+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (+ _request_resolved_auth_headers,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (+ StaticHeaderAuth,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok+ from litellm.types.mcp import MCPAuth, MCPTransport+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ user = UserAPIKeyAuth(+ api_key="sk-user",+ user_id="alice",+ user_role=LitellmUserRoles.INTERNAL_USER.value,+ )+ oauth_server = MCPServer(+ server_id="srv-sheets",+ name="google_sheets",+ server_name="google_sheets",+ url=None,+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2,+ spec_path="https://example.com/sheets-openapi.yaml",+ )++ fake_tool = MagicMock()+ fake_tool.name = "get_values"+ captured: dict = {}++ async def handle_local(_name, _arguments):+ captured["resolved"] = _request_resolved_auth_headers.get()+ return []++ with (+ patch.object(+ mcp_module.global_mcp_server_manager,+ "_get_mcp_server_from_tool_name",+ return_value=oauth_server,+ ),+ patch.object(+ mcp_module.global_mcp_server_manager,+ "pre_call_tool_check",+ new=AsyncMock(return_value={}),+ ),+ patch.object(+ mcp_module.global_mcp_tool_registry,+ "get_tool",+ return_value=fake_tool,+ ),+ patch.object(+ mcp_module.global_mcp_server_manager._cred_provider,+ "resolve_credentials",+ new=AsyncMock(return_value=Ok(StaticHeaderAuth("Bearer stored-user-token"))),+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._handle_local_mcp_tool",+ new=handle_local,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",+ return_value=True,+ ),+ ):+ await mcp_module.execute_mcp_tool(+ name="get_values",+ arguments={},+ allowed_mcp_servers=[oauth_server],+ start_time=datetime.now(timezone.utc),+ user_api_key_auth=user,+ )++ assert captured["resolved"] == {"Authorization": "Bearer stored-user-token"}+ assert _request_resolved_auth_headers.get() is None