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): reject discovered token endpoints uncorroborated by the manual authorization_url

Tin Chi Loa81c6ce350c2
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index fda6ae9bef5..284bf6a0926 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -213,6 +213,57 @@ def _carry_forward_resolved_oauth_endpoints(new_server: MCPServer, previous_serv
new_server.scopes = previous_server.scopes
+def _normalized_authorize_endpoint(url: str) -> str:
+ parsed = urlparse(url)
+ return f"{parsed.scheme.lower()}://{parsed.netloc.lower()}{parsed.path.rstrip('/')}"
+
+
+def _gate_discovered_endpoints_against_manual_authorization_url(
+ metadata: MCPOAuthMetadata | None,
+ manual_authorization_url: str | None,
+ server_identifier: str,
+ is_dcr_bridge: bool,
+) -> MCPOAuthMetadata | None:
+ """Refuse discovered token/registration endpoints the pinned authorize endpoint cannot vouch for.
+
+ Discovery is rooted at the MCP resource (RFC 9728), so a compromised upstream can advertise an
+ attacker-run authorization server. When the admin manually configured ``authorization_url``,
+ filling a blank ``token_url`` from that advertisement recreates the RFC 9700 mix-up attack at
+ configuration time: users sign in at the trusted authorize endpoint while the gateway redeems
+ the code, with the stored client secret and PKCE verifier, at the attacker's token endpoint.
+ Endpoints from one metadata document are only trustworthy together, so the discovered
+ ``token_url`` and ``registration_url`` are accepted only when that same document's
+ ``authorization_endpoint`` matches the pinned value (scheme+host+path; query and trailing slash
+ are not identity). Scope discovery stays ungated: scopes steer the redirect to the trusted
+ authorize endpoint and carry no credentials.
+ """
+ if metadata is None or not manual_authorization_url:
+ return metadata
+ if not metadata.token_url and not metadata.registration_url:
+ return metadata
+ if metadata.authorization_url and _normalized_authorize_endpoint(
+ manual_authorization_url
+ ) == _normalized_authorize_endpoint(metadata.authorization_url):
+ return metadata
+ bridge_note = (
+ " The discovered registration_url is rejected with it, so this dcr_bridge server stays on the"
+ " short-circuit registration arm."
+ if is_dcr_bridge and metadata.registration_url
+ else ""
+ )
+ verbose_logger.warning(
+ "MCP OAuth discovery for server %s advertised authorization_endpoint %s, which does not match the "
+ "manually configured authorization_url %s; rejecting the discovered token_url/registration_url so "
+ "authorization codes and client credentials only go to endpoints vouched for by the configured "
+ "authorization server. Configure Token URL manually if the mismatch is intentional.%s",
+ server_identifier,
+ _normalized_authorize_endpoint(metadata.authorization_url) if metadata.authorization_url else "<absent>",
+ _normalized_authorize_endpoint(manual_authorization_url),
+ bridge_note,
+ )
+ return metadata.model_copy(update={"token_url": None, "registration_url": None})
+
+
def invalidate_user_env_vars_cache(user_id: str, server_id: str) -> None:
"""Drop a cached entry after the user stores or clears their env var values
so the next request reads the fresh value instead of a stale one."""
@@ -1041,20 +1092,31 @@ class MCPServerManager:
else:
mcp_oauth_metadata = None
+ gated_oauth_metadata = (
+ _gate_discovered_endpoints_against_manual_authorization_url(
+ mcp_oauth_metadata,
+ server_config.get("authorization_url"),
+ server_name or server_id,
+ bool(server_config.get("dcr_bridge")),
+ )
+ if auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES
+ else mcp_oauth_metadata
+ )
+
# Filter blank scopes (e.g. YAML ``scopes: [""]``) the same way the DB-build path does, so
# an all-blank list normalizes to None rather than a ``("",)`` tuple that skips the
# entra_obo fail-closed scope precondition and POSTs an empty scope to the IdP.
resolved_scopes = self._extract_scopes(server_config.get("scopes")) or (
- mcp_oauth_metadata.scopes if mcp_oauth_metadata else None
+ gated_oauth_metadata.scopes if gated_oauth_metadata else None
)
resolved_authorization_url = server_config.get("authorization_url") or (
- mcp_oauth_metadata.authorization_url if mcp_oauth_metadata else None
+ gated_oauth_metadata.authorization_url if gated_oauth_metadata else None
)
resolved_token_url = server_config.get("token_url") or (
- mcp_oauth_metadata.token_url if mcp_oauth_metadata else None
+ gated_oauth_metadata.token_url if gated_oauth_metadata else None
)
resolved_registration_url = server_config.get("registration_url") or (
- mcp_oauth_metadata.registration_url if mcp_oauth_metadata else None
+ gated_oauth_metadata.registration_url if gated_oauth_metadata else None
)
config_oauth2_flow = server_config.get("oauth2_flow", None)
@@ -1472,8 +1534,18 @@ class MCPServerManager:
mcp_server.server_id,
server_url,
)
+ gated_oauth_metadata = (
+ _gate_discovered_endpoints_against_manual_authorization_url(
+ mcp_oauth_metadata,
+ mcp_server.authorization_url,
+ mcp_server.server_id,
+ bool(getattr(mcp_server, "dcr_bridge", None)),
+ )
+ if auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES
+ else mcp_oauth_metadata
+ )
- resolved_scopes = scopes or (mcp_oauth_metadata.scopes if mcp_oauth_metadata else None)
+ resolved_scopes = scopes or (gated_oauth_metadata.scopes if gated_oauth_metadata else None)
new_server = MCPServer(
server_id=mcp_server.server_id,
@@ -1493,9 +1565,9 @@ class MCPServerManager:
client_secret=client_secret_value or getattr(mcp_server, "client_secret", None),
oauth2_flow=self._explicit_oauth2_flow(getattr(mcp_server, "oauth2_flow", None)),
scopes=resolved_scopes,
- authorization_url=mcp_server.authorization_url or getattr(mcp_oauth_metadata, "authorization_url", None),
- token_url=mcp_server.token_url or getattr(mcp_oauth_metadata, "token_url", None),
- registration_url=mcp_server.registration_url or getattr(mcp_oauth_metadata, "registration_url", None),
+ authorization_url=mcp_server.authorization_url or getattr(gated_oauth_metadata, "authorization_url", None),
+ token_url=mcp_server.token_url or getattr(gated_oauth_metadata, "token_url", None),
+ registration_url=mcp_server.registration_url or getattr(gated_oauth_metadata, "registration_url", None),
token_endpoint_auth_method=(
credentials_dict.get("token_endpoint_auth_method") if credentials_dict else None
),
@@ -1555,7 +1627,7 @@ class MCPServerManager:
existing_authorization_url=mcp_server.authorization_url,
existing_token_url=mcp_server.token_url,
existing_scopes=scopes,
- metadata=mcp_oauth_metadata,
+ metadata=gated_oauth_metadata,
)
return new_server
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 6af86b9bda3..8091675090e 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
@@ -356,6 +356,55 @@ class TestMCPServerManager:
assert server.oauth2_flow == "authorization_code"
assert server.needs_user_oauth_token is True
+ @pytest.mark.asyncio
+ async def test_load_servers_from_config_rejects_discovered_token_url_on_authorization_endpoint_mismatch(self):
+ """The config loader always runs discovery and or-merges per field, so a yaml server with a
+ manual authorization_url has the same config-time mix-up exposure as a DB row: a discovered
+ token_url from a document advertising a different authorize endpoint must not be combined
+ with the pinned one. Scopes still backfill."""
+ manager = MCPServerManager()
+
+ metadata = MCPOAuthMetadata(
+ authorization_url="https://attacker.example.com/authorize",
+ token_url="https://attacker.example.com/token",
+ scopes=["read"],
+ )
+ config = self._oauth2_config(
+ oauth2_flow="authorization_code",
+ authorization_url="https://idp.example.com/authorize",
+ token_url=None,
+ )
+ with patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=metadata)):
+ await manager.load_servers_from_config(config)
+
+ server = next(iter(manager.config_mcp_servers.values()))
+ assert server.authorization_url == "https://idp.example.com/authorize"
+ assert server.token_url is None
+ assert server.scopes == ["read"]
+
+ @pytest.mark.asyncio
+ async def test_load_servers_from_config_fills_token_url_when_metadata_corroborates_manual_authorization_url(self):
+ """Corroborated metadata keeps the self-heal on the config path: when the discovered
+ document advertises the same authorize endpoint the admin pinned, its token_url fills the
+ blank field."""
+ manager = MCPServerManager()
+
+ metadata = MCPOAuthMetadata(
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ scopes=["read"],
+ )
+ config = self._oauth2_config(
+ oauth2_flow="authorization_code",
+ authorization_url="https://idp.example.com/authorize/",
+ token_url=None,
+ )
+ with patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=metadata)):
+ await manager.load_servers_from_config(config)
+
+ server = next(iter(manager.config_mcp_servers.values()))
+ assert server.token_url == "https://idp.example.com/token"
+
@pytest.mark.asyncio
async def test_load_servers_from_config_non_oauth2_needs_no_flow(self):
manager = MCPServerManager()
@@ -1056,7 +1105,9 @@ class TestMCPServerManager:
async def test_build_from_table_discovers_scopes_when_authorization_url_is_manual(self):
"""An admin-typed authorization_url must not switch off discovery for the fields left
blank: without the scopes_supported backfill the authorize redirect goes out scope-less
- and IdPs like Google hard-fail it with 400 "Missing required parameter: scope"."""
+ and IdPs like Google hard-fail it with 400 "Missing required parameter: scope". Scope
+ backfill works even when the advertised authorization_endpoint differs from the manual
+ value, because scopes only steer the redirect to the trusted authorize endpoint."""
manager = MCPServerManager()
row = LiteLLM_MCPServerTable(
server_id="manual-auth-url-1",
@@ -1081,9 +1132,90 @@ class TestMCPServerManager:
mock_discovery.assert_awaited_once()
assert built.authorization_url == "https://idp.example.com/manual-authorize"
- assert built.token_url == "https://idp.example.com/token"
+ assert built.token_url is None
assert built.scopes == ["calendar.read", "calendar.write"]
+ @pytest.mark.asyncio
+ async def test_build_from_table_fills_endpoints_when_metadata_corroborates_manual_authorization_url(self):
+ """A discovered token_url is only trusted next to a manual authorization_url when the same
+ metadata document advertises that authorize endpoint, and the comparison must tolerate
+ formatting-only differences (host case, trailing slash, query params like ?prompt=consent)
+ so hand-copied URLs still self-heal."""
+ manager = MCPServerManager()
+ row = LiteLLM_MCPServerTable(
+ server_id="manual-auth-url-2",
+ alias="manual_auth_url_match",
+ description="manual authorization_url matching discovery, blank token_url",
+ url="https://up.example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ authorization_url="https://IDP.example.com/authorize/?prompt=consent",
+ created_at=datetime.now(),
+ updated_at=datetime.now(),
+ )
+
+ metadata = MCPOAuthMetadata(
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ registration_url="https://idp.example.com/register",
+ scopes=["read"],
+ )
+ with patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=metadata)):
+ built = await manager.build_mcp_server_from_table(row, credentials_are_encrypted=False)
+
+ assert built.authorization_url == "https://IDP.example.com/authorize/?prompt=consent"
+ assert built.token_url == "https://idp.example.com/token"
+ assert built.registration_url == "https://idp.example.com/register"
+ assert built.scopes == ["read"]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "advertised_authorization_url",
+ ["https://attacker.example.com/authorize", None],
+ )
+ async def test_build_from_table_rejects_discovered_token_url_on_authorization_endpoint_mismatch(
+ self, advertised_authorization_url
+ ):
+ """Resource-rooted discovery lets a compromised upstream advertise its own authorization
+ server. With a manual authorization_url pinned, accepting that document's token_url would
+ send the authorization code, stored client secret, and PKCE verifier to the attacker's
+ token endpoint (config-time RFC 9700 mix-up), and the persist hook would make the hostile
+ endpoint durable. Both the in-memory merge and the persisted metadata must drop the
+ uncorroborated token_url and registration_url."""
+ manager = MCPServerManager()
+ row = LiteLLM_MCPServerTable(
+ server_id="manual-auth-url-3",
+ alias="manual_auth_url_mismatch",
+ description="manual authorization_url, hostile discovery document",
+ url="https://up.example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ authorization_url="https://idp.example.com/authorize",
+ created_at=datetime.now(),
+ updated_at=datetime.now(),
+ )
+
+ metadata = MCPOAuthMetadata(
+ authorization_url=advertised_authorization_url,
+ token_url="https://attacker.example.com/token",
+ registration_url="https://attacker.example.com/register",
+ scopes=["read"],
+ )
+ with (
+ patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=metadata)),
+ patch.object(manager, "_persist_discovered_oauth_endpoints", new=AsyncMock()) as mock_persist,
+ ):
+ built = await manager.build_mcp_server_from_table(row, credentials_are_encrypted=False)
+
+ assert built.authorization_url == "https://idp.example.com/authorize"
+ assert built.token_url is None
+ assert built.registration_url is None
+ assert built.scopes == ["read"]
+ persisted_metadata = mock_persist.await_args.kwargs["metadata"]
+ assert persisted_metadata.token_url is None
+ assert persisted_metadata.registration_url is None
+ assert persisted_metadata.scopes == ["read"]
+
@pytest.mark.asyncio
async def test_build_from_table_skips_discovery_when_all_upstream_oauth_fields_present(self):
"""A fully hand-configured server (authorization_url, token_url, and scopes all set) has
@@ -2310,6 +2442,10 @@ class TestMCPServerManager:
@pytest.mark.asyncio
async def test_load_servers_from_config_overrides_discovery_metadata(self):
+ """Config values win per field. The discovered token_url/registration_url do NOT fill the
+ blanks here: the document advertises a different authorization_endpoint than the manually
+ configured one, so combining its endpoints with the pinned authorize URL would be the
+ config-time mix-up the discovery gate exists to prevent."""
manager = MCPServerManager()
discovered_metadata = MCPOAuthMetadata(
@@ -2343,8 +2479,8 @@ class TestMCPServerManager:
server = next(iter(manager.config_mcp_servers.values()))
assert server.scopes == ["config"] # config overrides discovery
assert server.authorization_url == "https://config.example.com/auth"
- assert server.token_url == "https://discovered.example.com/token"
- assert server.registration_url == "https://discovered.example.com/register"
+ assert server.token_url is None
+ assert server.registration_url is None
@pytest.mark.asyncio
async def test_load_servers_from_config_filters_blank_scopes(self):