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-by-default issuer (trust-on-first-use) + stale-clear on url/auth_type change + UI
Tin Chi Lo031922eec648
diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.pyindex ff018a1a021..22c531b5c79 100644--- a/litellm/proxy/_experimental/mcp_server/db.py+++ b/litellm/proxy/_experimental/mcp_server/db.py@@ -698,13 +698,14 @@ async def update_mcp_server(# of being reset to a schema default (transport=sse, allow_all_keys=False...).data_dict = _prepare_mcp_server_data(data, exclude_unset=True, fields_set=fields_set)- # Pre-fetch existing record once if we need it for auth_type or credential logic+ # Pre-fetch existing record once if we need it for auth_type, url, or credential logicexisting = Nonehas_credentials = "credentials" in data_dict and data_dict["credentials"] is not None# An explicit token-exchange column write (set or clear) also migrates the# legacy blob copies below, so the existing row is needed for those updates.explicit_te_write = bool(_TOKEN_EXCHANGE_COLUMN_FIELDS & data_dict.keys())- if data.auth_type or has_credentials or explicit_te_write:+ url_provided = "url" in data_dict and data_dict["url"] is not None+ if data.auth_type or has_credentials or explicit_te_write or url_provided:existing = await MCPServerRepository(prisma_client).table.find_unique(where={"server_id": data.server_id})auth_type_changed = bool(@@ -712,12 +713,15 @@ async def update_mcp_server(and existingand _credential_auth_class(existing.auth_type) != _credential_auth_class(data.auth_type))+ # A url change re-points the server at a potentially different upstream, so any discovered or+ # trust-on-first-use OAuth endpoints/issuer belong to the old upstream and must re-discover.+ url_changed = bool(url_provided and existing and existing.url != data_dict["url"])# Clear stale credentials when auth_type changes but no new credentials providedif auth_type_changed and "credentials" not in data_dict:data_dict["credentials"] = None- if auth_type_changed:+ if auth_type_changed or url_changed:data_dict.update({field: None for field in _AUTH_FLOW_SCOPED_FIELDS if field not in data_dict})# An explicit column write that does not touch credentials must still migratediff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 9c5d3bab5e9..42c9921ecf7 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -1713,6 +1713,7 @@ class MCPServerManager:await self._persist_discovered_oauth_endpoints(server_id=mcp_server.server_id,auth_type=auth_type,+ existing_issuer=manual_issuer,existing_authorization_url=manual_authorization_url,existing_token_url=manual_token_url,existing_scopes=scopes,@@ -1760,6 +1761,7 @@ class MCPServerManager:*,server_id: str,auth_type: MCPAuthType | None,+ existing_issuer: str | None,existing_authorization_url: str | None,existing_token_url: str | None,existing_scopes: list[str] | None,@@ -1782,6 +1784,9 @@ class MCPServerManager:returnif metadata is None or metadata.from_origin_fallback:return+ issuer_update = (+ {"issuer": metadata.discovered_issuer} if metadata.discovered_issuer and not existing_issuer else {}+ )authorization_url_update = ({"authorization_url": metadata.authorization_url}if metadata.authorization_url and not existing_authorization_url@@ -1789,7 +1794,12 @@ class MCPServerManager:)token_url_update = {"token_url": metadata.token_url} if metadata.token_url and not existing_token_url else {}scopes_update = {"credentials": {"scopes": metadata.scopes}} if metadata.scopes and not existing_scopes else {}- updates: dict[str, object] = {**authorization_url_update, **token_url_update, **scopes_update}+ updates: dict[str, object] = {+ **issuer_update,+ **authorization_url_update,+ **token_url_update,+ **scopes_update,+ }if not updates:returnfrom litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 # db.py imports this module at load@@ -3453,6 +3463,7 @@ class MCPServerManager:authorization_url=data.get("authorization_endpoint"),token_url=data.get("token_endpoint"),registration_url=data.get("registration_endpoint"),+ discovered_issuer=claimed_issuer if isinstance(claimed_issuer, str) and claimed_issuer else None,)if any(diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.pyindex c892824fb54..cf3eed20f5b 100644--- a/litellm/types/mcp_server/mcp_server_manager.py+++ b/litellm/types/mcp_server/mcp_server_manager.py@@ -26,6 +26,11 @@ class MCPOAuthMetadata(BaseModel):authorization_url: Optional[str] = Nonetoken_url: Optional[str] = Noneregistration_url: Optional[str] = None+ discovered_issuer: Optional[str] = None+ """The ``issuer`` the authorization-server metadata document self-attests (RFC 8414). Persisted+ trust-on-first-use as the server's ``issuer`` when none is configured, so that later rebuilds+ anchor discovery on it (RFC 8414 §3.3) and a subsequently compromised resource cannot re-point+ it. Never overwrites an admin-configured issuer."""from_origin_fallback: bool = False"""True when the metadata came from guessing the resource origin as its authorizationserver rather than from an RFC 9728/8414-advertised document. Guessed endpoints arediff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_partial_update.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_partial_update.pyindex 41d61c8f508..637ee409fbe 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_partial_update.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_partial_update.py@@ -203,6 +203,7 @@ async def test_auth_type_switch_clears_stale_flow_scoped_fields():data_dict = await _run_update_with_existing(data, existing_auth_type="oauth2")for stale_field in (+ "issuer","authorization_url","token_url","registration_url",@@ -217,6 +218,46 @@ async def test_auth_type_switch_clears_stale_flow_scoped_fields():assert _credentials_cleared(data_dict["credentials"])+async def test_url_change_clears_stale_discovered_oauth_fields():+ """Re-pointing the server url at a potentially different upstream must clear the discovered or+ trust-on-first-use OAuth issuer and endpoints, so the new upstream re-discovers instead of+ anchoring on the previous upstream's issuer (RFC 8414 §3.3 against a stale anchor)."""+ mock_prisma = _mock_prisma()+ existing = MagicMock()+ existing.auth_type = "oauth2"+ existing.url = "https://old.example.com/mcp"+ existing.credentials = None+ mock_prisma.db.litellm_mcpservertable.find_unique = AsyncMock(return_value=existing)++ data = UpdateMCPServerRequest(server_id="my-test-server", url="https://new.example.com/mcp")+ await update_mcp_server(mock_prisma, data, "test-user")+ data_dict = mock_prisma.db.litellm_mcpservertable.update.call_args[1]["data"]++ assert data_dict["url"] == "https://new.example.com/mcp"+ for stale_field in ("issuer", "authorization_url", "token_url", "registration_url"):+ assert data_dict[stale_field] is None, f"{stale_field} must be cleared on url change"+++async def test_unchanged_url_does_not_clear_discovered_oauth_fields():+ """A partial update that resends the same url (or omits it) must not clear the discovered OAuth+ fields, so a routine save does not force needless re-discovery."""+ mock_prisma = _mock_prisma()+ existing = MagicMock()+ existing.auth_type = "oauth2"+ existing.url = "https://same.example.com/mcp"+ existing.credentials = None+ mock_prisma.db.litellm_mcpservertable.find_unique = AsyncMock(return_value=existing)++ data = UpdateMCPServerRequest(server_id="my-test-server", url="https://same.example.com/mcp")+ await update_mcp_server(mock_prisma, data, "test-user")+ data_dict = mock_prisma.db.litellm_mcpservertable.update.call_args[1]["data"]++ for preserved_field in ("issuer", "authorization_url", "token_url", "registration_url"):+ assert preserved_field not in data_dict, f"{preserved_field} must not be cleared when url is unchanged"++@pytest.mark.asyncioasync def test_auth_type_switch_keeps_explicitly_provided_flow_fields():"""Fields explicitly provided alongside the auth_type switch must survive it."""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 58773642692..3dcd05e5936 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@@ -1255,7 +1255,6 @@ class TestMCPServerManager:token_url="https://idp.example.com/token",registration_url="https://idp.example.com/register",scopes=["read", "write"],- authorization_server_scopes=["read", "write"],)resource_rooted = AsyncMock(return_value=MCPOAuthMetadata(token_url="https://attacker.example.com/steal"))with (@@ -5340,6 +5339,7 @@ class TestMCPServerTimestamps:await manager._persist_discovered_oauth_endpoints(server_id="s",auth_type=MCPAuth.api_key,+ existing_issuer=None,existing_authorization_url=None,existing_token_url=None,existing_scopes=None,@@ -5348,6 +5348,7 @@ class TestMCPServerTimestamps:await manager._persist_discovered_oauth_endpoints(server_id="s",auth_type=MCPAuth.oauth2,+ existing_issuer=None,existing_authorization_url=None,existing_token_url=None,existing_scopes=None,@@ -5356,6 +5357,7 @@ class TestMCPServerTimestamps:await manager._persist_discovered_oauth_endpoints(server_id="s",auth_type=MCPAuth.oauth2,+ existing_issuer=None,existing_authorization_url=None,existing_token_url=None,existing_scopes=None,@@ -5364,6 +5366,7 @@ class TestMCPServerTimestamps:await manager._persist_discovered_oauth_endpoints(server_id="s",auth_type=MCPAuth.oauth2,+ existing_issuer=None,existing_authorization_url="https://configured.example.com/authorize",existing_token_url="https://configured.example.com/token",existing_scopes=["configured"],@@ -5389,6 +5392,7 @@ class TestMCPServerTimestamps:await manager._persist_discovered_oauth_endpoints(server_id="s",auth_type=MCPAuth.oauth2,+ existing_issuer=None,existing_authorization_url=None,existing_token_url="https://configured.example.com/token",existing_scopes=None,@@ -5405,6 +5409,46 @@ class TestMCPServerTimestamps:assert persisted.credentials == {"scopes": ["s1"]}assert "token_url" not in persisted.fields_set()+ @pytest.mark.asyncio+ async def test_persist_discovered_oauth_endpoints_writes_discovered_issuer_trust_on_first_use(self):+ """A server with no configured issuer records the discovered issuer trust-on-first-use, so the+ next rebuild anchors discovery on it (RFC 8414 §3.3) instead of re-trusting the resource. When+ an issuer is already set (admin-typed or a prior discovery), it is never overwritten."""+ manager = MCPServerManager()+ metadata = MCPOAuthMetadata(+ authorization_url="https://idp.example.com/authorize",+ token_url="https://idp.example.com/token",+ discovered_issuer="https://idp.example.com",+ )++ update_mcp_server_mock = AsyncMock()+ with (+ patch("litellm.proxy._experimental.mcp_server.db.update_mcp_server", new=update_mcp_server_mock),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ ):+ await manager._persist_discovered_oauth_endpoints(+ server_id="s",+ auth_type=MCPAuth.oauth2,+ existing_issuer=None,+ existing_authorization_url=None,+ existing_token_url=None,+ existing_scopes=None,+ metadata=metadata,+ )+ await manager._persist_discovered_oauth_endpoints(+ server_id="s",+ auth_type=MCPAuth.oauth2,+ existing_issuer="https://admin-configured.example.com",+ existing_authorization_url="https://admin-configured.example.com/authorize",+ existing_token_url="https://admin-configured.example.com/token",+ existing_scopes=["cfg"],+ metadata=metadata,+ )++ assert update_mcp_server_mock.await_count == 1+ persisted = update_mcp_server_mock.call_args.kwargs["data"]+ assert persisted.issuer == "https://idp.example.com"+@pytest.mark.asyncioasync def test_build_mcp_server_from_table_skips_persistence_for_temporary_servers(self):"""The session endpoint builds temporary servers whose server_id has no DB row; withdiff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsxindex fc72981edd0..76e4342f52e 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/OAuthFormFields.tsx@@ -167,6 +167,17 @@ const OAuthFormFields: React.FC<OAuthFormFieldsProps> = ({><Select mode="tags" tokenSeparators={[","]} placeholder="Add scopes" className="rounded-lg" size="large" /></Form.Item>+ <Form.Item+ label={+ <FieldLabel+ label="Issuer (optional)"+ tooltip="OAuth 2.0 authorization server issuer (RFC 8414). Auto-discovered from the upstream on first connect; set it explicitly to pin the trust anchor so token and scope discovery is fetched from and validated against this issuer (RFC 8414 §3.3) instead of anything the resource advertises."+ />+ }+ name="issuer"+ >+ <TextInput placeholder="https://issuer.example.com" className={fieldClassName} />+ </Form.Item><Form.Itemlabel={<FieldLabeldiff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/create_mcp_server.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/create_mcp_server.tsxindex 70838c592c8..9f7639d00c7 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/create_mcp_server.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/create_mcp_server.tsx@@ -210,6 +210,7 @@ const CreateMCPServer: React.FC<CreateMCPServerProps> = ({credentials: isClientForwardedTokenMode(values.auth_type)? preservedDeclaredAppCredentials(values.credentials): { ...((values.credentials as Record<string, unknown> | undefined) ?? {}), ...(dcrClientRef.current ?? {}) },+ issuer: values.issuer,authorization_url: values.authorization_url,token_url: values.token_url,registration_url: values.registration_url,@@ -759,7 +760,7 @@ const CreateMCPServer: React.FC<CreateMCPServerProps> = ({if ("credentials" in changedValues) {setAppMayNotMatchUpstream(false);} else {- const upstreamChanged = ["url", "spec_path", "authorization_url", "token_url", "registration_url"].some(+ const upstreamChanged = ["url", "spec_path", "issuer", "authorization_url", "token_url", "registration_url"].some((key) => key in changedValues,);const hasDeclaredApp = preservedDeclaredAppCredentials(form.getFieldValue("credentials")) !== undefined;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_edit.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_edit.tsxindex 455fe69455d..8646ab192c9 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_edit.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_edit.tsx@@ -117,6 +117,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({const currentAuthType = Form.useWatch("auth_type", form);const currentStaticHeaders = Form.useWatch("static_headers", form);const currentCredentials = Form.useWatch("credentials", form);+ const currentIssuer = Form.useWatch("issuer", form);const currentAuthorizationUrl = Form.useWatch("authorization_url", form);const currentTokenUrl = Form.useWatch("token_url", form);const currentRegistrationUrl = Form.useWatch("registration_url", form);@@ -471,7 +472,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({if ("credentials" in changedValues) {setAppMayNotMatchUpstream(false);} else {- const upstreamChanged = ["url", "spec_path", "authorization_url", "token_url", "registration_url"].some(+ const upstreamChanged = ["url", "spec_path", "issuer", "authorization_url", "token_url", "registration_url"].some((key) => key in changedValues,);const hasDeclaredApp = preservedDeclaredAppCredentials(form.getFieldValue("credentials")) !== undefined;@@ -517,6 +518,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({transport: rawTransport === TRANSPORT.OPENAPI ? TRANSPORT.HTTP : rawTransport,auth_type: AUTH_TYPE.OAUTH2,oauth2_flow: MCP_OAUTH2_FLOW_INTERACTIVE,+ issuer: values.issuer,authorization_url: values.authorization_url,token_url: values.token_url,registration_url: values.registration_url,@@ -636,6 +638,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({spec_path: undefined,auth_type: undefined,credentials: undefined,+ issuer: undefined,authorization_url: undefined,token_url: undefined,registration_url: undefined,@@ -845,7 +848,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({stdio_config: undefined,env_json: undefined,...(mcpServer.auth_type === AUTH_TYPE.OAUTH2 && restValues.auth_type !== AUTH_TYPE.OAUTH2- ? { authorization_url: null, token_url: null, registration_url: null }+ ? { issuer: null, authorization_url: null, token_url: null, registration_url: null }: {}),...(mcpServer.auth_type === AUTH_TYPE.OAUTH2_TOKEN_EXCHANGE &&restValues.auth_type !== AUTH_TYPE.OAUTH2_TOKEN_EXCHANGE@@ -1301,6 +1304,22 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({size="large"/></Form.Item>+ <Form.Item+ label={+ <span className="text-sm font-medium text-gray-700 flex items-center">+ Issuer (optional)+ <Tooltip title="OAuth 2.0 authorization server issuer (RFC 8414). Auto-discovered on first connect; set it explicitly to pin the trust anchor so token and scope discovery is fetched from and validated against this issuer (RFC 8414 §3.3) instead of anything the resource advertises.">+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />+ </Tooltip>+ </span>+ }+ name="issuer"+ >+ <Input+ placeholder="https://issuer.example.com"+ className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"+ />+ </Form.Item><Form.Itemlabel={<span className="text-sm font-medium text-gray-700 flex items-center">@@ -1588,6 +1607,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({oauthFlowTypeValue ?? oauth2FlowToFormValue(mcpServer.oauth2_flow) ?? OAUTH_FLOW.INTERACTIVE,static_headers: currentStaticHeaders ?? mcpServer.static_headers,credentials: currentCredentials,+ issuer: currentIssuer ?? mcpServer.issuer,authorization_url: currentAuthorizationUrl ?? mcpServer.authorization_url,token_url: currentTokenUrl ?? mcpServer.token_url,registration_url: currentRegistrationUrl ?? mcpServer.registration_url,diff --git a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx b/ui/litellm-dashboard/src/components/mcp_tools/types.tsxindex 04766aad7b4..dd7ed2bfbe4 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/types.tsx@@ -81,6 +81,7 @@ export const getOAuthAuthorizationIdentity = (values: Record<string, unknown>):client_id: credentials.client_id ?? null,client_secret: credentials.client_secret ?? null,scopes: credentials.scopes ?? null,+ issuer: values.issuer ?? null,authorization_url: values.authorization_url ?? null,token_url: values.token_url ?? null,registration_url: values.registration_url ?? null,@@ -341,6 +342,7 @@ export interface MCPServer {transport?: string | null;auth_type?: string | null;oauth2_flow?: string | null;+ issuer?: string | null;authorization_url?: string | null;token_url?: string | null;registration_url?: string | null;