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
feat(mcp): discover the OBO token endpoint via RFC 9728 -> RFC 8414 (no IdP guessing) (#31762)
tin-berric737789b2636
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 04cbd974b85..8451f6dff6f 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -540,6 +540,18 @@ class MCPServerManager:return "client_credentials"return None+ @staticmethod+ def _obo_needs_endpoint_discovery(+ auth_type: Optional[MCPAuthType],+ token_exchange_endpoint: Optional[str],+ token_url: Optional[str],+ ) -> bool:+ """An ``oauth2_token_exchange`` server with no configured token endpoint can have it+ discovered (RFC 9728 -> RFC 8414) the same way the ``oauth2`` flow already does; an explicitly+ configured ``token_exchange_endpoint``/``token_url`` wins and skips the discovery round-trip.+ """+ return auth_type == MCPAuth.oauth2_token_exchange and not (token_exchange_endpoint or token_url)+def __init__(self, cred_provider: Optional[UpstreamCredentialProvider] = None):self._cred_provider = cred_provider or UpstreamCredentialProvider(oauth_token_store=LazyPerUserOAuthTokenStore(self.get_mcp_server_by_id),@@ -729,9 +741,17 @@ class MCPServerManager:)auth_type = server_config.get("auth_type", None)- if server_url and auth_type is not None and auth_type == MCPAuth.oauth2:+ if server_url and (+ auth_type == MCPAuth.oauth2+ or self._obo_needs_endpoint_discovery(+ auth_type,+ server_config.get("token_exchange_endpoint"),+ server_config.get("token_url"),+ )+ ):mcp_oauth_metadata = await self._descovery_metadata(server_url=server_url,+ allow_origin_fallback=auth_type == MCPAuth.oauth2,)else:mcp_oauth_metadata = None@@ -1109,9 +1129,19 @@ class MCPServerManager:auth_type = cast(MCPAuthType, mcp_server.auth_type)server_url = mcp_server.url- needs_discovery = bool(server_url) and auth_type == MCPAuth.oauth2 and not mcp_server.authorization_url+ needs_discovery = bool(server_url) and (+ (auth_type == MCPAuth.oauth2 and not mcp_server.authorization_url)+ or self._obo_needs_endpoint_discovery(+ auth_type,+ credentials_dict.get("token_exchange_endpoint") if credentials_dict else None,+ mcp_server.token_url,+ )+ )mcp_oauth_metadata = (- await self._descovery_metadata(server_url=server_url) # type: ignore[arg-type]+ await self._descovery_metadata(+ server_url=server_url, # type: ignore[arg-type]+ allow_origin_fallback=auth_type == MCPAuth.oauth2,+ )if needs_discoveryelse None)@@ -1186,8 +1216,49 @@ class MCPServerManager:max_concurrent_requests=getattr(mcp_server, "max_concurrent_requests", None),)_warn_internal_delegate_pkce_if_applicable(new_server, source="database")+ await self._persist_discovered_obo_token_url(+ server_id=mcp_server.server_id,+ auth_type=auth_type,+ existing_token_url=mcp_server.token_url,+ discovered_token_url=new_server.token_url,+ )return new_server+ async def _persist_discovered_obo_token_url(+ self,+ *,+ server_id: str,+ auth_type: Optional[MCPAuthType],+ existing_token_url: Optional[str],+ discovered_token_url: Optional[str],+ ) -> None:+ """Write a freshly discovered OBO token endpoint back onto the DB row.++ ``build_mcp_server_from_table`` resolves ``token_url`` via RFC 9728 -> RFC 8414 for an+ ``oauth2_token_exchange`` server that has none configured, but that resolved value otherwise+ lives only on the returned in-memory object; the row keeps ``token_url=None`` so every rebuild+ re-runs discovery, and a transient upstream outage during a rebuild leaves the server with no+ endpoint until discovery next succeeds. Persisting it makes ``_obo_needs_endpoint_discovery``+ return False on the next build. Fires at most once per server (skipped once the row has a+ value), and is best-effort: a write failure just means discovery runs again next time.+ """+ if auth_type != MCPAuth.oauth2_token_exchange:+ return+ if existing_token_url or not discovered_token_url:+ return+ from litellm.proxy.proxy_server import prisma_client # noqa: PLC0415++ if prisma_client is None:+ return+ try:+ await MCPServerRepository(prisma_client).table.update(+ where={"server_id": server_id},+ data={"token_url": discovered_token_url},+ )+ verbose_logger.debug("Persisted discovered OBO token_url for MCP server %s", server_id)+ except Exception as exc: # noqa: BLE001 - best-effort; a failed write re-discovers next build+ verbose_logger.warning("Failed to persist discovered OBO token_url for MCP server %s: %s", server_id, exc)+async def _maybe_register_openapi_tools(self, server: MCPServer, *, initialize_mapping: bool = True):"""Register OpenAPI tools if the server has a spec_path configured."""if server.spec_path:@@ -1933,6 +2004,36 @@ class MCPServerManager:raise_token_exchange_challenge(server, root_path=get_server_root_path())raise_public(err)+ async def preflight_token_exchange(+ self,+ server: MCPServer,+ oauth2_headers: Optional[dict[str, str]],+ user_api_key_auth: Optional[UserAPIKeyAuth],+ ) -> None:+ """Run the OBO exchange for a caller-supplied subject at the transport edge.++ Single-server routes call this before the MCP session opens, where an HTTP status and+ ``WWW-Authenticate`` still reach the client. A rejected subject raises the RFC 9728+ challenge and any other ``CredError`` maps onto its public HTTP status, so an exchange+ failure surfaces as a failure instead of the session continuing into an empty tool list.+ A successful exchange is cached by the exchanger, so the session's list/call reuses it.+ """+ if server.auth_type != MCPAuth.oauth2_token_exchange:+ return+ subject_token = self._extract_bearer_token(oauth2_headers, None)+ if not subject_token:+ return+ spec = to_server_spec(server)+ if spec is None or not isinstance(spec.config, TokenExchangeConfig):+ return+ match await self._cred_provider.resolve_credentials(to_subject(user_api_key_auth, subject_token), spec):+ case Ok(_):+ return+ case Error(err):+ if err.tag == "unauthorized":+ raise_token_exchange_challenge(server, root_path=get_server_root_path())+ raise_public(err)+async def _create_mcp_client(self,server: MCPServer,@@ -2489,8 +2590,17 @@ class MCPServerManager:async def _descovery_metadata(self,server_url: str,+ *,+ allow_origin_fallback: bool = True,) -> Optional[MCPOAuthMetadata]:- """Discover OAuth metadata by following RFC 9728 (protected resource metadata discovery)."""+ """Discover OAuth metadata by following RFC 9728 (protected resource metadata discovery).++ ``allow_origin_fallback`` controls the last-resort guess that treats the resource server's own+ origin as its authorization server when nothing is advertised. The browser ``oauth2`` flow keeps+ it (a human sees the redirect), but token_exchange (OBO) sets it False so the gateway never+ exchanges a subject token against an endpoint it inferred rather than one explicitly configured+ or authoritatively advertised via RFC 9728 / RFC 8414.+ """try:client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP)@@ -2540,7 +2650,7 @@ class MCPServerManager:) = await self._attempt_well_known_discovery(server_url)metadata = None- if not authorization_servers:+ if allow_origin_fallback and not authorization_servers:try:parsed_url = urlparse(server_url)if parsed_url.scheme and parsed_url.netloc:@@ -2702,6 +2812,14 @@ class MCPServerManager:continuescopes = self._extract_scopes(data.get("scopes_supported"))+ verbose_logger.debug(+ "Authorization server metadata from %s: issuer=%s grant_types_supported=%s "+ "token_endpoint_auth_methods_supported=%s",+ url,+ data.get("issuer"),+ data.get("grant_types_supported"),+ data.get("token_endpoint_auth_methods_supported"),+ )metadata = MCPOAuthMetadata(scopes=scopes,authorization_url=data.get("authorization_endpoint"),diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex 014516f881f..d978771f433 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -1861,7 +1861,8 @@ if MCP_AVAILABLE:# tools. Surfacing the upstream 401 to the client as a re-auth challenge is# intentionally not done here: raising from this list handler cannot produce a# 401 + WWW-Authenticate (the MCP session manager serializes it as a JSON-RPC- # error), so that belongs in a request-scope preemptive check, tracked separately.+ # error). Single-server routes surface it via the request-scope preemptive+ # check in _raise_preemptive_401_for_unauthenticated_servers instead.verbose_logger.debug(f"MCP list_tools: omitting {server.name}; it needs upstream auth")return []except Exception as e:@@ -3486,6 +3487,23 @@ if MCP_AVAILABLE:raise_token_exchange_challenge(server, root_path=get_server_root_path())+ # token_exchange (OBO) with a subject present: run the exchange here at the transport+ # edge, so a rejected subject raises the RFC 9728 challenge (and a gateway fault its+ # public status) instead of the session opening and list_tools masking the failure as+ # an empty tool list. Gated to single-server routes; the multi-server aggregate keeps+ # absorbing per-server auth failures so one bad server cannot 401 the whole connect.+ if (+ server+ and server.auth_type == MCPAuth.oauth2_token_exchange+ and oauth2_headers+ and len(mcp_servers or []) == 1+ ):+ await global_mcp_server_manager.preflight_token_exchange(+ server=server,+ oauth2_headers=oauth2_headers,+ user_api_key_auth=user_api_key_auth,+ )+# Pass-through OAuth: when the admin has opted a server into# forwarding the client's bearer token (is_oauth_passthrough) and# the client hasn't supplied one, fail fast with 401 and pointdiff --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 e49e97b6e8d..7c70bb24001 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@@ -837,6 +837,86 @@ class TestMCPServerManager:assert client._resolved_auth is not Noneassert "authorization" not in {k.lower() for k in (client.extra_headers or {})}+ @pytest.mark.asyncio+ async def test_preflight_token_exchange_challenges_on_rejected_subject(self):+ """A subject the IdP rejects must raise the RFC 9728 401 challenge from the preflight, so a+ single-server route fails observably at the transport edge instead of the old behavior of+ the session opening and list_tools masking the failed exchange as an empty tool list."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Error+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import CredError++ class _FakeProvider:+ async def resolve_credentials(self, subject, server):+ return Error(CredError.of_unauthorized("subject token rejected by the IdP"))++ manager = MCPServerManager(cred_provider=_FakeProvider())+ server = self._token_exchange_server("te-preflight-401")++ with pytest.raises(HTTPException) as exc_info:+ await manager.preflight_token_exchange(+ server=server,+ oauth2_headers={"Authorization": "Bearer rejected-subject"},+ user_api_key_auth=None,+ )+ assert exc_info.value.status_code == 401+ headers = exc_info.value.headers or {}+ www_authenticate = headers.get("WWW-Authenticate") or headers.get("www-authenticate") or ""+ assert "resource_metadata" in www_authenticate++ @pytest.mark.asyncio+ async def test_preflight_token_exchange_maps_gateway_fault_to_public_status(self):+ """A gateway-fault CredError (e.g. invalid_client) must surface its public status (500)+ from the preflight, not the OBO 401 challenge and not an empty-success session."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Error+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import CredError++ class _FakeProvider:+ async def resolve_credentials(self, subject, server):+ return Error(CredError.of_misconfigured("token exchange configuration error"))++ manager = MCPServerManager(cred_provider=_FakeProvider())+ server = self._token_exchange_server("te-preflight-500")++ with pytest.raises(HTTPException) as exc_info:+ await manager.preflight_token_exchange(+ server=server,+ oauth2_headers={"Authorization": "Bearer subj"},+ user_api_key_auth=None,+ )+ assert exc_info.value.status_code == 500++ @pytest.mark.asyncio+ async def test_preflight_token_exchange_noop_on_success_and_without_subject(self):+ """A successful exchange returns without raising, and a request with no bearer never+ reaches the resolver (the no-subject case is the existing preemptive challenge's job)."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (+ StaticHeaderAuth,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Ok++ resolved = []++ class _FakeProvider:+ async def resolve_credentials(self, subject, server):+ resolved.append(subject.inbound_token.get_secret_value() if subject.inbound_token else None)+ return Ok(StaticHeaderAuth("Bearer MINTED", header_name="Authorization"))++ manager = MCPServerManager(cred_provider=_FakeProvider())+ server = self._token_exchange_server("te-preflight-ok")++ assert (+ await manager.preflight_token_exchange(+ server=server,+ oauth2_headers={"Authorization": "Bearer good-subject"},+ user_api_key_auth=None,+ )+ is None+ )+ assert resolved == ["good-subject"]++ await manager.preflight_token_exchange(server=server, oauth2_headers=None, user_api_key_auth=None)+ assert resolved == ["good-subject"]+@pytest.mark.asyncioasync def test_call_regular_mcp_tool_passthrough_strips_authorization_when_admission_consumed_litellm_key(self,@@ -1509,8 +1589,10 @@ class TestMCPServerManager:registration_url="https://discovered.example.com/register",)- async def fake_discovery(server_url: str):+ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):assert server_url == "https://example.com/mcp"+ # oauth2 (browser flow) keeps the origin fallback; only OBO disables it.+ assert allow_origin_fallback is Truereturn discovered_metadatamanager._descovery_metadata = fake_discovery # type: ignore[attr-defined]@@ -3361,9 +3443,7 @@ class TestMCPServerManager:with (patch.object(proxy_server_module, "user_api_key_cache", _Cache()),patch.object(proxy_server_module, "prisma_client", None),- patch.object(- manager, "get_allow_all_keys_server_ids", return_value=["global-server"]- ),+ patch.object(manager, "get_allow_all_keys_server_ids", return_value=["global-server"]),patch.object(MCPRequestHandler,"get_allowed_mcp_servers",@@ -3462,9 +3542,7 @@ class TestMCPServerManager:with (patch.object(proxy_server_module, "user_api_key_cache", cache),patch.object(proxy_server_module, "prisma_client", None),- patch.object(- manager, "get_allow_all_keys_server_ids", return_value=["global-server"]- ),+ patch.object(manager, "get_allow_all_keys_server_ids", return_value=["global-server"]),patch.object(MCPRequestHandler,"get_allowed_mcp_servers",@@ -3556,9 +3634,7 @@ class TestMCPServerManager:with (patch.object(proxy_server_module, "user_api_key_cache", _Cache()),patch.object(proxy_server_module, "prisma_client", None),- patch.object(- manager, "get_allow_all_keys_server_ids", return_value=["global-server"]- ),+ patch.object(manager, "get_allow_all_keys_server_ids", return_value=["global-server"]),patch.object(MCPRequestHandler,"get_allowed_mcp_servers",@@ -3711,6 +3787,180 @@ class TestMCPServerTimestamps:default_server = await manager.build_mcp_server_from_table(default_record, credentials_are_encrypted=False)assert default_server.token_endpoint_auth_method is None+ @pytest.mark.asyncio+ async def test_build_mcp_server_from_table_discovers_obo_token_url_when_unset(self):+ """DB path: an OBO server with no token_exchange_endpoint in credentials and no token_url+ column runs discovery, and the resolved endpoint lands on the returned MCPServer."""+ manager = MCPServerManager()+ calls: list[bool] = []++ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):+ calls.append(allow_origin_fallback)+ return MCPOAuthMetadata(+ scopes=None,+ authorization_url=None,+ token_url="https://discovered.example.com/token",+ registration_url=None,+ )++ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]++ record = LiteLLM_MCPServerTable(+ server_id="obo-discover-db-1",+ server_name="obo_discover_db",+ url="https://example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2_token_exchange,+ credentials={"client_id": "cid", "client_secret": "csec"},+ )++ # prisma_client None -> the write-back no-ops; this test isolates the discovery behavior.+ with patch("litellm.proxy.proxy_server.prisma_client", None):+ server = await manager.build_mcp_server_from_table(record, credentials_are_encrypted=False)++ assert calls == [False] # discovery ran once, origin fallback disabled for OBO+ assert server.token_url == "https://discovered.example.com/token"++ @pytest.mark.asyncio+ async def test_build_mcp_server_from_table_skips_discovery_when_obo_endpoint_configured(self):+ """DB path: a configured token_exchange_endpoint in the credentials JSON wins and skips+ discovery entirely, even though the token_url column is empty (the DB-specific lookup uses+ credentials_dict["token_exchange_endpoint"], not the column)."""+ manager = MCPServerManager()+ calls: list[str] = []++ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):+ calls.append(server_url)+ raise AssertionError("discovery must not run when token_exchange_endpoint is configured")++ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]++ record = LiteLLM_MCPServerTable(+ server_id="obo-configured-db-1",+ server_name="obo_configured_db",+ url="https://example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2_token_exchange,+ credentials={+ "client_id": "cid",+ "client_secret": "csec",+ "token_exchange_endpoint": "https://idp.example.com/token",+ },+ )++ server = await manager.build_mcp_server_from_table(record, credentials_are_encrypted=False)++ assert calls == [] # discovery never ran+ assert server.token_exchange_endpoint == "https://idp.example.com/token"++ @pytest.mark.asyncio+ async def test_build_mcp_server_from_table_persists_discovered_obo_token_url(self):+ """A DB-backed OBO server with no configured endpoint discovers token_url and must write it+ back to the row, so the next rebuild skips discovery instead of re-running it every time."""+ manager = MCPServerManager()++ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):+ assert server_url == "https://example.com/mcp"+ assert allow_origin_fallback is False # OBO never guesses the origin+ return MCPOAuthMetadata(+ scopes=None,+ authorization_url=None,+ token_url="https://discovered.example.com/token",+ registration_url=None,+ )++ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]++ record = LiteLLM_MCPServerTable(+ server_id="obo-persist-1",+ server_name="obo_persist",+ url="https://example.com/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.oauth2_token_exchange,+ credentials={"client_id": "cid", "client_secret": "csec", "audience": "aud"},+ )++ update_mock = AsyncMock()+ repo_instance = MagicMock()+ repo_instance.table.update = update_mock+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerRepository",+ return_value=repo_instance,+ ),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ ):+ server = await manager.build_mcp_server_from_table(record, credentials_are_encrypted=False)++ assert server.token_url == "https://discovered.example.com/token"+ update_mock.assert_awaited_once()+ assert update_mock.call_args.kwargs["where"] == {"server_id": "obo-persist-1"}+ assert update_mock.call_args.kwargs["data"] == {"token_url": "https://discovered.example.com/token"}++ @pytest.mark.asyncio+ async def test_persist_discovered_obo_token_url_skips_when_not_needed(self):+ """The write-back fires only for an OBO server that discovered a new endpoint: a row that+ already has token_url, a non-OBO auth_type, or a discovery that found nothing all no-op."""+ manager = MCPServerManager()+ update_mock = AsyncMock()+ repo_instance = MagicMock()+ repo_instance.table.update = update_mock++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerRepository",+ return_value=repo_instance,+ ),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ ):+ # already populated -> no write+ await manager._persist_discovered_obo_token_url(+ server_id="s",+ auth_type=MCPAuth.oauth2_token_exchange,+ existing_token_url="https://already.example.com/token",+ discovered_token_url="https://new.example.com/token",+ )+ # not an OBO server -> no write+ await manager._persist_discovered_obo_token_url(+ server_id="s",+ auth_type=MCPAuth.oauth2,+ existing_token_url=None,+ discovered_token_url="https://new.example.com/token",+ )+ # discovery found nothing -> no write+ await manager._persist_discovered_obo_token_url(+ server_id="s",+ auth_type=MCPAuth.oauth2_token_exchange,+ existing_token_url=None,+ discovered_token_url=None,+ )++ update_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_persist_discovered_obo_token_url_is_best_effort(self):+ """A write-back failure must not propagate; discovery just re-runs on the next build."""+ manager = MCPServerManager()+ update_mock = AsyncMock(side_effect=Exception("db unavailable"))+ repo_instance = MagicMock()+ repo_instance.table.update = update_mock++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerRepository",+ return_value=repo_instance,+ ),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ ):+ await manager._persist_discovered_obo_token_url(+ server_id="s",+ auth_type=MCPAuth.oauth2_token_exchange,+ existing_token_url=None,+ discovered_token_url="https://new.example.com/token",+ )++ update_mock.assert_awaited_once()+def test_build_mcp_server_table_preserves_timestamps(self):"""_build_mcp_server_table must use the MCPServer's stored timestamps, not datetime.now()."""manager = MCPServerManager()@@ -5287,9 +5537,7 @@ def _upstream_status_error(status_code: int, challenge: str) -> httpx.HTTPStatusheaders={"WWW-Authenticate": challenge},request=request,)- return httpx.HTTPStatusError(- "upstream rejected token", request=request, response=response- )+ return httpx.HTTPStatusError("upstream rejected token", request=request, response=response)class TestMCPToolsListAuthSurfacing:@@ -5349,9 +5597,7 @@ class TestMCPToolsListAuthSurfacing:)manager = MCPServerManager()- server = MCPServer(- server_id="oauth-srv", name="oauth-srv", transport=MCPTransport.http- )+ server = MCPServer(server_id="oauth-srv", name="oauth-srv", transport=MCPTransport.http)challenge = 'Bearer resource_metadata="/.well-known/oauth-protected-resource/mcp/oauth-srv"'manager._create_mcp_client = AsyncMock(side_effect=HTTPException(@@ -5373,9 +5619,7 @@ class TestMCPToolsListAuthSurfacing:"""A non-auth HTTPException (500) stays absorbed so one misconfigured server cannot blankthe listing; 401/403 are the challenge-class statuses routed to MCPUpstreamAuthError."""manager = MCPServerManager()- server = MCPServer(- server_id="stdio-srv", name="stdio-srv", transport=MCPTransport.http- )+ server = MCPServer(server_id="stdio-srv", name="stdio-srv", transport=MCPTransport.http)manager._create_mcp_client = AsyncMock(side_effect=HTTPException(status_code=500,@@ -5414,6 +5658,8 @@ class TestMCPToolsListAuthSurfacing:result = await manager.list_tools()assert [t.name for t in result] == ["good-do_thing"]++def test_should_strip_caller_authorization_for_token_exchange():"""OBO: the inbound bearer is the subject token (exchanged), never forwarded upstream raw."""server = MCPServer(@@ -5552,5 +5798,118 @@ class TestOBOCallToolRetry:assert first.attempts == 1 and retry.attempts == 1+class TestOBOEndpointDiscovery:+ """An oauth2_token_exchange server with no configured token endpoint discovers it (RFC 9728 ->+ RFC 8414) like the oauth2 flow does; an explicitly configured endpoint skips discovery."""++ @pytest.mark.parametrize(+ "auth_type, endpoint, token_url, expected",+ [+ (MCPAuth.oauth2_token_exchange, None, None, True), # OBO, nothing configured -> discover+ (MCPAuth.oauth2_token_exchange, "https://idp/token", None, False), # endpoint set -> skip+ (MCPAuth.oauth2_token_exchange, None, "https://idp/token", False), # token_url set -> skip+ (MCPAuth.oauth2, None, None, False), # not OBO+ (MCPAuth.none, None, None, False),+ (None, None, None, False),+ ],+ )+ def test_decision(self, auth_type, endpoint, token_url, expected):+ assert MCPServerManager._obo_needs_endpoint_discovery(auth_type, endpoint, token_url) is expected++ @pytest.mark.asyncio+ async def test_config_obo_without_endpoint_discovers_token_endpoint(self):+ manager = MCPServerManager()+ discovered = MCPOAuthMetadata(+ scopes=None,+ authorization_url=None,+ token_url="https://discovered.example.com/token",+ registration_url=None,+ )+ seen = []++ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):+ seen.append((server_url, allow_origin_fallback))+ return discovered++ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]++ await manager.load_servers_from_config(+ {+ "obo": {+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ "auth_type": MCPAuth.oauth2_token_exchange,+ "client_id": "cid",+ "client_secret": "csec",+ }+ }+ )++ server = next(iter(manager.config_mcp_servers.values()))+ # OBO discovery runs, and never guesses the resource origin as the IdP (origin fallback off).+ assert seen == [("https://example.com/mcp", False)]+ # The discovered token endpoint lands on token_url, which _token_exchange_spec reads.+ assert server.token_url == "https://discovered.example.com/token"++ @pytest.mark.asyncio+ async def test_config_obo_with_configured_endpoint_skips_discovery(self):+ manager = MCPServerManager()++ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):+ raise AssertionError("discovery must not run when the endpoint is configured")++ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]++ await manager.load_servers_from_config(+ {+ "obo": {+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ "auth_type": MCPAuth.oauth2_token_exchange,+ "token_exchange_endpoint": "https://configured.example.com/token",+ "client_id": "cid",+ "client_secret": "csec",+ }+ }+ )++ server = next(iter(manager.config_mcp_servers.values()))+ assert server.token_exchange_endpoint == "https://configured.example.com/token"++ @pytest.mark.asyncio+ async def test_descovery_metadata_does_not_guess_origin_when_disallowed(self):+ # The authoritative RFC 9728 -> RFC 8414 chain stays, but with allow_origin_fallback=False the+ # resource origin is never assumed to be the IdP, so no token endpoint is invented.+ manager = MCPServerManager()+ server_url = "https://example.com/public/mcp"+ request = httpx.Request("GET", server_url)+ response_obj = httpx.Response(+ status_code=401, request=request, headers={"WWW-Authenticate": 'Bearer scope="read"'}+ )+ response_obj.raise_for_status = MagicMock(+ side_effect=lambda: (_ for _ in ()).throw(+ httpx.HTTPStatusError("unauthorized", request=request, response=response_obj)+ )+ )+ mock_client = MagicMock()+ mock_client.get = AsyncMock(return_value=response_obj)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.get_async_httpx_client",+ return_value=mock_client,+ ),+ patch.object(manager, "_fetch_oauth_metadata_from_resource", AsyncMock(return_value=([], None))),+ patch.object(manager, "_attempt_well_known_discovery", AsyncMock(return_value=([], None))),+ patch.object(manager, "_fetch_authorization_server_metadata", AsyncMock()) as mock_fetch_auth,+ ):+ result = await manager._descovery_metadata(server_url, allow_origin_fallback=False)++ # No advertised AS -> with the guess disabled, the AS-metadata fetch is never attempted, so no+ # token endpoint is discovered (only the scopes parsed from the challenge survive).+ mock_fetch_auth.assert_not_awaited()+ assert result is None or result.token_url is None++if __name__ == "__main__":pytest.main([__file__])