Skip to content

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]

fix(mcp): forward the per-server auth header on OpenAPI tool calls (#37410)

tin-berrida7a10ebbdb1
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index ecce959143a..65855df89f6 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -123,6 +123,7 @@ from litellm.proxy._experimental.mcp_server.utils import (
iter_known_server_prefixes,
iter_known_tool_name_spellings,
logging_safe_mcp_headers,
+ lookup_mcp_server_auth_in_headers,
match_known_server_prefix,
match_known_tool_name,
merge_mcp_headers,
@@ -873,6 +874,53 @@ def _openapi_forwarded_extra_headers(
return forwarded or None
+def _resolve_openapi_tool_auth(
+ mcp_server: MCPServer,
+ mcp_auth_header: str | None,
+ mcp_server_auth_headers: Mapping[str, str | dict[str, str]] | None, # mutable-ok: sink shape
+ raw_headers: dict[str, str] | None, # mutable-ok: sink takes a concrete dict
+ user_api_key_auth: UserAPIKeyAuth | None,
+) -> tuple[str | None, dict[str, str] | None, str | dict[str, str] | None]: # mutable-ok: sink shapes
+ """The caller's upstream credential for one ``spec_path`` server, for both OpenAPI dispatch arms.
+
+ A per-server ``x-mcp-{alias}-authorization`` wins over the deprecated global / BYOK
+ ``mcp_auth_header``, the same precedence ``_call_regular_mcp_tool`` applies, so the OpenAPI and
+ managed paths cannot disagree about which credential is authoritative. The two kinds are not
+ interchangeable: a per-server value is already a complete header value and is forwarded verbatim,
+ while a BYOK credential is a raw secret that takes the server's auth-type prefix. Formatting the
+ former would ship ``Bearer Bearer <token>``.
+
+ Returns the ``Authorization`` value to inject, the extra headers to forward, and the credential to
+ hand ``resolve_openapi_upstream_auth``, whose passthrough arm reads it via
+ ``_passthrough_token_from_mcp_auth_header``. The per-server Authorization travels only in the
+ credential, never also in the forwarded headers, because the resolver pops Authorization out of
+ those and would otherwise have two sources to reconcile.
+ """
+ forwarded: Final = _openapi_forwarded_extra_headers(mcp_server, raw_headers, user_api_key_auth)
+ per_server: Final = (
+ lookup_mcp_server_auth_in_headers(
+ mcp_server_auth_headers,
+ alias=mcp_server.alias,
+ server_name=mcp_server.server_name,
+ )
+ if mcp_server_auth_headers
+ else None
+ )
+
+ if isinstance(per_server, dict):
+ authorization: Final = next((v for k, v in per_server.items() if k.lower() == "authorization"), None)
+ merged: Final = merge_mcp_headers(extra_headers=forwarded, static_headers=_without_authorization(per_server))
+ if authorization is None:
+ byok: Final = _format_byok_openapi_auth_header(mcp_server, mcp_auth_header) if mcp_auth_header else None
+ return byok, merged, mcp_auth_header
+ return authorization, merged, per_server
+ if isinstance(per_server, str) and per_server:
+ return per_server, forwarded, per_server
+ if mcp_auth_header:
+ return _format_byok_openapi_auth_header(mcp_server, mcp_auth_header), forwarded, mcp_auth_header
+ return None, forwarded, None
+
+
async def _resolve_byok_mcp_auth_header(
mcp_server: MCPServer,
user_api_key_auth: UserAPIKeyAuth | None,
@@ -3193,10 +3241,6 @@ class MCPServerManager:
# Get server-specific auth header if available
server_auth_header: str | dict[str, str] | None = None
if mcp_server_auth_headers:
- from litellm.proxy._experimental.mcp_server.utils import (
- lookup_mcp_server_auth_in_headers,
- )
-
server_auth_header = lookup_mcp_server_auth_in_headers(
mcp_server_auth_headers,
alias=server.alias,
@@ -5221,11 +5265,6 @@ class MCPServerManager:
# the exact case of server alias/name (e.g., '1litellmagcgateway' vs '1LiteLLMAGCGateway')
server_auth_header: dict[str, str] | str | None = None
if mcp_server_auth_headers:
- # Normalize keys for case-insensitive lookup
- from litellm.proxy._experimental.mcp_server.utils import (
- lookup_mcp_server_auth_in_headers,
- )
-
server_auth_header = lookup_mcp_server_auth_in_headers(
mcp_server_auth_headers,
alias=mcp_server.alias,
@@ -5718,16 +5757,20 @@ class MCPServerManager:
server_name,
)
- auth_header_value: Final = (
- _format_byok_openapi_auth_header(mcp_server, mcp_auth_header) if mcp_auth_header else None
+ auth_header_value, openapi_forwarded_headers, upstream_credential = _resolve_openapi_tool_auth(
+ mcp_server=mcp_server,
+ mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
+ raw_headers=raw_headers,
+ user_api_key_auth=user_api_key_auth,
)
resolved_auth_headers, forwarded_headers = await self.resolve_openapi_upstream_auth(
mcp_server=mcp_server,
oauth2_headers=caller_oauth2_headers,
raw_headers=raw_headers,
- mcp_auth_header=mcp_auth_header,
+ mcp_auth_header=upstream_credential,
user_api_key_auth=user_api_key_auth,
- forwarded_headers=_openapi_forwarded_extra_headers(mcp_server, raw_headers, user_api_key_auth),
+ forwarded_headers=openapi_forwarded_headers,
)
async def _call_openapi_via_handler():
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 7365fc4efbd..8d69d84e492 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -430,6 +430,7 @@ if MCP_AVAILABLE:
MCPServerManager,
_caller_authorization_fans_out,
_client_forwarded_authorization_headers,
+ _resolve_openapi_tool_auth,
_should_strip_caller_authorization,
_without_authorization,
global_mcp_server_manager,
@@ -2835,58 +2836,26 @@ if MCP_AVAILABLE:
arguments = hook_result["arguments"]
verbose_logger.debug("Executing local registry tool: %s", name)
- # For BYOK servers the credential must be injected via a ContextVar
- # because the tool function has headers baked into its closure.
- # Pre-format the full Authorization header value using the server's
- # configured auth_type so the generator doesn't need to know the prefix.
- auth_header_value: str | None = None
- if mcp_auth_header:
- server_auth_type: Final = getattr(mcp_server, "auth_type", None) if mcp_server else None
- if server_auth_type == MCPAuth.api_key:
- auth_header_value = f"ApiKey {mcp_auth_header}"
- elif server_auth_type == MCPAuth.basic:
- auth_header_value = f"Basic {mcp_auth_header}"
- else:
- auth_header_value = f"Bearer {mcp_auth_header}"
-
- # Forward named client headers to OpenAPI tool upstream requests.
- # MCPServer.extra_headers lists header names to copy from raw_headers.
- # The strip decision is centralized in _should_strip_caller_authorization so this
- # OpenAPI/local path agrees with the managed paths: M2M and the resolver-owned modes
- # (token_exchange's raw subject token, authorization_code's stored token) must never
- # have the caller's Authorization forwarded verbatim upstream.
- forwarded_headers: dict[str, str] | None = None
- if mcp_server and mcp_server.extra_headers and raw_headers:
- normalized_raw: Final = {str(k).lower(): v for k, v in raw_headers.items() if isinstance(k, str)}
- skip_caller_authorization: Final = _should_strip_caller_authorization(
- mcp_server=mcp_server,
- raw_headers=raw_headers,
- user_api_key_auth=user_api_key_auth,
- )
- for header_name in mcp_server.extra_headers:
- if not isinstance(header_name, str):
- continue
- if skip_caller_authorization and header_name.lower() == "authorization":
- continue
- value = normalized_raw.get(header_name.lower())
- if value is not None:
- if forwarded_headers is None:
- 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,
- )
+ # The credential rides ContextVars because the tool function has its
+ # headers baked into the closure at registration time.
+ auth_header_value, openapi_forwarded_headers, upstream_credential = _resolve_openapi_tool_auth(
+ mcp_server=mcp_server,
+ mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
+ raw_headers=raw_headers,
+ user_api_key_auth=user_api_key_auth,
+ )
+ (
+ 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=upstream_credential,
+ user_api_key_auth=user_api_key_auth,
+ forwarded_headers=openapi_forwarded_headers,
+ )
_auth_token: Final = _request_auth_header.set(auth_header_value)
_extra_token: Final = _request_extra_headers.set(forwarded_headers)
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.py
index 309f3cfb572..9064312fd6d 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
@@ -42,6 +42,7 @@ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
_deserialize_json_list,
_normalize_mcp_server_cost_info,
_obo_retry_applies,
+ _resolve_openapi_tool_auth,
_should_strip_caller_authorization,
_without_authorization,
)
@@ -10664,3 +10665,103 @@ class TestClientForwardedDiscoveryFailureIsNotFatal:
assert resolved.registration_url == "https://idp.example.com/register"
assert manager.config_mcp_servers[server.server_id].authorization_url == "https://idp.example.com/authorize"
assert manager._oauth_discovery_slot(server.server_id) is None
+
+
+class TestResolveOpenapiToolAuth:
+ """The credential matrix for a ``spec_path`` server's two OpenAPI dispatch arms.
+
+ A per-server ``x-mcp-{alias}-authorization`` is already a complete header value and is forwarded
+ verbatim; a BYOK credential is a raw secret that takes the auth-type prefix. Conflating them
+ ships ``Bearer Bearer <token>``, so every cell pins which of the two a value came from.
+ """
+
+ @staticmethod
+ def _server(auth_type: MCPAuthType = MCPAuth.oauth_delegate) -> MCPServer:
+ return MCPServer(
+ server_id="srv-openapi",
+ name="report_api",
+ server_name="report_api",
+ alias="report_api",
+ url="https://api.internal.example.com",
+ transport=MCPTransport.http,
+ auth_type=auth_type,
+ spec_path="https://api.internal.example.com/openapi.json",
+ extra_headers=["X-Tenant"],
+ )
+
+ @pytest.mark.parametrize(
+ "per_server, byok, expected_auth, expected_extra_keys, expected_credential",
+ [
+ (
+ {"report_api": "Bearer caller-token"},
+ None,
+ "Bearer caller-token",
+ {"X-Tenant"},
+ "Bearer caller-token",
+ ),
+ (
+ {"report_api": {"Authorization": "Bearer caller-token", "X-Trace": "abc"}},
+ None,
+ "Bearer caller-token",
+ {"X-Tenant", "X-Trace"},
+ {"Authorization": "Bearer caller-token", "X-Trace": "abc"},
+ ),
+ (
+ {"report_api": {"X-Api-Key": "k1"}},
+ "byok-secret",
+ "Bearer byok-secret",
+ {"X-Tenant", "X-Api-Key"},
+ "byok-secret",
+ ),
+ ({"report_api": {"X-Api-Key": "k1"}}, None, None, {"X-Tenant", "X-Api-Key"}, None),
+ (None, "byok-secret", "Bearer byok-secret", {"X-Tenant"}, "byok-secret"),
+ (None, None, None, {"X-Tenant"}, None),
+ ({"other_server": "Bearer wrong"}, None, None, {"X-Tenant"}, None),
+ ],
+ )
+ def test_credential_matrix(
+ self,
+ per_server: dict | None,
+ byok: str | None,
+ expected_auth: str | None,
+ expected_extra_keys: set,
+ expected_credential: object,
+ ):
+ auth_value, forwarded, credential = _resolve_openapi_tool_auth(
+ mcp_server=self._server(),
+ mcp_auth_header=byok,
+ mcp_server_auth_headers=per_server,
+ raw_headers={"x-tenant": "acme", "authorization": "Bearer admission-key"},
+ user_api_key_auth=None,
+ )
+
+ assert auth_value == expected_auth
+ assert set(forwarded or {}) == expected_extra_keys
+ assert credential == expected_credential
+
+ def test_per_server_value_is_never_re_prefixed(self):
+ """The regression that a naive wiring produces: the caller already sent ``Bearer <token>``."""
+ auth_value, _, credential = _resolve_openapi_tool_auth(
+ mcp_server=self._server(auth_type=MCPAuth.api_key),
+ mcp_auth_header="byok-secret",
+ mcp_server_auth_headers={"report_api": "Bearer caller-token"},
+ raw_headers=None,
+ user_api_key_auth=None,
+ )
+
+ assert auth_value == "Bearer caller-token"
+ assert credential == "Bearer caller-token"
+ assert not auth_value.startswith("ApiKey ")
+
+ def test_per_server_authorization_is_not_also_left_in_forwarded_headers(self):
+ """``resolve_openapi_upstream_auth`` pops Authorization out of the forwarded headers, so a
+ second copy there would give the passthrough arm two sources to reconcile."""
+ _, forwarded, _ = _resolve_openapi_tool_auth(
+ mcp_server=self._server(),
+ mcp_auth_header=None,
+ mcp_server_auth_headers={"report_api": {"Authorization": "Bearer caller-token"}},
+ raw_headers={"x-tenant": "acme"},
+ user_api_key_auth=None,
+ )
+
+ assert "Authorization" not in (forwarded or {})
diff --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.py
index 63473bf3cf5..7bd846aeda4 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
@@ -189,9 +189,11 @@ async def test_openapi_local_tool_denied_when_server_not_resolvable():
pre_call = AsyncMock(return_value={})
handle_local = AsyncMock(return_value=[])
+ resolve_auth = MagicMock()
# `_get_mcp_server_from_tool_name` returns None — no server context.
with (
+ patch.object(mcp_module, "_resolve_openapi_tool_auth", new=resolve_auth),
patch.object(
mcp_module.global_mcp_server_manager,
"_get_mcp_server_from_tool_name",
@@ -228,6 +230,9 @@ async def test_openapi_local_tool_denied_when_server_not_resolvable():
assert exc.value.status_code == 503
pre_call.assert_not_awaited()
handle_local.assert_not_awaited()
+ # The credential resolver takes a non-optional server, so the 503 guard above it is what keeps
+ # a missing server from ever reaching it. Pinned here so moving the guard reds this test.
+ resolve_auth.assert_not_called()
@pytest.mark.asyncio
@@ -549,3 +554,101 @@ async def test_unknown_tool_name_still_reports_not_found():
assert exc.value.status_code == 404
assert "not found" in str(exc.value.detail)
+
+
+OPENAPI_PER_SERVER_TOKEN = "Bearer per-server-upstream-token"
+
+
+def _spec_path_server() -> MCPServer:
+ return MCPServer(
+ server_id="srv-reports",
+ name="report_api",
+ server_name="report_api",
+ alias="report_api",
+ url="https://api.internal.example.com",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth_delegate,
+ spec_path="https://api.internal.example.com/openapi.json",
+ )
+
+
[email protected]("dispatch_arm", ["local_registry", "call_tool"])
+async def test_per_server_auth_header_reaches_both_openapi_dispatch_arms(dispatch_arm: str):
+ """`x-mcp-{alias}-authorization` must survive on BOTH OpenAPI dispatch arms.
+
+ OpenAPI tools live in the local tool registry, so `execute_mcp_tool` serves MCP-protocol and REST
+ tool calls while `MCPServerManager.call_tool` serves the responses-API handler. Both arms sourced
+ the upstream credential only from the deprecated global / BYOK `mcp_auth_header`, so the
+ per-server header was dropped and the upstream API saw no Authorization at all.
+
+ Asserting on the resolver kwarg as well as the ContextVar is deliberate: for the client-forwarded
+ modes the credential has to reach `resolve_openapi_upstream_auth`, whose passthrough arm outranks
+ the ContextVar when it materializes a header.
+ """
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (
+ _request_auth_header,
+ )
+
+ server = _spec_path_server()
+ auth_headers = {"report_api": {"Authorization": OPENAPI_PER_SERVER_TOKEN}}
+ user = UserAPIKeyAuth(api_key="sk-user", user_id="alice", user_role=LitellmUserRoles.INTERNAL_USER.value)
+ captured: dict = {}
+
+ async def fake_resolver(**kwargs):
+ captured["resolver_credential"] = kwargs["mcp_auth_header"]
+ return None, kwargs["forwarded_headers"]
+
+ async def capture_local(_name, _arguments):
+ captured["injected"] = _request_auth_header.get()
+ return []
+
+ async def capture_openapi_handler(_server, _name, _arguments):
+ captured["injected"] = _request_auth_header.get()
+ return []
+
+ manager = mcp_module.global_mcp_server_manager
+ with (
+ patch.object(manager, "resolve_openapi_upstream_auth", new=fake_resolver),
+ patch.object(manager, "pre_call_tool_check", new=AsyncMock(return_value={})),
+ ):
+ if dispatch_arm == "local_registry":
+ fake_tool = MagicMock()
+ fake_tool.name = "list_reports"
+ with (
+ patch.object(manager, "_get_mcp_server_from_tool_name", return_value=server),
+ patch.object(mcp_module.global_mcp_tool_registry, "get_tool", return_value=fake_tool),
+ patch(
+ "litellm.proxy._experimental.mcp_server.server._handle_local_mcp_tool",
+ new=capture_local,
+ ),
+ patch(
+ "litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",
+ return_value=True,
+ ),
+ ):
+ await mcp_module.execute_mcp_tool(
+ name="list_reports",
+ arguments={},
+ allowed_mcp_servers=[server],
+ start_time=datetime.now(timezone.utc),
+ user_api_key_auth=user,
+ mcp_server_auth_headers=auth_headers,
+ )
+ else:
+ with (
+ patch.object(manager, "_resolve_mcp_server_for_tool_call", return_value=server),
+ patch.object(manager, "_call_openapi_tool_handler", new=capture_openapi_handler),
+ ):
+ await manager.call_tool(
+ server_name="report_api",
+ name="list_reports",
+ arguments={},
+ user_api_key_auth=user,
+ mcp_server_auth_headers=auth_headers,
+ )
+
+ assert captured["resolver_credential"] == {"Authorization": OPENAPI_PER_SERVER_TOKEN}
+ assert captured["injected"] == OPENAPI_PER_SERVER_TOKEN
+ assert _request_auth_header.get() is None