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): route true_passthrough and oauth_delegate through upstream OAuth discovery
Tin Chi Lo446a6e8cddc8
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex 89d645b6f8a..f383c99c563 100644--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@ -1337,7 +1337,9 @@ async def _build_oauth_protected_resource_response(# Pass-through branch: proxy the upstream's own metadata so discovery# directs the client at the real IdP (Okta, Keycloak, …) instead of us.- if mcp_server is not None and mcp_server.is_oauth_passthrough:+ if mcp_server is not None and (+ mcp_server.is_oauth_passthrough or mcp_server.is_oauth_delegate or mcp_server.is_true_passthrough+ ):try:upstream_metadata = await fetch_upstream_oauth_protected_resource(mcp_server)except Exception as exc:@@ -1353,8 +1355,9 @@ async def _build_oauth_protected_resource_response()if upstream_metadata is not None:- response = {**upstream_metadata, "resource": resource_url}- return response+ if mcp_server.is_true_passthrough:+ return upstream_metadata+ return {**upstream_metadata, "resource": resource_url}# Upstream responded but with non-200 or non-dict payload. For# pass-through servers the gateway is NOT the authorization server,diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex 96fd014fbe1..7a854f698c9 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -3526,6 +3526,29 @@ if MCP_AVAILABLE:headers={"www-authenticate": www_authenticate},)+ if server and server.is_oauth_delegate and _get_forwarded_auth_from_scope(scope) is None:+ www_authenticate = _get_passthrough_www_authenticate(+ scope=scope,+ server_name=server_name,+ )+ raise HTTPException(+ status_code=401,+ detail="Unauthorized",+ headers={"www-authenticate": www_authenticate},+ )++ if server and server.is_true_passthrough and not _scope_has_authorization_header(scope):+ upstream_status, upstream_www_authenticate = await _probe_upstream_auth(server.url or "", "")+ if upstream_status == 401 and upstream_www_authenticate:+ raise HTTPException(+ status_code=401,+ detail="Unauthorized",+ headers={"www-authenticate": upstream_www_authenticate},+ )++ def _scope_has_authorization_header(scope: Scope) -> bool:+ return any(key.lower() == b"authorization" for key, _ in scope.get("headers", []))+def _get_forwarded_auth_from_scope(scope: Scope) -> Optional[str]:"""Return the upstream-bound ``Authorization`` header value, or None.@@ -3553,7 +3576,7 @@ if MCP_AVAILABLE:url: str,auth_header: str,timeout: float = 5.0,- ) -> tuple:+ ) -> tuple[int, Optional[str]]:"""JSON-RPC initialize-probe the upstream URL to check whether the token is accepted.Uses POST so StreamableHTTP MCP servers run the same auth path as a@@ -3583,8 +3606,8 @@ if MCP_AVAILABLE:},}probe_headers = {- "Authorization": auth_header,"Accept": "application/json, text/event-stream",+ **({"Authorization": auth_header} if auth_header else {}),}try:resp = await client.post(diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_oauth_passthrough.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_oauth_passthrough.pyindex ad78609ee18..002e98034c1 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_oauth_passthrough.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_oauth_passthrough.py@@ -472,3 +472,102 @@ async def test_oauth_protected_resource_gateway_managed_unchanged():"https://gateway.example.com/keycloak_whoami"]assert result["scopes_supported"] == ["read"]+++def _make_upstream_metadata_client() -> tuple[dict, MagicMock]:+ upstream_payload = {+ "resource": "https://upstream.example.com/mcp",+ "authorization_servers": ["https://okta.example.com/oauth2/default"],+ "scopes_supported": ["openid", "profile"],+ "bearer_methods_supported": ["header"],+ }+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = upstream_payload+ mock_client = MagicMock()+ mock_client.get = AsyncMock(return_value=mock_response)+ return upstream_payload, mock_client+++async def test_oauth_protected_resource_oauth_delegate_proxies_upstream_with_gateway_resource():+ """oauth_delegate discovery must proxy the upstream's authorization_servers+ (so the client authorizes against the upstream IdP) while rewriting resource+ to the gateway (so bearers are presented back to LiteLLM). A regression that+ dropped oauth_delegate from the pass-through predicate would fall through to+ the gateway-AS branch and advertise LiteLLM as the authorization server."""+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )++ global_mcp_server_manager.registry.clear()+ delegate_server = MCPServer(+ server_id="delegate-1",+ name="sample_docs",+ server_name="sample_docs",+ alias="sample_docs",+ url="https://upstream.example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth_delegate,+ )+ global_mcp_server_manager.registry[delegate_server.server_id] = delegate_server++ _, mock_client = _make_upstream_metadata_client()+ try:+ with patch.object(+ discoverable_endpoints, "get_async_httpx_client", return_value=mock_client+ ):+ result = await _build_oauth_protected_resource_response(+ request=_make_request(),+ mcp_server_name="sample_docs",+ use_standard_pattern=True,+ )++ assert result["authorization_servers"] == [+ "https://okta.example.com/oauth2/default"+ ]+ assert result["resource"].endswith("/mcp/sample_docs")+ assert result["resource"] != "https://upstream.example.com/mcp"+ finally:+ global_mcp_server_manager.registry.clear()+++async def test_oauth_protected_resource_true_passthrough_returns_upstream_metadata_verbatim():+ """true_passthrough discovery must return the upstream metadata verbatim,+ resource included, so the client treats the upstream as the resource and+ authorizes directly against it. A regression that rewrote resource (the+ gateway-proxied behavior) would break the transparent-proxy contract."""+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )++ global_mcp_server_manager.registry.clear()+ true_passthrough_server = MCPServer(+ server_id="tp-1",+ name="sample_docs",+ server_name="sample_docs",+ alias="sample_docs",+ url="https://upstream.example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.true_passthrough,+ )+ global_mcp_server_manager.registry[true_passthrough_server.server_id] = (+ true_passthrough_server+ )++ upstream_payload, mock_client = _make_upstream_metadata_client()+ try:+ with patch.object(+ discoverable_endpoints, "get_async_httpx_client", return_value=mock_client+ ):+ result = await _build_oauth_protected_resource_response(+ request=_make_request(),+ mcp_server_name="sample_docs",+ use_standard_pattern=True,+ )++ assert result == upstream_payload+ assert result["resource"] == "https://upstream.example.com/mcp"+ finally:+ global_mcp_server_manager.registry.clear()diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.pyindex 76614a35b53..44ea5f43a70 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py@@ -713,6 +713,9 @@ async def test_handle_streamable_http_mcp_delegated_server_surfaces_upstream_chadelegated_server.auth_type = MCPAuth.oauth2delegated_server.delegate_auth_to_upstream = Truedelegated_server.needs_user_oauth_token = True+ delegated_server.is_oauth_passthrough = False+ delegated_server.is_oauth_delegate = False+ delegated_server.is_true_passthrough = Falsedelegated_server.server_id = "delegated-oauth-server"upstream_challenge = 'Bearer resource_metadata="https://upstream.example.com/.well-known/oauth-protected-resource"'@@ -1048,3 +1051,310 @@ async def test_handle_streamable_http_mcp_token_exchange_without_subject_returnsassert "/.well-known/oauth-protected-resource" in challengeassert challenge.split('resource_metadata="', 1)[1].split('"', 1)[0].endswith("/mcp/obo_server")assert 'error="invalid_token"' in challenge+++def _passthrough_mode_scope(server_name: str, extra_headers=None):+ headers = [+ (b"content-type", b"application/json"),+ (b"host", b"litellm.example.com"),+ ] + list(extra_headers or [])+ return {+ "type": "http",+ "method": "POST",+ "path": f"/mcp/{server_name}",+ "_original_path": f"/{server_name}/mcp",+ "scheme": "https",+ "query_string": b"",+ "root_path": "",+ "server": ("litellm.example.com", 443),+ "headers": headers,+ }+++def _build_passthrough_mode_server(server_name: str, auth_type):+ from litellm.proxy._types import MCPTransport+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ return MCPServer(+ server_id=f"{server_name}-id",+ name=server_name,+ server_name=server_name,+ alias=server_name,+ url="https://upstream.example.com/mcp",+ transport=MCPTransport.http,+ auth_type=auth_type,+ )+++async def test_handle_streamable_http_mcp_oauth_delegate_without_token_returns_gateway_proxied_401():+ """oauth_delegate is admitted with the LiteLLM key but still owns upstream+ OAuth. With no forwarded upstream token the gateway must challenge with the+ proxied resource_metadata (which advertises the upstream IdP), never the+ gateway authorization_uri and never a silent 200."""+ from fastapi import HTTPException++ try:+ from litellm.proxy._experimental.mcp_server.server import (+ handle_streamable_http_mcp,+ session_manager_stateful,+ )+ except ImportError:+ pytest.skip("MCP server not available")++ scope = _passthrough_mode_scope("od_server")+ receive = AsyncMock(+ return_value={+ "type": "http.request",+ "body": b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}',+ "more_body": False,+ }+ )+ send = AsyncMock()+ user_auth = MagicMock()+ user_auth.user_id = "u1"+ od_server = _build_passthrough_mode_server("od_server", MCPAuth.oauth_delegate)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",+ new_callable=AsyncMock,+ return_value=(user_auth, None, ["od_server"], None, None, None),+ ),+ patch("litellm.proxy._experimental.mcp_server.server.set_auth_context"),+ patch(+ "litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",+ True,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager.get_mcp_server_by_name",+ return_value=od_server,+ ),+ patch.object(+ session_manager_stateful,+ "handle_request",+ new_callable=AsyncMock,+ ) as mock_handle_request,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await handle_streamable_http_mcp(scope, receive, send)++ assert mock_handle_request.await_count == 0+ assert exc_info.value.status_code == 401+ challenge = exc_info.value.headers["www-authenticate"]+ assert "resource_metadata=" in challenge+ assert "authorization_uri=" not in challenge+ assert "/.well-known/oauth-protected-resource/od_server/mcp" in challenge+++async def test_handle_streamable_http_mcp_oauth_delegate_with_forwarded_token_skips_challenge():+ """When the oauth_delegate caller carries both the LiteLLM key and a separate+ upstream Authorization, the gateway must forward to the session manager, not+ re-challenge. Guards the ``_get_forwarded_auth_from_scope(...) is None``+ condition: dropping it would 401 even a fully-authenticated request."""+ try:+ from litellm.proxy._experimental.mcp_server.server import (+ handle_streamable_http_mcp,+ session_manager_stateless,+ )+ except ImportError:+ pytest.skip("MCP server not available")++ scope = _passthrough_mode_scope(+ "od_server",+ extra_headers=[+ (b"x-litellm-api-key", b"Bearer sk-1234"),+ (b"authorization", b"Bearer upstream-token"),+ ],+ )+ receive = AsyncMock(+ return_value={+ "type": "http.request",+ "body": b'{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}',+ "more_body": False,+ }+ )+ send = AsyncMock()+ user_auth = MagicMock()+ user_auth.user_id = "u1"+ od_server = _build_passthrough_mode_server("od_server", MCPAuth.oauth_delegate)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",+ new_callable=AsyncMock,+ return_value=(user_auth, None, ["od_server"], None, None, None),+ ),+ patch("litellm.proxy._experimental.mcp_server.server.set_auth_context"),+ patch(+ "litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",+ True,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._handle_stale_mcp_session",+ new_callable=AsyncMock,+ return_value=False,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._check_passthrough_upstream_auth",+ new_callable=AsyncMock,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager.get_mcp_server_by_name",+ return_value=od_server,+ ),+ patch.object(+ session_manager_stateless,+ "handle_request",+ new_callable=AsyncMock,+ ) as mock_handle_request,+ patch.object(session_manager_stateless, "_server_instances", {}),+ ):+ await handle_streamable_http_mcp(scope, receive, send)++ assert mock_handle_request.await_count == 1+++async def test_handle_streamable_http_mcp_true_passthrough_without_token_surfaces_verbatim_upstream_challenge():+ """true_passthrough is a transparent proxy: with no client Authorization the+ gateway probes the upstream and surfaces its own WWW-Authenticate verbatim,+ so the client discovers and authorizes against the upstream directly. Guards+ against answering initialize locally with a silent 200."""+ from fastapi import HTTPException++ try:+ from litellm.proxy._experimental.mcp_server.server import (+ handle_streamable_http_mcp,+ session_manager_stateful,+ )+ except ImportError:+ pytest.skip("MCP server not available")++ upstream_challenge = 'Bearer resource_metadata="https://upstream.example.com/.well-known/oauth-protected-resource"'+ probe_response = MagicMock()+ probe_response.status_code = 401+ probe_response.headers = {"www-authenticate": upstream_challenge}+ probe_client = MagicMock()+ probe_client.post = AsyncMock(return_value=probe_response)++ scope = _passthrough_mode_scope("tp_server")+ receive = AsyncMock(+ return_value={+ "type": "http.request",+ "body": b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}',+ "more_body": False,+ }+ )+ send = AsyncMock()+ user_auth = MagicMock()+ user_auth.user_id = None+ tp_server = _build_passthrough_mode_server("tp_server", MCPAuth.true_passthrough)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",+ new_callable=AsyncMock,+ return_value=(user_auth, None, ["tp_server"], None, None, None),+ ),+ patch("litellm.proxy._experimental.mcp_server.server.set_auth_context"),+ patch(+ "litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",+ True,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.get_async_httpx_client",+ return_value=probe_client,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager.get_mcp_server_by_name",+ return_value=tp_server,+ ),+ patch.object(+ session_manager_stateful,+ "handle_request",+ new_callable=AsyncMock,+ ) as mock_handle_request,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await handle_streamable_http_mcp(scope, receive, send)++ assert mock_handle_request.await_count == 0+ assert exc_info.value.status_code == 401+ assert exc_info.value.headers["www-authenticate"] == upstream_challenge+ probe_client.post.assert_awaited_once()+++async def test_handle_streamable_http_mcp_true_passthrough_with_token_skips_probe_and_challenge():+ """When the true_passthrough caller already carries an Authorization the+ gateway must forward without probing or challenging. Guards the+ ``not _scope_has_authorization_header(scope)`` condition and the no-probe+ fast path."""+ try:+ from litellm.proxy._experimental.mcp_server.server import (+ handle_streamable_http_mcp,+ session_manager_stateless,+ )+ except ImportError:+ pytest.skip("MCP server not available")++ probe_client = MagicMock()+ probe_client.post = AsyncMock()++ scope = _passthrough_mode_scope(+ "tp_server",+ extra_headers=[(b"authorization", b"Bearer upstream-token")],+ )+ receive = AsyncMock(+ return_value={+ "type": "http.request",+ "body": b'{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}',+ "more_body": False,+ }+ )+ send = AsyncMock()+ user_auth = MagicMock()+ user_auth.user_id = None+ tp_server = _build_passthrough_mode_server("tp_server", MCPAuth.true_passthrough)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",+ new_callable=AsyncMock,+ return_value=(user_auth, None, ["tp_server"], None, None, None),+ ),+ patch("litellm.proxy._experimental.mcp_server.server.set_auth_context"),+ patch(+ "litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",+ True,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._handle_stale_mcp_session",+ new_callable=AsyncMock,+ return_value=False,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._check_passthrough_upstream_auth",+ new_callable=AsyncMock,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.get_async_httpx_client",+ return_value=probe_client,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager.get_mcp_server_by_name",+ return_value=tp_server,+ ),+ patch.object(+ session_manager_stateless,+ "handle_request",+ new_callable=AsyncMock,+ ) as mock_handle_request,+ patch.object(session_manager_stateless, "_server_instances", {}),+ ):+ await handle_streamable_http_mcp(scope, receive, send)++ assert mock_handle_request.await_count == 1+ probe_client.post.assert_not_awaited()