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): mint an ephemeral OAuth client when passthrough authorize has no client_id
Tin Chi Loc6a0ad542459
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex 9a1b5cf4864..ee3196b539c 100644--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@ -3,6 +3,7 @@ import html as _htmlimport jsonimport secretsimport time+from collections.abc import Mappingfrom datetime import datetime, timezonefrom typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Tuplefrom urllib.parse import parse_qsl, urlencode, urlparse, urlunparse@@ -13,6 +14,7 @@ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Respfrom pydantic import BaseModel, ConfigDict, Field, SecretStr, ValidationErrorfrom litellm._logging import verbose_logger+from litellm.caching.in_memory_cache import InMemoryCachefrom litellm.llms.custom_httpx.http_handler import (get_async_httpx_client,httpxSpecialProvider,@@ -20,7 +22,9 @@ from litellm.llms.custom_httpx.http_handler import (from litellm.proxy._experimental.mcp_server.auth.token_endpoint_auth import (TokenEndpointAuthConfigError,build_token_endpoint_client_auth,+ normalize_token_endpoint_auth_method,)+from litellm.types.mcp_server.mcp_server_manager import MCPTokenEndpointAuthMethodfrom litellm.proxy._experimental.mcp_server.bridge_token_flow import (_bridge_mint_error_response,_BridgeMintReady,@@ -111,6 +115,9 @@ def encode_state_with_base_url(client_redirect_uri: Optional[str] = None,litellm_user_id: str | None = None,mcp_server_id: str | None = None,+ dcr_client_id: str | None = None,+ dcr_client_secret: str | None = None,+ dcr_token_endpoint_auth_method: MCPTokenEndpointAuthMethod | None = None,) -> str:"""Encode the base_url, original state, and PKCE parameters using encryption.@@ -124,8 +131,18 @@ def encode_state_with_base_url(litellm_user_id: The SSO-authenticated litellm user captured at the bridge authorize(interactive dcr_bridge oauth_delegate only); the callback seals it into the gatewayauthorization code so the token mint can bind the envelope to this user- mcp_server_id: The bridge server the interactive flow targets, sealed alongside- litellm_user_id so the gateway code cannot be replayed against another server+ mcp_server_id: The server the flow targets, sealed alongside litellm_user_id (bridge) or+ dcr_client_id (ephemeral mint) so the gateway code cannot be replayed against another+ server+ dcr_client_id: The ephemeral DCR client the gateway minted at authorize for a+ client-forwarded-token server with no caller-supplied client; the callback seals it+ into the forwarded authorization code so the token exchange can authenticate with it+ while the gateway stores nothing+ dcr_client_secret: The minted client's secret, when the upstream issued one+ dcr_token_endpoint_auth_method: The token-endpoint auth method the upstream's registration+ response granted the minted client, sealed alongside the credentials so the exchange+ authenticates the way the upstream expects instead of falling back to the server row's+ configured methodReturns:An encrypted string that encodes all values@@ -138,6 +155,9 @@ def encode_state_with_base_url("client_redirect_uri": client_redirect_uri,"litellm_user_id": litellm_user_id,"mcp_server_id": mcp_server_id,+ "dcr_client_id": dcr_client_id,+ "dcr_client_secret": dcr_client_secret,+ "dcr_token_endpoint_auth_method": dcr_token_endpoint_auth_method,}state_json = json.dumps(state_data, sort_keys=True)encrypted_state = encrypt_value_helper(state_json)@@ -217,6 +237,93 @@ def open_bridge_authorization_code(code: str) -> _BridgeAuthorizationCode | Nonereturn None+_PASSTHROUGH_AUTH_CODE_PREFIX = "llm_ptcode_"+++class PassthroughAuthorizationCode(BaseModel):+ """The ephemeral DCR client and upstream code the gateway seals into the authorization code it+ forwards for a client-forwarded-token server (``true_passthrough`` / ``oauth_delegate``) whose+ authorize fell through to gateway-side registration. These modes forbid the gateway from storing+ an OAuth client identity, so the minted client survives only inside this sealed value: the+ client echoes it back at the token endpoint, where the gateway recovers the client to+ authenticate the upstream exchange. ``mcp_server_id`` binds the code to the server it was minted+ for so it cannot be spent at another server's token endpoint."""++ model_config = ConfigDict(frozen=True)+ upstream_code: str = Field(min_length=1)+ client_id: str = Field(min_length=1)+ client_secret: str | None = None+ token_endpoint_auth_method: MCPTokenEndpointAuthMethod | None = None+ mcp_server_id: str = Field(min_length=1)+++def seal_passthrough_authorization_code(+ upstream_code: str,+ client_id: str,+ client_secret: str | None,+ mcp_server_id: str,+ token_endpoint_auth_method: MCPTokenEndpointAuthMethod | None = None,+) -> str:+ """Seal the upstream authorization code together with the ephemeral DCR client that authorized+ it. Encrypted with the same authenticated symmetric helper as the OAuth state and bridge codes,+ so the client can neither read the (possibly confidential) client credentials nor forge a+ code."""+ payload = json.dumps(+ {+ "upstream_code": upstream_code,+ "client_id": client_id,+ "client_secret": client_secret,+ "token_endpoint_auth_method": token_endpoint_auth_method,+ "mcp_server_id": mcp_server_id,+ },+ sort_keys=True,+ )+ return _PASSTHROUGH_AUTH_CODE_PREFIX + encrypt_value_helper(payload)+++def open_passthrough_authorization_code(code: str) -> PassthroughAuthorizationCode | None:+ """Recover the sealed ephemeral client and upstream code, or ``None`` when ``code`` is not a+ gateway passthrough code or does not decrypt / validate, so a raw upstream code falls through to+ the existing caller-supplied-client behavior."""+ if not code.startswith(_PASSTHROUGH_AUTH_CODE_PREFIX):+ return None+ decrypted = decrypt_value_helper(+ code[len(_PASSTHROUGH_AUTH_CODE_PREFIX) :], "passthrough_authorization_code", return_original_value=False+ )+ if not isinstance(decrypted, str):+ return None+ try:+ return PassthroughAuthorizationCode.model_validate_json(decrypted)+ except ValidationError:+ return None+++def redeem_passthrough_authorization_code(+ code: str | None, mcp_server: MCPServer, code_verifier: str | None+) -> PassthroughAuthorizationCode | None:+ """The single redemption gate for sealed passthrough codes: a raw or foreign code returns+ ``None`` so the caller keeps its existing behavior, while a genuine sealed code must be spent+ at the server it was minted for and must carry the PKCE verifier of the S256 flow that minted+ it (the mint refuses downgraded flows, so a verifier-less redemption is an interception+ attempt, not a legitimate client)."""+ if not code:+ return None+ sealed = open_passthrough_authorization_code(code)+ if sealed is None:+ return None+ if sealed.mcp_server_id != mcp_server.server_id:+ raise HTTPException(+ status_code=400,+ detail="Authorization code was issued for a different MCP server",+ )+ if not code_verifier:+ raise HTTPException(+ status_code=400,+ detail="code_verifier is required to redeem this authorization code",+ )+ return sealed++def _redirect_to_litellm_login(request: Request) -> RedirectResponse:"""Send an unauthenticated browser through litellm login before the interactive bridge authorizecan capture its identity. The bridge oauth_delegate flow seals the SSO user into the gateway code,@@ -594,6 +701,7 @@ async def authorize_with_server(code_challenge_method: Optional[str] = None,response_type: Optional[str] = None,scope: Optional[str] = None,+ ephemeral_dcr_client: "EphemeralDcrClient | None" = None,):_raise_if_not_oauth2(mcp_server)if mcp_server.authorization_url is None:@@ -612,7 +720,10 @@ async def authorize_with_server(# calling this for its enforcement side effect, then falls through to the gateway# /callback flow below, which reads the original code_challenge names.bridge_challenge, bridge_method = _require_s256_pkce(code_challenge, code_challenge_method)- if _dcr_bridge_relays_client_registration(mcp_server):+ # A gateway-minted ephemeral client is registered against {base}/callback, so its+ # flow must run the short-circuit arm; the relay arm is only for clients that+ # registered themselves through the front door and hold their own redirect binding.+ if _dcr_bridge_relays_client_registration(mcp_server) and ephemeral_dcr_client is None:return _redirect_to_upstream_authorize(mcp_server=mcp_server,client_id=client_id,@@ -656,7 +767,12 @@ async def authorize_with_server(code_challenge_method=code_challenge_method,client_redirect_uri=redirect_uri,litellm_user_id=litellm_user_id,- mcp_server_id=mcp_server.server_id if litellm_user_id else None,+ mcp_server_id=mcp_server.server_id if (litellm_user_id or ephemeral_dcr_client) else None,+ dcr_client_id=ephemeral_dcr_client.client_id if ephemeral_dcr_client else None,+ dcr_client_secret=ephemeral_dcr_client.client_secret if ephemeral_dcr_client else None,+ dcr_token_endpoint_auth_method=ephemeral_dcr_client.token_endpoint_auth_method+ if ephemeral_dcr_client+ else None,)relay_state = secrets.token_urlsafe(_OAUTH_STATE_HANDLE_BYTES)@@ -703,6 +819,7 @@ async def exchange_token_with_server(code_verifier: Optional[str],refresh_token: Optional[str] = None,scope: Optional[str] = None,+ client_token_endpoint_auth_method: MCPTokenEndpointAuthMethod | None = None,):_raise_if_not_oauth2(mcp_server)if grant_type not in ("authorization_code", "refresh_token"):@@ -718,15 +835,24 @@ async def exchange_token_with_server(),)- # The id and secret must come from the same source. When the server-side client_id wins,- # falling back to the caller's secret pairs the persisted client with a foreign secret; the- # register short-circuit hands clients a placeholder secret ("dummy"), so a re-auth against a- # persisted public PKCE client (no stored secret) would send that placeholder and the IdP 401s.+ # The id, secret, and token-endpoint auth method must come from the same source. When the+ # server-side client_id wins, falling back to the caller's secret pairs the persisted client+ # with a foreign secret; the register short-circuit hands clients a placeholder secret+ # ("dummy"), so a re-auth against a persisted public PKCE client (no stored secret) would send+ # that placeholder and the IdP 401s. Symmetrically, a caller-side client (an ephemeral mint+ # recovered from a sealed code) must authenticate the way its own registration was granted,+ # not the way the server row is configured; callers that carry no method keep the row's method+ # as before.resolved_client_id = mcp_server.client_id if mcp_server.client_id else client_idresolved_client_secret = mcp_server.client_secret if mcp_server.client_id else client_secret+ resolved_auth_method = (+ mcp_server.token_endpoint_auth_method+ if mcp_server.client_id+ else (client_token_endpoint_auth_method or mcp_server.token_endpoint_auth_method)+ )try:client_auth = build_token_endpoint_client_auth(- auth_method=mcp_server.token_endpoint_auth_method,+ auth_method=resolved_auth_method,client_id=resolved_client_id,client_secret=resolved_client_secret,)@@ -1229,7 +1355,7 @@ async def _persist_dcr_client_registration(return "failed"-def _client_supplied_redirect_uris(value: object) -> list[str] | None:+def client_supplied_redirect_uris(value: object) -> list[str] | None:"""RFC 7591 redirect_uris must be a non-empty array of URI strings. Any other shape (not a list,an empty list, or a list holding a non-string or empty-string element) yields None so everyregister arm falls back to the gateway callback instead of echoing a malformed value back to the@@ -1241,6 +1367,142 @@ def _client_supplied_redirect_uris(value: object) -> list[str] | None:return uris if len(uris) == len(value) else None+async def _post_dcr_registration(+ registration_url: str,+ register_data: Mapping[str, object],+ server_id: str,+) -> httpx.Response:+ """POST an RFC 7591 registration to the upstream and return its response, relaying a classified+ upstream rejection instead of a generic 500 and failing loud on an absent response."""+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+ async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Register)+ try:+ response = await async_client.post(+ registration_url,+ headers=headers,+ json=register_data,+ )+ if response is not None:+ response.raise_for_status()+ except httpx.HTTPStatusError as exc:+ status_code, detail = dcr_fault_detail(classify_upstream_dcr_rejection(exc.response, log_context=server_id))+ raise HTTPException(status_code=status_code, detail=detail) from exc+ if response is None:+ raise HTTPException(+ status_code=502,+ detail="MCP upstream registration endpoint returned no response",+ )+ return response+++class EphemeralDcrClient(BaseModel):+ """A DCR client minted for a single authorize round trip and never stored by the gateway."""++ model_config = ConfigDict(frozen=True)+ client_id: str = Field(min_length=1)+ client_secret: str | None = None+ token_endpoint_auth_method: MCPTokenEndpointAuthMethod | None = None+++_EPHEMERAL_DCR_CLIENT_CACHE = InMemoryCache(default_ttl=_OAUTH_STATE_COOKIE_TTL_SECONDS)+_EPHEMERAL_DCR_MINT_LOCKS: dict[str, asyncio.Lock] = {}+++async def mint_ephemeral_dcr_client(request: Request, mcp_server: MCPServer) -> EphemeralDcrClient | None:+ """Mint a throwaway OAuth client via the upstream's RFC 7591 registration endpoint for a+ client-forwarded-token server whose authorize arrived with no client_id. Returns ``None`` when+ the upstream exposes no registration endpoint, so the caller keeps its existing failure path.+ The minted client is deliberately not persisted anywhere: ``true_passthrough`` /+ ``oauth_delegate`` require the gateway to hold no OAuth client identity, so it survives only in+ the encrypted OAuth state and the sealed authorization code the callback forwards.++ Reloading the authorize page or retrying a flow must not register a fresh upstream client every+ time (an OAuth client identifies the application, not the user, so reuse is semantically+ correct). A per-process TTL cache bounded to the OAuth state cookie's lifetime dedupes the mint+ per (server, gateway origin), and a per-server lock single-flights concurrent mints (the+ ``_OAUTH_METADATA_FETCH_LOCKS`` pattern; keyed by server_id alone so the lock registry stays+ bounded by the server count even when the request origin varies) so parallel authorize requests+ cannot each register an upstream client; the cache stamps nothing onto the server record and+ correctness never depends on it because the sealed state carries the client through the flow."""+ if mcp_server.registration_url is None:+ return None+ request_base_url = get_request_base_url(request)+ cache_key = f"mcp_ephemeral_dcr_client:{mcp_server.server_id}:{request_base_url}"+ cached = _EPHEMERAL_DCR_CLIENT_CACHE.get_cache(cache_key)+ if isinstance(cached, EphemeralDcrClient):+ return cached+ lock = _EPHEMERAL_DCR_MINT_LOCKS.setdefault(mcp_server.server_id, asyncio.Lock())+ async with lock:+ cached_after_wait = _EPHEMERAL_DCR_CLIENT_CACHE.get_cache(cache_key)+ if isinstance(cached_after_wait, EphemeralDcrClient):+ return cached_after_wait+ register_data: dict[str, object] = {+ "client_name": mcp_server.server_name or mcp_server.server_id,+ "redirect_uris": [f"{request_base_url}/callback"],+ "grant_types": ["authorization_code", "refresh_token"],+ "response_types": ["code"],+ "token_endpoint_auth_method": "none",+ }+ response = await _post_dcr_registration(+ registration_url=mcp_server.registration_url,+ register_data=register_data,+ server_id=mcp_server.server_id,+ )+ try:+ registration = _DcrClientRegistration.model_validate_json(response.text)+ except ValidationError as exc:+ raise HTTPException(+ status_code=502,+ detail="MCP upstream registration endpoint returned no usable client_id",+ ) from exc+ if not registration.client_id:+ raise HTTPException(+ status_code=502,+ detail="MCP upstream registration endpoint returned no usable client_id",+ )+ minted = EphemeralDcrClient(+ client_id=registration.client_id,+ client_secret=registration.client_secret,+ token_endpoint_auth_method=normalize_token_endpoint_auth_method(registration.token_endpoint_auth_method),+ )+ _EPHEMERAL_DCR_CLIENT_CACHE.set_cache(cache_key, minted)+ return minted+++async def resolve_ephemeral_dcr_client(+ request: Request,+ mcp_server: MCPServer,+ code_challenge: str | None,+ code_challenge_method: str | None,+ redirect_uri: str,+) -> EphemeralDcrClient | None:+ """The single owner of the gateway-side mint policy for a clientless authorize. Returns+ ``None`` for servers whose mode does not permit gateway minting and for upstreams without a+ registration endpoint, so those callers keep their existing failure paths: plain ``oauth2``+ keeps its persisted-client contract, and the interactive ``oauth_delegate`` dcr_bridge+ sign-in has its own sealed-identity flow. ``true_passthrough`` mints regardless of the+ ``dcr_bridge`` flag (the UI creates passthrough servers with the flag on by default): a+ minted flow runs the bridge short-circuit arm, while the relay front door remains for+ external clients that registered themselves. Flows that could never succeed fail loud+ before any upstream registration: a missing ``authorization_url``, a downgraded PKCE pair+ (without S256 the sealed code would be bearer-redeemable by any authenticated caller who+ intercepts the redirect), or an untrusted ``redirect_uri`` (a rejected redirect must not be+ usable to generate orphan IdP clients)."""+ if not (mcp_server.is_true_passthrough or (mcp_server.is_oauth_delegate and not mcp_server.is_dcr_bridge)):+ return None+ if mcp_server.authorization_url is None:+ raise HTTPException(+ status_code=400,+ detail="MCP server authorization url is not set",+ )+ _require_s256_pkce(code_challenge, code_challenge_method)+ validate_trusted_redirect_uri(request, redirect_uri)+ return await mint_ephemeral_dcr_client(request, mcp_server)++async def register_client_with_server(request: Request,mcp_server: MCPServer,@@ -1302,30 +1564,11 @@ async def register_client_with_server("response_types": response_types or (["code"] if bridge_relay else []),"token_endpoint_auth_method": token_endpoint_auth_method or ("none" if bridge_relay else ""),}- headers = {- "Content-Type": "application/json",- "Accept": "application/json",- }-- async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Register)- try:- response = await async_client.post(- mcp_server.registration_url,- headers=headers,- json=register_data,- )- if response is not None:- response.raise_for_status()- except httpx.HTTPStatusError as exc:- status_code, detail = dcr_fault_detail(- classify_upstream_dcr_rejection(exc.response, log_context=mcp_server.server_id)- )- raise HTTPException(status_code=status_code, detail=detail) from exc- if response is None:- raise HTTPException(- status_code=502,- detail="MCP upstream registration endpoint returned no response",- )+ response = await _post_dcr_registration(+ registration_url=mcp_server.registration_url,+ register_data=register_data,+ server_id=mcp_server.server_id,+ )token_response = response.json()@@ -1563,11 +1806,23 @@ async def callback(# envelope to this user. Every other flow forwards the raw code unchanged.litellm_user_id = state_data.get("litellm_user_id")mcp_server_id = state_data.get("mcp_server_id")+ dcr_client_id = state_data.get("dcr_client_id")+ dcr_client_secret = state_data.get("dcr_client_secret")forwarded_code = codeif isinstance(litellm_user_id, str) and litellm_user_id and isinstance(mcp_server_id, str) and mcp_server_id:forwarded_code = seal_bridge_authorization_code(upstream_code=code, litellm_user_id=litellm_user_id, mcp_server_id=mcp_server_id)+ elif isinstance(dcr_client_id, str) and dcr_client_id and isinstance(mcp_server_id, str) and mcp_server_id:+ forwarded_code = seal_passthrough_authorization_code(+ upstream_code=code,+ client_id=dcr_client_id,+ client_secret=dcr_client_secret if isinstance(dcr_client_secret, str) and dcr_client_secret else None,+ mcp_server_id=mcp_server_id,+ token_endpoint_auth_method=normalize_token_endpoint_auth_method(+ state_data.get("dcr_token_endpoint_auth_method")+ ),+ )params = {"code": forwarded_code, "state": original_state}complete_returned_url = _append_query_params(redirect_uri, params)@@ -2158,7 +2413,7 @@ async def register_client(request: Request, mcp_server_name: Optional[str] = Nonrequest_data = await _read_request_body(request=request)data: dict = {**request_data}- client_redirect_uris = _client_supplied_redirect_uris(data.get("redirect_uris"))+ client_redirect_uris = client_supplied_redirect_uris(data.get("redirect_uris"))dummy_return = {"client_id": mcp_server_name or "dummy_client",diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.pyindex d50db8324ef..89f28a30a84 100644--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py@@ -136,9 +136,12 @@ if MCP_AVAILABLE:from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (_raise_if_not_oauth2,authorize_with_server,+ client_supplied_redirect_uris,exchange_token_with_server,get_request_base_url,+ redeem_passthrough_authorization_code,register_client_with_server,+ resolve_ephemeral_dcr_client,)from litellm.proxy._experimental.mcp_server.mcp_server_manager import (global_mcp_server_manager,@@ -1661,7 +1664,21 @@ if MCP_AVAILABLE:mcp_server = await _get_cached_temporary_mcp_server_or_404(server_id, user_api_key_dict, request=request)_raise_if_not_oauth2(mcp_server)# Use the server's stored client_id when the caller doesn't supply one- resolved_client_id = mcp_server.client_id or client_id or ""+ stored_or_supplied_client_id = mcp_server.client_id or client_id or ""+ ephemeral_dcr_client = (+ await resolve_ephemeral_dcr_client(+ request=request,+ mcp_server=mcp_server,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ redirect_uri=redirect_uri,+ )+ if not stored_or_supplied_client_id+ else None+ )+ resolved_client_id = stored_or_supplied_client_id or (+ ephemeral_dcr_client.client_id if ephemeral_dcr_client else ""+ )if not resolved_client_id:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,@@ -1683,6 +1700,7 @@ if MCP_AVAILABLE:code_challenge_method=code_challenge_method,response_type=response_type,scope=scope,+ ephemeral_dcr_client=ephemeral_dcr_client,)@router.post(@@ -1705,7 +1723,21 @@ if MCP_AVAILABLE:):mcp_server = await _get_cached_temporary_mcp_server_or_404(server_id, user_api_key_dict, request=request)_raise_if_not_oauth2(mcp_server)- resolved_client_id = mcp_server.client_id or client_id or ""+ # Sealed passthrough codes exist only for the authorization_code grant. A refresh_token+ # grant must never open one: the minted client is unrecoverable after the single flow by+ # contract, so an expired browser-held token re-runs authorize instead.+ sealed_code = (+ redeem_passthrough_authorization_code(code=code, mcp_server=mcp_server, code_verifier=code_verifier)+ if grant_type == "authorization_code"+ else None+ )+ resolved_code = sealed_code.upstream_code if sealed_code else code+ # A sealed flow ran the gateway /callback as its upstream redirect (bridge short-circuit+ # or plain flow alike), so the exchange must present that binding, not the browser page.+ resolved_redirect_uri = f"{get_request_base_url(request)}/callback" if sealed_code else redirect_uri+ caller_client_id = sealed_code.client_id if sealed_code else client_id+ caller_client_secret = sealed_code.client_secret if sealed_code else client_secret+ resolved_client_id = mcp_server.client_id or caller_client_id or ""if not resolved_client_id:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,@@ -1721,13 +1753,14 @@ if MCP_AVAILABLE:request=request,mcp_server=mcp_server,grant_type=grant_type,- code=code,- redirect_uri=redirect_uri,+ code=resolved_code,+ redirect_uri=resolved_redirect_uri,client_id=resolved_client_id,- client_secret=client_secret,+ client_secret=caller_client_secret,code_verifier=code_verifier,refresh_token=refresh_token,scope=scope,+ client_token_endpoint_auth_method=sealed_code.token_endpoint_auth_method if sealed_code else None,)@router.post(@@ -1743,6 +1776,7 @@ if MCP_AVAILABLE:mcp_server = await _get_cached_temporary_mcp_server_or_404(server_id, user_api_key_dict, request=request)request_data = await _read_request_body(request=request)data: dict = {**request_data}+ client_redirect_uris = client_supplied_redirect_uris(data.get("redirect_uris"))return await register_client_with_server(request=request,@@ -1753,6 +1787,7 @@ if MCP_AVAILABLE:token_endpoint_auth_method=data.get("token_endpoint_auth_method", ""),fallback_client_id=server_id,persist_credentials=_user_is_full_admin(user_api_key_dict),+ client_redirect_uris=client_redirect_uris,)@router.delete(diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.pyindex 636c7fbd3d5..692e5340f48 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py@@ -8148,3 +8148,489 @@ async def test_register_wall_names_the_fix_for_urlless_servers():detail_text = str(exc_info.value.detail)assert "set Authorization URL and Token URL" in detail_textassert "Issuer" in detail_text+++def test_passthrough_authorization_code_round_trips_and_rejects_hostile_input():+ """The passthrough gateway code seals and recovers the ephemeral DCR client and upstream code,+ and is total over hostile input: a raw upstream code opens to None, and a tampered or+ non-gateway value opens to None rather than raising, so every existing caller-supplied-client+ flow is untouched."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ open_passthrough_authorization_code,+ seal_passthrough_authorization_code,+ )++ with patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY):+ sealed = seal_passthrough_authorization_code(+ upstream_code="up-code",+ client_id="minted-77",+ client_secret="mint-secret",+ mcp_server_id="srv-1",+ token_endpoint_auth_method="client_secret_basic",+ )+ opened = open_passthrough_authorization_code(sealed)+ assert opened is not None+ assert opened.upstream_code == "up-code"+ assert opened.client_id == "minted-77"+ assert opened.client_secret == "mint-secret"+ assert opened.mcp_server_id == "srv-1"+ assert opened.token_endpoint_auth_method == "client_secret_basic"+ assert open_passthrough_authorization_code("raw-upstream-code") is None+ assert open_passthrough_authorization_code(sealed[:-4] + "aaaa") is None++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ _BRIDGE_AUTH_CODE_PREFIX,+ _PASSTHROUGH_AUTH_CODE_PREFIX,+ open_bridge_authorization_code,+ seal_bridge_authorization_code,+ )++ bridge_sealed = seal_bridge_authorization_code(+ upstream_code="up-code", litellm_user_id="sso-user-9", mcp_server_id="srv-1"+ )+ reprefixed_as_passthrough = _PASSTHROUGH_AUTH_CODE_PREFIX + bridge_sealed[len(_BRIDGE_AUTH_CODE_PREFIX) :]+ reprefixed_as_bridge = _BRIDGE_AUTH_CODE_PREFIX + sealed[len(_PASSTHROUGH_AUTH_CODE_PREFIX) :]+ assert open_passthrough_authorization_code(reprefixed_as_passthrough) is None+ assert open_bridge_authorization_code(reprefixed_as_bridge) is None+++async def test_authorize_with_ephemeral_dcr_client_seals_client_into_state():+ """When mcp_authorize fell through to a gateway-side DCR mint, authorize_with_server seals the+ minted client and the target server into the encrypted OAuth state, so the callback can bind+ them into the forwarded authorization code while the gateway stores nothing."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ EphemeralDcrClient,+ authorize_with_server,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.true_passthrough, dcr_bridge=None)+ captured: dict = {}++ def _capture(**kwargs):+ captured.update(kwargs)+ return "mocked_encrypted_state"++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.encode_state_with_base_url",+ side_effect=_capture,+ ):+ response = await authorize_with_server(+ request=_bridge_mock_request(),+ mcp_server=server,+ client_id="minted-77",+ redirect_uri="http://127.0.0.1:60108/callback",+ state="s",+ code_challenge="chal",+ code_challenge_method="S256",+ ephemeral_dcr_client=EphemeralDcrClient(+ client_id="minted-77", client_secret="mint-secret", token_endpoint_auth_method="client_secret_basic"+ ),+ )++ assert captured["dcr_client_id"] == "minted-77"+ assert captured["dcr_client_secret"] == "mint-secret"+ assert captured["dcr_token_endpoint_auth_method"] == "client_secret_basic"+ assert captured["mcp_server_id"] == server.server_id+ assert "client_id=minted-77" in response.headers["location"]+++async def test_callback_wraps_code_into_passthrough_code_for_ephemeral_dcr_state():+ """When the OAuth state carries an ephemeral DCR client, the callback forwards a sealed+ passthrough code (binding the client and the upstream code to the server) instead of the raw+ upstream code, so the client's later token call can authenticate the exchange with a client the+ gateway never stored."""+ from urllib.parse import parse_qs, urlparse++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ callback,+ open_passthrough_authorization_code,+ )++ state_data = {+ "original_state": "client-state",+ "client_redirect_uri": "http://127.0.0.1:60108/cb",+ "base_url": "http://127.0.0.1:60108/cb",+ "mcp_server_id": "srv-1",+ "dcr_client_id": "minted-77",+ "dcr_client_secret": "mint-secret",+ "dcr_token_endpoint_auth_method": "client_secret_basic",+ }+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._resolve_encoded_oauth_state",+ return_value="enc",+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.decode_state_hash",+ return_value=state_data,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._get_validated_client_redirect_uri",+ return_value="http://127.0.0.1:60108/cb",+ ),+ patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY),+ ):+ response = await callback(request=_bridge_mock_request(), code="REAL-UPSTREAM-CODE", state="relay")++ forwarded_code = parse_qs(urlparse(response.headers["location"]).query)["code"][0]+ opened = open_passthrough_authorization_code(forwarded_code)++ assert opened is not None+ assert opened.upstream_code == "REAL-UPSTREAM-CODE"+ assert opened.client_id == "minted-77"+ assert opened.client_secret == "mint-secret"+ assert opened.mcp_server_id == "srv-1"+ assert opened.token_endpoint_auth_method == "client_secret_basic"+++async def test_authorize_bridge_server_with_ephemeral_client_takes_short_circuit_arm():+ """A gateway-minted client is registered against {base}/callback, so a bridge server's+ authorize with an ephemeral client must run the short-circuit (gateway /callback) arm with a+ relay state cookie, never the verbatim relay: relaying would send the browser's redirect_uri+ to an IdP that has the gateway callback registered, stranding the flow."""+ from urllib.parse import parse_qs, urlparse++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ EphemeralDcrClient,+ authorize_with_server,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.true_passthrough)+ with patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY):+ response = await authorize_with_server(+ request=_bridge_mock_request(),+ mcp_server=server,+ client_id="minted-77",+ redirect_uri="http://127.0.0.1:60108/callback",+ state="client-state",+ code_challenge="chal",+ code_challenge_method="S256",+ ephemeral_dcr_client=EphemeralDcrClient(client_id="minted-77", client_secret=None),+ )++ location = response.headers["location"]+ params = parse_qs(urlparse(location).query)+ assert params["redirect_uri"] == ["https://litellm.example.com/callback"]+ assert params["client_id"] == ["minted-77"]+ assert params["state"] != ["client-state"]+ assert any(cookie.startswith("mcp_oauth_state_") for cookie in response.headers.get("set-cookie", "").split(";"))+++async def test_callback_forwards_raw_code_when_dcr_state_lacks_server_binding():+ """A state carrying a dcr client but no server id cannot produce a server-bound sealed code, so+ the callback falls back to forwarding the raw upstream code instead of sealing an unbindable+ one."""+ from urllib.parse import parse_qs, urlparse++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import callback++ state_data = {+ "original_state": "client-state",+ "client_redirect_uri": "http://127.0.0.1:60108/cb",+ "base_url": "http://127.0.0.1:60108/cb",+ "dcr_client_id": "minted-77",+ }+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._resolve_encoded_oauth_state",+ return_value="enc",+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.decode_state_hash",+ return_value=state_data,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._get_validated_client_redirect_uri",+ return_value="http://127.0.0.1:60108/cb",+ ),+ patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY),+ ):+ response = await callback(request=_bridge_mock_request(), code="REAL-UPSTREAM-CODE", state="relay")++ forwarded_code = parse_qs(urlparse(response.headers["location"]).query)["code"][0]+ assert forwarded_code == "REAL-UPSTREAM-CODE"+++ "auth_type_value",+ [+ "none",+ "api_key",+ "bearer_token",+ "basic",+ "authorization",+ "oauth2",+ "aws_sigv4",+ "token",+ "oauth2_token_exchange",+ "oauth2_id_jag",+ "true_passthrough",+ "oauth_delegate",+ ],+)[email protected]("dcr_bridge", [True, False])+async def test_resolve_ephemeral_dcr_client_mint_set_is_exact(auth_type_value, dcr_bridge):+ """The full authorize-time mint decision matrix, one cell per (auth_type, dcr_bridge). The gateway+ mints iff true_passthrough (any bridge) or oauth_delegate-and-not-dcr_bridge; every other mode+ returns None so no non-OAuth mode ever registers an upstream client, and the interactive+ oauth_delegate dcr_bridge sign-in is left to its own browser-front-door flow. The UI+ gatewayMintsClientFor helper mirrors this exact set; ui/.../mcp_tools/types.test.tsx pins the+ frontend side against the same table, so a divergence fails on one side or the other."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ EphemeralDcrClient,+ resolve_ephemeral_dcr_client,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(+ auth_type=MCPAuth(auth_type_value),+ dcr_bridge=dcr_bridge,+ server_id=f"matrix_{auth_type_value}_{dcr_bridge}",+ server_name=f"matrix_{auth_type_value}_{dcr_bridge}",+ )+ expected_mint = server.is_true_passthrough or (server.is_oauth_delegate and not server.is_dcr_bridge)+ mint_mock = AsyncMock(return_value=EphemeralDcrClient(client_id="minted", client_secret=None))++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.mint_ephemeral_dcr_client",+ mint_mock,+ ):+ result = await resolve_ephemeral_dcr_client(+ request=_bridge_mock_request(),+ mcp_server=server,+ code_challenge="chal",+ code_challenge_method="S256",+ redirect_uri="http://127.0.0.1:9/callback",+ )++ if expected_mint:+ mint_mock.assert_awaited_once()+ assert result is not None+ else:+ mint_mock.assert_not_awaited()+ assert result is None+++async def test_mint_ephemeral_dcr_client_returns_none_without_registration_endpoint():+ """A server whose upstream exposes no RFC 7591 registration endpoint cannot mint, so the+ fall-through reports None and the caller keeps its existing missing_client_id failure."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ mint_ephemeral_dcr_client,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.true_passthrough, dcr_bridge=None, registration_url=None)+ assert await mint_ephemeral_dcr_client(_bridge_mock_request(), server) is None+++async def test_mint_ephemeral_dcr_client_posts_rfc7591_and_returns_client():+ """The mint POSTs a public-client RFC 7591 registration bound to the gateway /callback and hands+ back the upstream's client without persisting it anywhere."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ mint_ephemeral_dcr_client,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(+ auth_type=MCPAuth.true_passthrough, dcr_bridge=None, server_id="mint_posts_srv", server_name="mint_posts_srv"+ )+ mock_response = MagicMock()+ mock_response.text = json.dumps(+ {"client_id": "minted-77", "client_secret": "mint-secret", "token_endpoint_auth_method": "client_secret_basic"}+ )+ mock_response.raise_for_status = MagicMock()+ mock_async_client = MagicMock()+ mock_async_client.post = AsyncMock(return_value=mock_response)++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=mock_async_client,+ ):+ minted = await mint_ephemeral_dcr_client(_bridge_mock_request(), server)++ assert minted is not None+ assert minted.client_id == "minted-77"+ assert minted.client_secret == "mint-secret"+ assert minted.token_endpoint_auth_method == "client_secret_basic"+ register_data = mock_async_client.post.call_args.kwargs["json"]+ assert register_data["redirect_uris"] == ["https://litellm.example.com/callback"]+ assert register_data["token_endpoint_auth_method"] == "none"+ assert register_data["grant_types"] == ["authorization_code", "refresh_token"]+++async def test_mint_ephemeral_dcr_client_reuses_minted_client_within_flow_ttl():+ """Reloading the authorize page must not spam the upstream registration endpoint with orphan+ clients: within the OAuth state's lifetime a second mint for the same server and gateway origin+ reuses the cached client and performs no second upstream POST."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ mint_ephemeral_dcr_client,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(+ auth_type=MCPAuth.true_passthrough, dcr_bridge=None, server_id="mint_reuse_srv", server_name="mint_reuse_srv"+ )+ mock_response = MagicMock()+ mock_response.text = json.dumps({"client_id": "minted-77"})+ mock_response.raise_for_status = MagicMock()+ mock_async_client = MagicMock()+ mock_async_client.post = AsyncMock(return_value=mock_response)++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=mock_async_client,+ ):+ first = await mint_ephemeral_dcr_client(_bridge_mock_request(), server)+ second = await mint_ephemeral_dcr_client(_bridge_mock_request(), server)++ assert first is not None+ assert second == first+ mock_async_client.post.assert_called_once()+++async def test_mint_ephemeral_dcr_client_single_flights_concurrent_mints():+ """Two in-flight authorize requests for the same server must not both register an upstream+ client: the per-key lock makes the second waiter reuse the first mint, so exactly one upstream+ POST happens."""+ import asyncio++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ mint_ephemeral_dcr_client,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(+ auth_type=MCPAuth.true_passthrough,+ dcr_bridge=None,+ server_id="mint_concurrent_srv",+ server_name="mint_concurrent_srv",+ )+ mock_response = MagicMock()+ mock_response.text = json.dumps({"client_id": "minted-77"})+ mock_response.raise_for_status = MagicMock()++ async def _slow_post(*args, **kwargs):+ await asyncio.sleep(0.05)+ return mock_response++ mock_async_client = MagicMock()+ mock_async_client.post = AsyncMock(side_effect=_slow_post)++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=mock_async_client,+ ):+ first, second = await asyncio.gather(+ mint_ephemeral_dcr_client(_bridge_mock_request(), server),+ mint_ephemeral_dcr_client(_bridge_mock_request(), server),+ )++ assert first is not None+ assert second == first+ mock_async_client.post.assert_called_once()+++ "payload, server_id",+ [+ ({"unexpected": "shape"}, "mint_bad_shape_srv"),+ ({"client_id": ""}, "mint_empty_id_srv"),+ ],+)+async def test_mint_ephemeral_dcr_client_unusable_registration_response_is_502(payload, server_id):+ """An upstream registration response without a usable client_id, whether the field is missing or+ an empty string, surfaces as a loud 502 instead of letting the authorize proceed with an empty+ client and fail opaquely at the IdP."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ mint_ephemeral_dcr_client,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.true_passthrough, dcr_bridge=None, server_id=server_id, server_name=server_id)+ mock_response = MagicMock()+ mock_response.text = json.dumps(payload)+ mock_response.raise_for_status = MagicMock()+ mock_async_client = MagicMock()+ mock_async_client.post = AsyncMock(return_value=mock_response)++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=mock_async_client,+ ):+ with pytest.raises(HTTPException) as exc:+ await mint_ephemeral_dcr_client(_bridge_mock_request(), server)++ assert exc.value.status_code == 502+++ "sealed_auth_method, expects_basic_header",+ [+ ("client_secret_basic", True),+ (None, False),+ ],+)+async def test_token_exchange_authenticates_with_the_sealed_clients_own_auth_method(+ sealed_auth_method, expects_basic_header+):+ """The id, secret, and token-endpoint auth method must come from the same source: a client+ recovered from a sealed passthrough code authenticates the upstream exchange the way its own+ registration was granted, not the way the server row is configured. A sealed+ ``client_secret_basic`` grant sends the Basic header and keeps the secret out of the body; a+ sealed public client (no method) keeps the body-credential path."""+ import base64++ import httpx++ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ exchange_token_with_server,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.true_passthrough, dcr_bridge=None, server_id="sealed_method_srv")+ upstream_request = httpx.Request("POST", server.token_url)+ upstream_response = httpx.Response(+ 200, json={"access_token": "up-token", "token_type": "Bearer"}, request=upstream_request+ )+ mock_async_client = MagicMock()+ mock_async_client.post = AsyncMock(return_value=upstream_response)++ with patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=mock_async_client,+ ):+ await exchange_token_with_server(+ request=_bridge_mock_request(),+ mcp_server=server,+ grant_type="authorization_code",+ code="up-code",+ redirect_uri="https://litellm.example.com/callback",+ client_id="minted-77",+ client_secret="mint-secret",+ code_verifier="verifier",+ client_token_endpoint_auth_method=sealed_auth_method,+ )++ sent_headers = mock_async_client.post.call_args.kwargs["headers"]+ sent_body = mock_async_client.post.call_args.kwargs["data"]+ if expects_basic_header:+ expected = base64.b64encode(b"minted-77:mint-secret").decode()+ assert sent_headers["Authorization"] == f"Basic {expected}"+ assert "client_secret" not in sent_body+ else:+ assert "Authorization" not in sent_headers+ assert sent_body["client_id"] == "minted-77"+ assert sent_body["client_secret"] == "mint-secret"diff --git a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.pyindex 3e5bd3e9b7f..e1aaf398f97 100644--- a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py@@ -2,6 +2,7 @@ import osimport sysimport typesimport json+from contextlib import ExitStackfrom datetime import datetime, timedeltafrom types import SimpleNamespacefrom typing import List, Optional@@ -2025,8 +2026,469 @@ class TestTemporaryMCPSessionEndpoints:code_challenge_method="S256",response_type="code",scope="scope1",+ ephemeral_dcr_client=None,)+ async def _authorize_without_client_id(+ self, server, mint_mock=None, code_challenge="chal", code_challenge_method="S256"+ ):+ """Drive mcp_authorize with no caller client_id against ``server``, returning the+ (authorize_with_server mock, raised HTTPException or None) pair. Sends a valid S256 PKCE+ pair by default because the ephemeral mint requires it."""+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_authorize,+ )++ request = MagicMock()+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)+ patches = [+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints.authorize_with_server",+ AsyncMock(return_value=MagicMock()),+ ),+ ]+ if mint_mock is not None:+ patches.append(+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.mint_ephemeral_dcr_client",+ mint_mock,+ )+ )+ with ExitStack() as stack:+ entered = [stack.enter_context(p) for p in patches]+ authorize_mock = entered[1]+ try:+ await mcp_authorize(+ request=request,+ server_id=server.server_id,+ user_api_key_dict=admin_auth,+ client_id=None,+ redirect_uri="http://127.0.0.1:60108/callback",+ state="state123",+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ )+ except HTTPException as exc:+ return authorize_mock, exc+ return authorize_mock, None++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "code_challenge, code_challenge_method",+ [(None, None), ("chal", "plain"), ("chal", None)],+ )+ async def test_mcp_authorize_mint_requires_s256_pkce(self, code_challenge, code_challenge_method):+ """Without PKCE the sealed code would be bearer-redeemable by any authenticated caller who+ intercepts the redirect, so the ephemeral mint refuses to run for a downgraded flow (no+ challenge, or a non-S256 method) before any upstream registration happens."""+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = "https://idp.example.com/register"+ mint_mock = AsyncMock()++ authorize_mock, exc = await self._authorize_without_client_id(+ server, mint_mock=mint_mock, code_challenge=code_challenge, code_challenge_method=code_challenge_method+ )++ assert exc is not None+ assert exc.status_code == 400+ assert "PKCE" in str(exc.detail)+ mint_mock.assert_not_awaited()+ authorize_mock.assert_not_awaited()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("auth_type", [MCPAuth.true_passthrough, MCPAuth.oauth_delegate])+ async def test_mcp_authorize_client_forwarded_modes_mint_ephemeral_dcr_client_when_none_supplied(self, auth_type):+ """LIT-4581 regression: a client-forwarded-token server created without an auth step has no+ stored client_id and the tools-tab browser flow supplies none, so authorize must fall+ through to a gateway-side DCR mint and proceed with the minted client instead of+ dead-ending on a 400 missing_client_id. Both modes share the caller-held-client contract,+ so both get the fall-through."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ EphemeralDcrClient,+ )++ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = auth_type+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = "https://idp.example.com/register"+ minted = EphemeralDcrClient(client_id="minted-77", client_secret="mint-secret")+ mint_mock = AsyncMock(return_value=minted)++ authorize_mock, exc = await self._authorize_without_client_id(server, mint_mock=mint_mock)++ assert exc is None+ mint_mock.assert_awaited_once()+ assert authorize_mock.await_args.kwargs["client_id"] == "minted-77"+ assert authorize_mock.await_args.kwargs["ephemeral_dcr_client"] is minted++ @pytest.mark.asyncio+ async def test_mcp_authorize_rejects_untrusted_redirect_before_minting(self):+ """An untrusted redirect_uri must be rejected before the gateway performs any upstream+ registration, so bad-redirect requests cannot be used to generate orphan clients at the+ IdP."""+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_authorize,+ )++ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = "https://idp.example.com/register"+ mint_mock = AsyncMock()+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)+ request = MagicMock()+ request.base_url = "https://litellm.example.com/"+ request.headers = {}++ with (+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.mint_ephemeral_dcr_client",+ mint_mock,+ ),+ ):+ with pytest.raises(HTTPException) as exc:+ await mcp_authorize(+ request=request,+ server_id="server-1",+ user_api_key_dict=admin_auth,+ client_id=None,+ redirect_uri="https://evil.example.net/steal",+ state="state123",+ code_challenge="chal",+ code_challenge_method="S256",+ )++ assert exc.value.status_code == 400+ mint_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_authorize_true_passthrough_without_authorization_url_reports_the_real_fault(self):+ """A passthrough server whose discovery never yielded an authorize endpoint cannot start any+ flow, minted client or not, so the error names the missing authorization url instead of the+ misleading missing_client_id remedy."""+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ server.authorization_url = None+ server.registration_url = "https://idp.example.com/register"+ mint_mock = AsyncMock()++ authorize_mock, exc = await self._authorize_without_client_id(server, mint_mock=mint_mock)++ assert exc is not None+ assert exc.status_code == 400+ assert "authorization url" in str(exc.detail)+ mint_mock.assert_not_awaited()+ authorize_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_authorize_true_passthrough_without_registration_endpoint_keeps_missing_client_id(self):+ """When the upstream exposes no registration endpoint the mint is impossible, so the+ authorize fails closed with the existing missing_client_id 400 instead of proceeding with an+ empty client."""+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = None++ authorize_mock, exc = await self._authorize_without_client_id(server)++ assert exc is not None+ assert exc.status_code == 400+ assert exc.detail["error"] == "missing_client_id"+ authorize_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_authorize_oauth2_server_does_not_mint(self):+ """The ephemeral mint is scoped to the client-forwarded-token modes: a plain oauth2 server+ keeps the gateway-held-client contract (its client is persisted by the admin register flow),+ so an empty client_id stays a 400 and no upstream registration is attempted."""+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.oauth2+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = "https://idp.example.com/register"+ mint_mock = AsyncMock()++ authorize_mock, exc = await self._authorize_without_client_id(server, mint_mock=mint_mock)++ assert exc is not None+ assert exc.status_code == 400+ assert exc.detail["error"] == "missing_client_id"+ mint_mock.assert_not_awaited()+ authorize_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_authorize_true_passthrough_dcr_bridge_mints_too(self):+ """The UI creates passthrough servers with dcr_bridge enabled by default, so the default+ clientless tools-page authorize is a bridge server; it must mint exactly like a non-bridge+ one (the minted flow runs the bridge short-circuit arm) instead of dead-ending on+ missing_client_id. The relay front door stays reserved for clients that present their own+ client_id."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ EphemeralDcrClient,+ )++ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ server.dcr_bridge = True+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = "https://idp.example.com/register"+ minted = EphemeralDcrClient(client_id="minted-77", client_secret=None)+ mint_mock = AsyncMock(return_value=minted)++ authorize_mock, exc = await self._authorize_without_client_id(server, mint_mock=mint_mock)++ assert exc is None+ mint_mock.assert_awaited_once()+ assert authorize_mock.await_args.kwargs["client_id"] == "minted-77"+ assert authorize_mock.await_args.kwargs["ephemeral_dcr_client"] is minted++ @pytest.mark.asyncio+ async def test_mcp_authorize_oauth_delegate_dcr_bridge_does_not_mint(self):+ """The interactive oauth_delegate dcr_bridge sign-in has its own sealed-identity flow that+ captures the SSO user at authorize; the ephemeral mint must not preempt it."""+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.oauth_delegate+ server.dcr_bridge = True+ server.authorization_url = "https://idp.example.com/authorize"+ server.registration_url = "https://idp.example.com/register"+ mint_mock = AsyncMock()++ authorize_mock, exc = await self._authorize_without_client_id(server, mint_mock=mint_mock)++ assert exc is not None+ assert exc.status_code == 400+ assert exc.detail["error"] == "missing_client_id"+ mint_mock.assert_not_awaited()+ authorize_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_token_opens_sealed_passthrough_code_and_exchanges_with_minted_client(self):+ """LIT-4581 regression, token leg: the client echoes back the sealed passthrough code the+ callback forwarded, so the token endpoint recovers the ephemeral client and the real+ upstream code from it and authenticates the exchange with them, with no client_id supplied+ by the caller and none stored on the server."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ seal_passthrough_authorization_code,+ )+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_token,+ )++ request = MagicMock()+ request.base_url = "https://litellm.example.com/"+ request.headers = {}+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)++ with (+ patch("litellm.proxy.proxy_server.master_key", "sk-lit4581-test-master-key"),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints.exchange_token_with_server",+ AsyncMock(return_value={"access_token": "token"}),+ ) as exchange_mock,+ ):+ sealed = seal_passthrough_authorization_code(+ upstream_code="up-code",+ client_id="minted-77",+ client_secret="mint-secret",+ mcp_server_id="server-1",+ token_endpoint_auth_method="client_secret_basic",+ )+ result = await mcp_token(+ request=request,+ server_id="server-1",+ user_api_key_dict=admin_auth,+ grant_type="authorization_code",+ code=sealed,+ redirect_uri="https://example.com/callback",+ client_id=None,+ client_secret=None,+ code_verifier="verifier",+ refresh_token=None,+ scope=None,+ )++ assert result == {"access_token": "token"}+ assert exchange_mock.await_args.kwargs["code"] == "up-code"+ assert exchange_mock.await_args.kwargs["client_id"] == "minted-77"+ assert exchange_mock.await_args.kwargs["client_secret"] == "mint-secret"+ assert exchange_mock.await_args.kwargs["redirect_uri"] == "https://litellm.example.com/callback"+ assert exchange_mock.await_args.kwargs["client_token_endpoint_auth_method"] == "client_secret_basic"++ @pytest.mark.asyncio+ async def test_mcp_token_refresh_grant_never_opens_sealed_code(self):+ """The minted client is unrecoverable outside the single authorization_code flow by+ contract: a refresh_token grant that echoes a leftover sealed passthrough code (plus any+ verifier) must not recover the minted credentials, so a clientless server answers+ missing_client_id and the client re-runs authorize instead."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ seal_passthrough_authorization_code,+ )+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_token,+ )++ request = MagicMock()+ request.base_url = "https://litellm.example.com/"+ request.headers = {}+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)++ with (+ patch("litellm.proxy.proxy_server.master_key", "sk-lit4581-test-master-key"),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints.exchange_token_with_server",+ AsyncMock(return_value={"access_token": "token"}),+ ) as exchange_mock,+ ):+ sealed = seal_passthrough_authorization_code(+ upstream_code="up-code",+ client_id="minted-77",+ client_secret="mint-secret",+ mcp_server_id="server-1",+ token_endpoint_auth_method="client_secret_basic",+ )+ with pytest.raises(HTTPException) as exc:+ await mcp_token(+ request=request,+ server_id="server-1",+ user_api_key_dict=admin_auth,+ grant_type="refresh_token",+ code=sealed,+ redirect_uri="https://example.com/callback",+ client_id=None,+ client_secret=None,+ code_verifier="verifier",+ refresh_token="leftover-refresh",+ scope=None,+ )++ assert exc.value.status_code == 400+ assert exc.value.detail["error"] == "missing_client_id"+ exchange_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_token_sealed_code_requires_code_verifier(self):+ """A sealed code is minted only for S256 PKCE flows, so redeeming one without the+ corresponding verifier is refused at the gateway rather than trusting the upstream to+ enforce the binding."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ seal_passthrough_authorization_code,+ )+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_token,+ )++ request = MagicMock()+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)++ with (+ patch("litellm.proxy.proxy_server.master_key", "sk-lit4581-test-master-key"),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints.exchange_token_with_server",+ AsyncMock(),+ ) as exchange_mock,+ ):+ sealed = seal_passthrough_authorization_code(+ upstream_code="up-code", client_id="minted-77", client_secret=None, mcp_server_id="server-1"+ )+ with pytest.raises(HTTPException) as exc:+ await mcp_token(+ request=request,+ server_id="server-1",+ user_api_key_dict=admin_auth,+ grant_type="authorization_code",+ code=sealed,+ redirect_uri="https://example.com/callback",+ client_id=None,+ client_secret=None,+ code_verifier=None,+ refresh_token=None,+ scope=None,+ )++ assert exc.value.status_code == 400+ assert "code_verifier" in str(exc.value.detail)+ exchange_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_mcp_token_rejects_sealed_code_for_another_server(self):+ """A sealed passthrough code is bound to the server it was minted for: presenting it at+ another server's token endpoint is a 400 before any upstream exchange, so a code cannot be+ replayed across a server boundary."""+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ seal_passthrough_authorization_code,+ )+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_token,+ )++ request = MagicMock()+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.true_passthrough+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)++ with (+ patch("litellm.proxy.proxy_server.master_key", "sk-lit4581-test-master-key"),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints.exchange_token_with_server",+ AsyncMock(),+ ) as exchange_mock,+ ):+ sealed = seal_passthrough_authorization_code(+ upstream_code="up-code",+ client_id="minted-77",+ client_secret=None,+ mcp_server_id="a-different-server",+ )+ with pytest.raises(HTTPException) as exc:+ await mcp_token(+ request=request,+ server_id="server-1",+ user_api_key_dict=admin_auth,+ grant_type="authorization_code",+ code=sealed,+ redirect_uri="https://example.com/callback",+ client_id=None,+ client_secret=None,+ code_verifier="verifier",+ refresh_token=None,+ scope=None,+ )++ assert exc.value.status_code == 400+ exchange_mock.assert_not_awaited()+@pytest.mark.asyncioasync def test_mcp_authorize_rejects_non_oauth2_server(self):"""mcp_authorize must reject a none-auth server with an accurate 'does not use OAuth'@@ -2163,6 +2625,7 @@ class TestTemporaryMCPSessionEndpoints:code_verifier="verifier",refresh_token=None,scope=None,+ client_token_endpoint_auth_method=None,)@pytest.mark.asyncio@@ -2216,6 +2679,7 @@ class TestTemporaryMCPSessionEndpoints:code_verifier=None,refresh_token="rt-123",scope=None,+ client_token_endpoint_auth_method=None,)@pytest.mark.asyncio@@ -2270,8 +2734,59 @@ class TestTemporaryMCPSessionEndpoints:token_endpoint_auth_method="client_secret_basic",fallback_client_id="server-1",persist_credentials=True,+ client_redirect_uris=None,)+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "raw_redirect_uris, forwarded",+ [+ (["https://app.example.com/ui/callback"], ["https://app.example.com/ui/callback"]),+ (["https://app.example.com/ui/callback", 42, "", None], None),+ ("not-a-list", None),+ ([], None),+ ([123], None),+ ],+ )+ async def test_mcp_register_forwards_validated_redirect_uris(self, raw_redirect_uris, forwarded):+ """dcr_bridge servers relay the registration upstream and require the browser client's own+ redirect_uris, so mcp_register must forward them; the value is caller-controlled and is+ validated by the same client_supplied_redirect_uris boundary helper as the root /register+ door, so a malformed list is rejected whole at both doors (RFC 7591 redirect_uris is+ all-or-nothing) rather than silently forwarding the surviving entries here and rejecting+ them there."""+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (+ mcp_register,+ )++ request = MagicMock()+ server = generate_mock_mcp_server_config_record(server_id="server-1")+ server.auth_type = MCPAuth.oauth2+ request_body = {"client_name": "LiteLLM", "redirect_uris": raw_redirect_uris}+ admin_auth = generate_mock_user_api_key_auth(user_role=LitellmUserRoles.PROXY_ADMIN)++ with (+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",+ return_value=server,+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints._read_request_body",+ AsyncMock(return_value=request_body),+ ),+ patch(+ "litellm.proxy.management_endpoints.mcp_management_endpoints.register_client_with_server",+ AsyncMock(return_value={"client_id": "generated"}),+ ) as register_mock,+ ):+ await mcp_register(+ request=request,+ server_id="server-1",+ user_api_key_dict=admin_auth,+ )++ assert register_mock.await_args.kwargs["client_redirect_uris"] == forwarded+@pytest.mark.asyncioasync def test_mcp_register_does_not_persist_for_non_admin(self):"""A non-admin caller (who may have access to a real server) must not persist the DCRdiff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_view.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_view.tsxindex 620f76a739a..49df8206c8f 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_view.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_server_view.tsx@@ -211,6 +211,7 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({auth_type={mcpServer.auth_type}oauth2_flow={mcpServer.oauth2_flow}delegate_auth_to_upstream={mcpServer.delegate_auth_to_upstream}+ dcr_bridge={mcpServer.dcr_bridge}tokenUrl={mcpServer.token_url}userRole={userRole}userID={userID}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.test.tsxindex 8b0e6d62f66..3a189f50264 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.test.tsx@@ -17,8 +17,12 @@ vi.mock("@/utils/mcpTokenStore", () => ({removeToken: vi.fn(),}));+const { toolsOAuthFlowSpy } = vi.hoisted(() => ({+ toolsOAuthFlowSpy: vi.fn(() => ({ startOAuthFlow: vi.fn(), status: "idle", error: null })),+}));+vi.mock("@/hooks/useToolsOAuthFlow", () => ({- useToolsOAuthFlow: () => ({ startOAuthFlow: vi.fn(), status: "idle", error: null }),+ useToolsOAuthFlow: toolsOAuthFlowSpy,}));vi.mock("@/hooks/useUserMcpOAuthFlow", () => ({@@ -54,6 +58,27 @@ const credStatus = (overrides: Record<string, unknown> = {}) => ({...overrides,});+describe("MCPToolsViewer gatewayMintsClient wiring", () => {+ // Pins the call site (not just the helper): the viewer must pass the bridge-AWARE+ // gatewayMintsClientFor value to useToolsOAuthFlow, so the browser skips its own register exactly+ // when the gateway mints. The oauth_delegate + dcr_bridge cell is the regression guard: with the+ // old bridge-blind predicate it would have passed true here and dead-ended.+ beforeEach(() => toolsOAuthFlowSpy.mockClear());++ it.each([+ { auth_type: "true_passthrough", dcr_bridge: true, gatewayMintsClient: true },+ { auth_type: "true_passthrough", dcr_bridge: false, gatewayMintsClient: true },+ { auth_type: "oauth_delegate", dcr_bridge: false, gatewayMintsClient: true },+ { auth_type: "oauth_delegate", dcr_bridge: true, gatewayMintsClient: false },+ ])(+ "passes gatewayMintsClient=$gatewayMintsClient for $auth_type dcr_bridge=$dcr_bridge",+ ({ auth_type, dcr_bridge, gatewayMintsClient }) => {+ renderViewer({ auth_type, dcr_bridge, tokenUrl: null });+ expect(toolsOAuthFlowSpy).toHaveBeenCalledWith(expect.objectContaining({ gatewayMintsClient }));+ },+ );+});+describe("MCPToolsViewer auth gate routing", () => {beforeEach(() => {vi.mocked(listMCPTools).mockReset().mockResolvedValue({ tools: [], error: null });diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.tsxindex 428c10da284..28c17d1e41c 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_tools.tsx@@ -4,6 +4,7 @@ import { ToolTestPanel } from "./ToolTestPanel";import { resolveLogoSrc } from "@/lib/assetPaths";import {isClientForwardedTokenMode,+ gatewayMintsClientFor,MCPTool,MCPToolsViewerProps,MCPContent,@@ -28,6 +29,7 @@ const MCPToolsViewer = ({auth_type,oauth2_flow,delegate_auth_to_upstream,+ dcr_bridge,userRole,userID,serverAlias,@@ -76,6 +78,7 @@ const MCPToolsViewer = ({serverId,serverAlias,userId: userID,+ gatewayMintsClient: gatewayMintsClientFor({ auth_type, dcr_bridge }),onSuccess: setOauthToken,});diff --git a/ui/litellm-dashboard/src/components/mcp_tools/types.test.tsx b/ui/litellm-dashboard/src/components/mcp_tools/types.test.tsxindex 7ce803d583c..1b2feb3c731 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/types.test.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/types.test.tsx@@ -7,6 +7,7 @@ import {handleTransport,handleAuth,getMcpOAuthMode,+ gatewayMintsClientFor,getOAuthAuthorizationIdentity,isHeldOAuthTokenStale,oauth2FlowToFormValue,@@ -101,6 +102,41 @@ describe("constants", () => {});});+describe("gatewayMintsClientFor", () => {+ // The authoritative client-acquisition matrix: for each (auth_type, dcr_bridge) cell, does the+ // gateway mint the OAuth client at /authorize (browser skips its own register) or not (browser+ // registers)? This MUST equal the backend resolve_ephemeral_dcr_client mint set exactly, which+ // test_discoverable_endpoints.py::test_resolve_ephemeral_dcr_client_mint_set_is_exact pins against+ // the same predicate. A divergence in either direction dead-ends a mode (skip a register the+ // gateway never performs) or double-registers, so both sides are enumerated against this table.+ const MATRIX: Array<{ auth_type: string; dcr_bridge: boolean | null | undefined; mints: boolean }> = [+ { auth_type: AUTH_TYPE.TRUE_PASSTHROUGH, dcr_bridge: false, mints: true },+ { auth_type: AUTH_TYPE.TRUE_PASSTHROUGH, dcr_bridge: true, mints: true },+ { auth_type: AUTH_TYPE.TRUE_PASSTHROUGH, dcr_bridge: null, mints: true },+ { auth_type: AUTH_TYPE.OAUTH_DELEGATE, dcr_bridge: false, mints: true },+ { auth_type: AUTH_TYPE.OAUTH_DELEGATE, dcr_bridge: null, mints: true },+ { auth_type: AUTH_TYPE.OAUTH_DELEGATE, dcr_bridge: undefined, mints: true },+ // The one interactive-sign-in cell the gateway must NOT mint (browser front-door register).+ { auth_type: AUTH_TYPE.OAUTH_DELEGATE, dcr_bridge: true, mints: false },+ { auth_type: AUTH_TYPE.OAUTH2, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.OAUTH2, dcr_bridge: true, mints: false },+ { auth_type: AUTH_TYPE.OAUTH2_TOKEN_EXCHANGE, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.API_KEY, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.BEARER_TOKEN, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.BASIC, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.NONE, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.TOKEN, dcr_bridge: false, mints: false },+ { auth_type: AUTH_TYPE.AWS_SIGV4, dcr_bridge: false, mints: false },+ ];++ it.each(MATRIX)(+ "mints=$mints for auth_type=$auth_type dcr_bridge=$dcr_bridge",+ ({ auth_type, dcr_bridge, mints }) => {+ expect(gatewayMintsClientFor({ auth_type, dcr_bridge })).toBe(mints);+ },+ );+});+describe("getMcpOAuthMode", () => {it("returns null for non-OAuth2 servers", () => {expect(getMcpOAuthMode({ auth_type: AUTH_TYPE.API_KEY })).toBeNull();diff --git a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx b/ui/litellm-dashboard/src/components/mcp_tools/types.tsxindex dd7ed2bfbe4..049779e9fe2 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/types.tsx@@ -52,6 +52,19 @@ export const AUTH_TYPE = {export const isClientForwardedTokenMode = (authType?: string | null): boolean =>authType === AUTH_TYPE.TRUE_PASSTHROUGH || authType === AUTH_TYPE.OAUTH_DELEGATE;+/**+ * Whether the gateway acquires the OAuth client itself during /authorize (so the browser must NOT+ * pre-register one). This MUST mirror the backend `resolve_ephemeral_dcr_client` mint condition+ * exactly, cell for cell, or a mode where the two disagree either dead-ends (browser skips a+ * register the gateway never performs) or double-registers. The gateway mints for every+ * `true_passthrough` server, and for `oauth_delegate` only when it is NOT a dcr_bridge server: the+ * interactive oauth_delegate dcr_bridge sign-in captures the SSO user through the browser's own+ * front-door registration, which the mint must not preempt.+ */+export const gatewayMintsClientFor = (server: { auth_type?: string | null; dcr_bridge?: boolean | null }): boolean =>+ server.auth_type === AUTH_TYPE.TRUE_PASSTHROUGH ||+ (server.auth_type === AUTH_TYPE.OAUTH_DELEGATE && !server.dcr_bridge);+export const OAUTH_FLOW = {INTERACTIVE: "interactive",M2M: "m2m",@@ -316,6 +329,12 @@ export interface MCPToolsViewerProps {oauth2_flow?: string | null;/** When true (interactive OAuth2), the server uses PKCE passthrough. */delegate_auth_to_upstream?: boolean | null;+ /**+ * Read together with auth_type by gatewayMintsClientFor: an oauth_delegate dcr_bridge server is+ * NOT gateway-minted (its interactive sign-in registers through the browser front door), so the+ * tools-page Authorize must know the flag to decide whether to pre-register a client.+ */+ dcr_bridge?: boolean | null;/*** Connection field present on every OAuth2 flow (interactive and M2M alike),* so it does not indicate the mode. Retained for callers/other uses; not readdiff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex d6e9ba5665c..f5fe3990ba7 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -6737,6 +6737,7 @@ interface RegisterMcpOAuthClientPayload {grant_types?: string[];response_types?: string[];token_endpoint_auth_method?: string;+ redirect_uris?: string[];}export const registerMcpOAuthClient = async (diff --git a/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx b/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsxindex da4fd1f5eb4..6a7b201113e 100644--- a/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx+++ b/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx@@ -157,6 +157,10 @@ export const useMcpOAuthFlow = ({response_types: ["code"],token_endpoint_auth_method:temporaryPayload.credentials && temporaryPayload.credentials.client_secret ? "client_secret_post" : "none",+ // dcr_bridge servers relay this registration upstream and bind the+ // minted client to the browser's own callback; without it the relay+ // rejects the registration and the admin authorize dead-ends.+ redirect_uris: [callbackUrl()],});registeredClient = {clientId: registration?.client_id,diff --git a/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.test.tsx b/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.test.tsxnew file mode 100644index 00000000000..b7c65add47c--- /dev/null+++ b/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.test.tsx@@ -0,0 +1,89 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import * as networking from "@/components/networking";+import { useToolsOAuthFlow } from "./useToolsOAuthFlow";++vi.mock("@/components/networking", () => ({+ exchangeMcpOAuthToken: vi.fn(),+ registerMcpOAuthClient: vi.fn(),+ buildMcpOAuthAuthorizeUrl: vi.fn(() => "https://gw.example.com/v1/mcp/server/oauth/server-1/authorize"),+ getProxyBaseUrl: vi.fn(() => ""),+ serverRootPath: "",+}));++vi.mock("@/components/molecules/notifications_manager", () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++vi.mock("@/utils/pkce", () => ({+ generateCodeVerifier: () => "verifier-1",+ generateCodeChallenge: async () => "challenge-1",+}));++function renderFlow(options: { gatewayMintsClient?: boolean }) {+ return renderHook(() =>+ useToolsOAuthFlow({+ accessToken: "user-token",+ serverId: "server-1",+ serverAlias: "server one",+ userId: "user-1",+ gatewayMintsClient: options.gatewayMintsClient,+ onSuccess: vi.fn(),+ }),+ );+}++describe("useToolsOAuthFlow client registration", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ window.sessionStorage.clear();+ window.localStorage.clear();+ Object.defineProperty(window, "location", {+ value: { href: "https://app.example.com/ui?page=mcp-servers" },+ writable: true,+ configurable: true,+ });+ });++ it("skips browser-side client registration when the gateway mints the client", async () => {+ // Client-forwarded token modes: the gateway's /authorize mints and carries the+ // OAuth client itself, so a browser-side registration would only create an+ // extra orphan client at the IdP. The authorize URL must go out clientless.+ const { result } = renderFlow({ gatewayMintsClient: true });++ await act(async () => {+ await result.current.startOAuthFlow();+ });++ expect(networking.registerMcpOAuthClient).not.toHaveBeenCalled();+ expect(networking.buildMcpOAuthAuthorizeUrl).toHaveBeenCalledWith(+ expect.objectContaining({ serverId: "server-1", clientId: undefined }),+ );+ expect(window.location.href).toBe("https://gw.example.com/v1/mcp/server/oauth/server-1/authorize");+ });++ it("still registers browser-side for servers the gateway does not mint for", async () => {+ // The cells where gatewayMintsClientFor is false keep the browser-held client: an+ // oauth_delegate dcr_bridge server (interactive sign-in) and the legacy oauth2 passthrough both+ // register first, so the minted client_id rides the authorize URL through the front-door relay.+ vi.mocked(networking.registerMcpOAuthClient).mockResolvedValue({ client_id: "reg-client-1" });++ const { result } = renderFlow({});++ await act(async () => {+ await result.current.startOAuthFlow();+ });++ expect(networking.registerMcpOAuthClient).toHaveBeenCalledTimes(1);+ // The dcr_bridge relay rejects registrations without the client's own+ // callback, so the browser must bind its minted client to it.+ expect(networking.registerMcpOAuthClient).toHaveBeenCalledWith(+ "user-token",+ "server-1",+ expect.objectContaining({ redirect_uris: [expect.stringContaining("callback")] }),+ );+ expect(networking.buildMcpOAuthAuthorizeUrl).toHaveBeenCalledWith(+ expect.objectContaining({ serverId: "server-1", clientId: "reg-client-1" }),+ );+ });+});diff --git a/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.tsx b/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.tsxindex a538bb640c6..d21282ffcd7 100644--- a/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.tsx+++ b/ui/litellm-dashboard/src/hooks/useToolsOAuthFlow.tsx@@ -31,6 +31,13 @@ interface UseToolsOAuthFlowOptions {userId?: string | null;scopes?: string[];clientId?: string | null;+ /**+ * True for the client-forwarded token modes (true_passthrough / oauth_delegate): the gateway+ * mints the OAuth client itself during /authorize and carries it in the sealed state/code, so+ * the browser must not register a client of its own (each browser-side registration creates an+ * extra client at the IdP that the gateway's minted one then supersedes).+ */+ gatewayMintsClient?: boolean;onSuccess: (accessToken: string) => void;}@@ -61,6 +68,7 @@ export const useToolsOAuthFlow = ({userId,scopes,clientId: preClientId,+ gatewayMintsClient,onSuccess,}: UseToolsOAuthFlowOptions): UseToolsOAuthFlowResult => {const [status, setStatus] = useState<ToolsOAuthStatus>("idle");@@ -77,14 +85,19 @@ export const useToolsOAuthFlow = ({let clientId: string | undefined = preClientId ?? undefined;let clientSecret: string | undefined;+ const redirectUri = buildCallbackUrl();- if (!clientId) {+ if (!clientId && !gatewayMintsClient) {try {const reg = await registerMcpOAuthClient(accessToken, serverId, {client_name: serverAlias || serverId,grant_types: ["authorization_code", "refresh_token"],response_types: ["code"],token_endpoint_auth_method: "none",+ // dcr_bridge servers relay this registration upstream and bind the+ // minted client to the browser's own callback; without it the relay+ // rejects the registration and the flow dead-ends clientless.+ redirect_uris: [redirectUri],});clientId = reg?.client_id;clientSecret = reg?.client_secret;@@ -96,7 +109,6 @@ export const useToolsOAuthFlow = ({const verifier = generateCodeVerifier();const challenge = await generateCodeChallenge(verifier);const state = crypto.randomUUID();- const redirectUri = buildCallbackUrl();const scopeString = scopes?.filter((s) => s.trim()).join(" ");const authorizeUrl = buildMcpOAuthAuthorizeUrl({@@ -129,7 +141,7 @@ export const useToolsOAuthFlow = ({setStatus("error");NotificationsManager.error(msg);}- }, [accessToken, serverId, serverAlias, scopes, preClientId]);+ }, [accessToken, serverId, serverAlias, scopes, preClientId, gatewayMintsClient]);const resumeOAuthFlow = useCallback(async () => {if (typeof window === "undefined" || processingRef.current) return;