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): add ID-JAG (identity assertion authorization grant) support for MCP egress (#31516)
Yassin Kortame18966625d63
diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.pyindex 7129582ff2a..9fe970f7fa9 100644--- a/litellm/proxy/_experimental/mcp_server/db.py+++ b/litellm/proxy/_experimental/mcp_server/db.py@@ -375,6 +375,12 @@ def encrypt_credentials(credentials: MCPCredentials, encryption_key: Optional[stvalue=client_secret,new_encryption_key=encryption_key,)+ client_private_key = credentials.get("client_private_key")+ if client_private_key is not None:+ credentials["client_private_key"] = encrypt_value_helper(+ value=client_private_key,+ new_encryption_key=encryption_key,+ )# AWS SigV4 credential fieldsaws_access_key_id = credentials.get("aws_access_key_id")if aws_access_key_id is not None:@@ -406,6 +412,7 @@ def decrypt_credentials("auth_value","client_id","client_secret",+ "client_private_key","aws_access_key_id","aws_secret_access_key","aws_session_token",diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex ed6dde23d9e..1ba608b9510 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -93,6 +93,8 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchange_)from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (AuthorizationCodeConfig,+ CredError,+ IdJagConfig,PassthroughConfig,ServerSpec,TokenExchangeConfig,@@ -621,6 +623,47 @@ def _consumes_caller_authorization(server: MCPServer) -> bool:)+_REGISTRY_DUMP_SECRET_FIELDS = frozenset(+ {"authentication_token", "client_secret", "client_private_key", "aws_secret_access_key", "aws_session_token"}+)+++def _redacted_registry_dump(servers: dict[str, MCPServer]) -> dict[str, dict[str, str]]:+ """A JSON-safe view of the server registry with credential fields masked, for debug logging.++ The registry holds long-lived secrets as plain strings (the static token, OAuth client secret,+ the ID-JAG signing key, AWS keys); dumping them verbatim hands the gateway's client identity to+ anyone who can read debug logs.+ """+ dumps: dict[str, dict[str, object]] = {server_id: server.model_dump() for server_id, server in servers.items()}+ return {+ server_id: {+ field: ("**REDACTED**" if field in _REGISTRY_DUMP_SECRET_FIELDS and value is not None else str(value))+ for field, value in dump.items()+ }+ for server_id, dump in dumps.items()+ }+++def _to_server_spec_fail_closed(server: MCPServer) -> Optional[ServerSpec]:+ """`to_server_spec`, except a half-configured `oauth2_id_jag` server refuses instead of deferring.++ ID-JAG has no v1 arm, so deferring to v1 would let `resolve_mcp_auth` honor a caller x-mcp-*+ override or fall through to the static `authentication_token`, both of which bypass the per-user+ identity assertion the mode promises. That is an operator misconfiguration, not a fallback.+ """+ spec = to_server_spec(server)+ if spec is None and server.auth_type == MCPAuth.oauth2_id_jag:+ raise_public(+ CredError.of_misconfigured(+ "oauth2_id_jag requires token_exchange_endpoint, id_jag_resource_token_endpoint, "+ "client_id, and a client_secret or client_private_key; refusing to fall back to "+ "a static credential."+ )+ )+ return spec++def _caller_authorization_fans_out(server: MCPServer,scope_servers: Optional[list[MCPServer]],@@ -1326,6 +1369,12 @@ class MCPServerManager:"subject_token_type",DEFAULT_SUBJECT_TOKEN_TYPE,),+ # ID-JAG fields+ id_jag_resource_token_endpoint=server_config.get("id_jag_resource_token_endpoint", None),+ id_jag_resource=server_config.get("id_jag_resource", None),+ client_private_key=server_config.get("client_private_key", None),+ client_private_key_id=server_config.get("client_private_key_id", None),+ client_assertion_signing_alg=server_config.get("client_assertion_signing_alg", "RS256"),token_exchange_profile=server_config.get("token_exchange_profile", "rfc8693"),allow_sampling=bool(server_config.get("allow_sampling", False)),allow_elicitation=bool(server_config.get("allow_elicitation", False)),@@ -1346,7 +1395,9 @@ class MCPServerManager:base_url=server_config.get("url", ""),)- verbose_logger.debug(f"Loaded MCP Servers: {json.dumps(self.config_mcp_servers, indent=4, default=str)}")+ verbose_logger.debug(+ f"Loaded MCP Servers: {json.dumps(_redacted_registry_dump(self.config_mcp_servers), indent=4)}"+ )await self._hydrate_config_servers_dcr_clients()@@ -1797,6 +1848,21 @@ class MCPServerManager:subject_token_type=mcp_server.subject_token_typeor (credentials_dict.get("subject_token_type") if credentials_dict else None)or DEFAULT_SUBJECT_TOKEN_TYPE,+ # ID-JAG fields — read from credentials JSON blob+ id_jag_resource_token_endpoint=(+ credentials_dict.get("id_jag_resource_token_endpoint") if credentials_dict else None+ ),+ id_jag_resource=(credentials_dict.get("id_jag_resource") if credentials_dict else None),+ client_private_key=self._decrypt_credential_field(+ credentials_dict.get("client_private_key") if credentials_dict else None,+ "client_private_key",+ credentials_are_encrypted,+ ),+ client_private_key_id=(credentials_dict.get("client_private_key_id") if credentials_dict else None),+ client_assertion_signing_alg=(+ credentials_dict.get("client_assertion_signing_alg") if credentials_dict else None+ )+ or "RS256",token_exchange_profile=mcp_server.token_exchange_profileor (credentials_dict.get("token_exchange_profile") if credentials_dict else None)or "rfc8693",@@ -2673,9 +2739,10 @@ class MCPServerManager:)if not conflicts:return auth, extra_headers- if isinstance(spec.config, (TokenExchangeConfig, AuthorizationCodeConfig)):+ if isinstance(spec.config, (TokenExchangeConfig, AuthorizationCodeConfig, IdJagConfig)):# The resolver owns the per-user credential here (token_exchange's exchanged- # token, authorization_code's stored token). It is authoritative: a guardrail such+ # token, authorization_code's stored token, id_jag's minted assertion). It is+ # authoritative: a guardrail such# as MCPJWTSigner, static_headers, or any other injected Authorization must NOT# shadow it (otherwise the upstream gets e.g. the signer's JWT instead of the# exchanged token and rejects it). Drop the conflicting header so the resolved@@ -2766,20 +2833,23 @@ class MCPServerManager:Configured MCP client instance."""transport = server.transport or MCPTransport.sse- spec = None if transport == MCPTransport.stdio else to_server_spec(server)+ spec = None if transport == MCPTransport.stdio else _to_server_spec_fail_closed(server)provider = cred_provider or self._cred_provider# A caller-supplied per-request override (mcp_auth_header / x-mcp-*) defers to the v1 path# so it wins - except for the modes the v2 resolver owns per-caller (authorization_code's- # stored token, token_exchange's RFC 8693 minted token, and the passthrough modes'- # forwarded caller token). A caller must not be able to substitute another user's stored- # credential, nor silently disable the OBO exchange and forward an arbitrary bearer- # upstream, so we keep the v2 spec and ignore the override for these; the REST tools- # preview supplies its not-yet-persisted token through the resolver (cred_provider),- # never this path.+ # stored token, token_exchange's RFC 8693 minted token, id_jag's minted assertion, and the+ # passthrough modes' forwarded caller token). A caller must not be able to substitute another+ # user's stored credential, nor silently disable the OBO / ID-JAG exchange and forward an+ # arbitrary bearer upstream, so we keep the v2 spec and ignore the override for these; the+ # REST tools preview supplies its not-yet-persisted token through the resolver+ # (cred_provider), never this path.if (spec is not Noneand mcp_auth_header- and not isinstance(spec.config, (AuthorizationCodeConfig, PassthroughConfig, TokenExchangeConfig))+ and not isinstance(+ spec.config,+ (AuthorizationCodeConfig, IdJagConfig, PassthroughConfig, TokenExchangeConfig),+ )):spec = Noneauth_value = (@@ -4308,10 +4378,13 @@ class MCPServerManager:if server_auth_header is None:server_auth_header = mcp_auth_header- # Extract subject token for OAuth2 Token Exchange (OBO) flow+ # Extract subject token for OAuth2 Token Exchange (OBO) and ID-JAG flowssubject_token: Optional[str] = Noneextra_headers: Optional[dict[str, str]] = None- if mcp_server.auth_type == MCPAuth.oauth2_token_exchange:+ if mcp_server.auth_type in (+ MCPAuth.oauth2_token_exchange,+ MCPAuth.oauth2_id_jag,+ ):subject_token = self._extract_bearer_token(oauth2_headers, raw_headers)elif mcp_server.auth_type == MCPAuth.oauth2:if mcp_server.has_client_credentials:@@ -4413,10 +4486,10 @@ class MCPServerManager:arguments=arguments,)- if mcp_server.auth_type == MCPAuth.oauth2_token_exchange and subject_token:- # OBO: the exchanged token may have been revoked/rotated upstream since it was cached, so- # an upstream 401 gets one re-mint + retry. Gated to this mode; all others keep the plain- # single call below.+ if mcp_server.auth_type in (MCPAuth.oauth2_token_exchange, MCPAuth.oauth2_id_jag) and subject_token:+ # OBO / ID-JAG: the exchanged token may have been revoked/rotated upstream since it was+ # cached, so an upstream 401 gets one invalidate + re-mint + retry. Gated to these modes;+ # all others keep the plain single call below.async def _obo_call_tool_limited():async with self._limit_outbound_concurrency(mcp_server):return await self._obo_call_tool_with_retry(diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.pyindex 73166a45d6e..2bdb8770e4e 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py@@ -31,10 +31,14 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (AwsCredentialSource,AwsSigV4Config,Byok,+ ClientAuth,ClientCredentialsConfig,+ ClientSecretAuth,CredError,+ IdJagConfig,NoneConfig,PassthroughConfig,+ PrivateKeyJwtAuth,ServerSpec,SharedKey,StaticKeys,@@ -59,6 +63,10 @@ __all__ = ["AuthorizationCodeConfig","ClientCredentialsConfig","TokenExchangeConfig",+ "IdJagConfig",+ "ClientAuth",+ "PrivateKeyJwtAuth",+ "ClientSecretAuth","ApiKeyConfig","ApiKeySource","SharedKey",diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.pyindex e87e8081ced..6631e38f524 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py@@ -21,9 +21,13 @@ from typing_extensions import assert_neverfrom litellm.proxy._experimental.mcp_server.outbound_credentials.types import (ApiKeyConfig,AuthorizationCodeConfig,+ ClientAuth,+ ClientSecretAuth,CredError,+ IdJagConfig,NoneConfig,PassthroughConfig,+ PrivateKeyJwtAuth,ServerSpec,SharedKey,Subject,@@ -35,6 +39,9 @@ if TYPE_CHECKING:from litellm.proxy._types import UserAPIKeyAuthfrom litellm.types.mcp_server.mcp_server_manager import MCPServer+_TOKEN_EXCHANGE_SUBJECT_TOKEN_DEFAULT = "urn:ietf:params:oauth:token-type:access_token"+_ID_JAG_SUBJECT_TOKEN_DEFAULT = "urn:ietf:params:oauth:token-type:id_token"+def to_subject(user_api_key_auth: Optional[UserAPIKeyAuth], subject_token: Optional[str]) -> Subject:"""Map v1's authenticated principal onto the resolver's Subject.@@ -96,6 +103,8 @@ def to_server_spec(server: MCPServer) -> Optional[ServerSpec]:)# client_credentials (M2M) and delegate/passthrough oauth2 stay on v1return None+ case MCPAuth.oauth2_id_jag:+ return _id_jag_spec(server, resource)case MCPAuth.true_passthrough | MCPAuth.oauth_delegate:return ServerSpec(server_id=server.server_id, resource=resource, config=PassthroughConfig())case MCPAuth.oauth2_token_exchange:@@ -167,6 +176,58 @@ def _shared_key_spec()+def _id_jag_spec(server: MCPServer, resource: str) -> Optional[ServerSpec]:+ """Build an ID-JAG spec from the v1 server's raw fields, or defer (None) if half-configured.++ The enum already routes here, but a server missing an endpoint, ``client_id``, or any client-auth+ secret would make ``IdJagConfig`` raise at construction; returning None instead defers to v1 so a+ partially configured server does not 500. ``token_exchange_endpoint`` is leg 1 (the IdP org AS);+ leg 2 is ``id_jag_resource_token_endpoint`` (the upstream resource AS).+ """+ org_token_endpoint = server.token_exchange_endpoint+ resource_token_endpoint = server.id_jag_resource_token_endpoint+ client_id = server.client_id+ client_auth = _id_jag_client_auth(server)+ if not org_token_endpoint or not resource_token_endpoint or not client_id or client_auth is None:+ return None+ return ServerSpec(+ server_id=server.server_id,+ resource=resource,+ config=IdJagConfig(+ org_token_endpoint=org_token_endpoint,+ resource_token_endpoint=resource_token_endpoint,+ client_id=client_id,+ client_auth=client_auth,+ subject_token_type=_id_jag_subject_token_type(server),+ audience=server.audience,+ resource=server.id_jag_resource,+ scopes=tuple(server.scopes or ()),+ ),+ )+++def _id_jag_client_auth(server: MCPServer) -> Optional[ClientAuth]:+ """Private-key JWT when a key is configured, else client_secret, else None (defer to v1)."""+ if server.client_private_key:+ return PrivateKeyJwtAuth(+ private_key=SecretStr(server.client_private_key),+ key_id=server.client_private_key_id,+ signing_alg=server.client_assertion_signing_alg,+ )+ if server.client_secret:+ return ClientSecretAuth(client_secret=SecretStr(server.client_secret))+ return None+++def _id_jag_subject_token_type(server: MCPServer) -> str:+ """ID-JAG asserts the user's id_token, so the token-exchange access_token default maps to id_token;+ an explicitly configured value (e.g. a SAML2 assertion type) is honored verbatim."""+ configured = server.subject_token_type+ if configured and configured != _TOKEN_EXCHANGE_SUBJECT_TOKEN_DEFAULT:+ return configured+ return _ID_JAG_SUBJECT_TOKEN_DEFAULT++def raise_public(error: CredError) -> NoReturn:"""Map a resolver CredError onto the proxy's public HTTP contract. The one edge that raises."""match error.tag:diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.pyindex ecfd471190c..7e5c073870a 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py@@ -16,6 +16,8 @@ follow-up PR with their seam. Pure v2: no imports from v1.from __future__ import annotations+import hashlib+import httpxfrom typing_extensions import assert_never@@ -33,6 +35,11 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import (Ok,Result,)+from litellm.proxy._experimental.mcp_server.outbound_credentials.token_endpoint import (+ ExchangedToken,+ ExchangedTokenCache,+ TokenEndpointClient,+)from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger import (TokenExchanger,)@@ -42,16 +49,24 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (AuthSpecKind,AwsSigV4Config,Byok,+ ClientAuth,ClientCredentialsConfig,+ ClientSecretAuth,CredError,+ IdJagConfig,NoneConfig,PassthroughConfig,+ PrivateKeyJwtAuth,ServerSpec,SharedKey,Subject,TokenExchangeConfig,)+_TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"+_JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"+_ID_JAG_REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id-jag"+class _NullOAuthTokenStore:"""Fail-closed default: with no token store wired, every user reads as not authorized."""@@ -87,9 +102,13 @@ class UpstreamCredentialProvider:self,oauth_token_store: OAuthTokenStore | None = None,token_exchanger: TokenExchanger | None = None,+ token_endpoint: TokenEndpointClient | None = None,+ exchanged_tokens: ExchangedTokenCache | None = None,) -> None:self._oauth_token_store: OAuthTokenStore = oauth_token_store or _NullOAuthTokenStore()self._token_exchanger: TokenExchanger = token_exchanger or _NullTokenExchanger()+ self._token_endpoint: TokenEndpointClient = token_endpoint or TokenEndpointClient()+ self._exchanged_tokens: ExchangedTokenCache = exchanged_tokens or ExchangedTokenCache()async def resolve_credentials(self, subject: Subject, server: ServerSpec) -> Result[httpx.Auth, CredError]:match server.config:@@ -103,6 +122,8 @@ class UpstreamCredentialProvider:return _not_implemented(AuthSpecKind.client_credentials)case TokenExchangeConfig() as config:return await self._token_exchange(subject, server, config)+ case IdJagConfig() as config:+ return await self._id_jag(subject, server, config)case AuthorizationCodeConfig():return await self._authorization_code(subject, server)case AwsSigV4Config():@@ -141,6 +162,53 @@ class UpstreamCredentialProvider:return Error(CredError.of_not_implemented("api_key BYOK source not implemented yet"))assert_never(config.key_source)+ async def _id_jag(self, subject: Subject, server: ServerSpec, config: IdJagConfig) -> Result[httpx.Auth, CredError]:+ if subject.inbound_token is None:+ return Error(+ CredError.of_precondition_required(+ "ID-JAG requires a caller identity token; it asserts the calling "+ "user's identity upstream and cannot use a static credential."+ )+ )+ token = subject.inbound_token.get_secret_value()+ cache_key = _id_jag_cache_key(token, server.server_id, config)++ async def _exchange() -> Result[ExchangedToken, CredError]:+ leg1_params = {+ "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE,+ "requested_token_type": _ID_JAG_REQUESTED_TOKEN_TYPE,+ "subject_token": token,+ "subject_token_type": config.subject_token_type,+ **({"audience": config.audience} if config.audience else {}),+ **({"resource": config.resource} if config.resource else {}),+ **({"scope": " ".join(config.scopes)} if config.scopes else {}),+ }+ match await self._token_endpoint.fetch(+ config.org_token_endpoint,+ config.client_id,+ leg1_params,+ config.client_auth,+ ):+ case Error(err):+ return Error(err)+ case Ok(id_jag):+ leg2_params = {+ "grant_type": _JWT_BEARER_GRANT_TYPE,+ "assertion": id_jag.access_token,+ }+ return await self._token_endpoint.fetch(+ config.resource_token_endpoint,+ config.client_id,+ leg2_params,+ config.client_auth,+ )++ match await self._exchanged_tokens.get_or_compute(cache_key, _exchange):+ case Ok(access_token):+ return Ok(StaticHeaderAuth(f"Bearer {access_token}"))+ case Error(err):+ return Error(err)+async def _authorization_code(self, subject: Subject, server: ServerSpec) -> Result[StaticHeaderAuth, CredError]:token = await self._authz_token(subject, server)if token is None:@@ -176,13 +244,19 @@ class UpstreamCredentialProvider:"""Drop any cached credential the resolver owns for this `(subject, server)`.Used after an upstream rejects the injected credential, so the next resolve re-mints rather- than serving the same rejected token until TTL. Only `token_exchange` holds a re-mintable- cached credential here; other modes are a no-op.+ than serving the same rejected token until TTL. `token_exchange` and `id_jag` hold a+ re-mintable cached credential here; other modes are a no-op."""- if isinstance(server.config, TokenExchangeConfig) and subject.inbound_token is not None:+ if subject.inbound_token is None:+ return+ if isinstance(server.config, TokenExchangeConfig):await self._token_exchanger.invalidate(subject.inbound_token.get_secret_value(), server, server.config, tenant_id=subject.tenant_id)+ if isinstance(server.config, IdJagConfig):+ self._exchanged_tokens.invalidate(+ _id_jag_cache_key(subject.inbound_token.get_secret_value(), server.server_id, server.config)+ )async def _authz_token(self, subject: Subject, server: ServerSpec) -> OAuthToken | None:"""The user's authorization_code token, or None when absent or the store is unreachable.@@ -196,5 +270,41 @@ class UpstreamCredentialProvider:return None+def _id_jag_cache_key(subject_token: str, server_id: str, config: IdJagConfig) -> str:+ """Bind the cached leg-2 bearer to the caller token, the server, AND the config that minted it.++ Every exchange parameter derives from the config (endpoints, audience, resource, scopes, client+ auth), so a server update that changes any of them must change the key; otherwise the old bearer,+ authorized under the old policy, keeps being served until its TTL. Everything is hashed, so no+ secret is held in the key.+ """+ material = "\x00".join(+ (+ subject_token,+ server_id,+ config.org_token_endpoint,+ config.resource_token_endpoint,+ config.client_id,+ _client_auth_fingerprint(config.client_auth),+ config.subject_token_type,+ config.audience or "",+ config.resource or "",+ " ".join(config.scopes),+ )+ )+ return hashlib.sha256(material.encode()).hexdigest()+++def _client_auth_fingerprint(client_auth: ClientAuth) -> str:+ match client_auth:+ case PrivateKeyJwtAuth() as auth:+ return "\x00".join(+ ("private_key_jwt", auth.private_key.get_secret_value(), auth.key_id or "", auth.signing_alg)+ )+ case ClientSecretAuth() as auth:+ return "\x00".join(("client_secret", auth.client_secret.get_secret_value()))+ assert_never(client_auth)++def _not_implemented(kind: AuthSpecKind) -> Result[httpx.Auth, CredError]:return Error(CredError.of_not_implemented(f"{kind.value}: resolver arm not implemented yet"))diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_endpoint.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_endpoint.pynew file mode 100644index 00000000000..4bc5732ec0e--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_endpoint.py@@ -0,0 +1,225 @@+"""An authenticated OAuth token-endpoint call plus a short-lived-token cache.++`TokenEndpointClient.fetch` POSTs one grant to a token endpoint, authenticating the gateway as+an OAuth client via `client_auth` (RFC 7523 private-key JWT, or `client_secret_post`), and returns+the minted token or a typed `CredError`. `ExchangedTokenCache` memoizes the final token string per+opaque cache key with per-key single-flight, so concurrent callers share one round-trip and a hit+skips the endpoint entirely.++Pure v2: no imports from the v1 MCP auth handlers. The multi-leg flows that compose these (ID-JAG,+and later token_exchange / client_credentials) live in the resolver arms; this collaborator owns+only the single authenticated call and the cache.+"""++from __future__ import annotations++import asyncio+import json+import time+import uuid+import weakref+from collections.abc import Awaitable, Callable, Mapping+from dataclasses import dataclass++import httpx+import jwt+from pydantic import BaseModel, ValidationError+from typing_extensions import assert_never++from litellm._logging import verbose_proxy_logger+from litellm.caching.in_memory_cache import InMemoryCache+from litellm.constants import (+ MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL,+ MCP_OAUTH2_TOKEN_CACHE_MIN_TTL,+ MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS,+ MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE,+)+from litellm.exceptions import Timeout+from litellm.llms.custom_httpx.http_handler import (+ get_async_httpx_client, # pyright: ignore[reportUnknownVariableType] # litellm http handler is untyped+)+from litellm.proxy._experimental.mcp_server.outbound_credentials.result import (+ Error,+ Ok,+ Result,+)+from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (+ ClientAuth,+ ClientSecretAuth,+ CredError,+ PrivateKeyJwtAuth,+)+from litellm.types.llms.custom_http import httpxSpecialProvider++CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"+CLIENT_ASSERTION_LIFETIME_SECONDS = 60+++@dataclass(frozen=True, slots=True)+class ExchangedToken:+ access_token: str+ expires_in: int | None+++class _TokenEndpointResponse(BaseModel):+ access_token: str+ expires_in: int | None = None+++class TokenEndpointClient:+ """One authenticated POST to an OAuth token endpoint, returning the minted token as a value."""++ async def fetch(+ self,+ endpoint: str,+ client_id: str,+ grant_params: Mapping[str, str],+ client_auth: ClientAuth,+ ) -> Result[ExchangedToken, CredError]:+ try:+ data = {**grant_params, **_client_auth_params(endpoint, client_id, client_auth)}+ except (ValueError, TypeError, NotImplementedError, jwt.PyJWTError):+ verbose_proxy_logger.warning("MCP token endpoint %s: could not sign the client assertion", endpoint)+ return Error(+ CredError.of_misconfigured(+ "token exchange failed: could not sign the client assertion; "+ "check client_private_key and client_assertion_signing_alg"+ )+ )+ try:+ raw = await _post_form(endpoint, data)+ except httpx.HTTPStatusError as exc:+ verbose_proxy_logger.warning(+ "MCP token endpoint %s failed with status %s", endpoint, exc.response.status_code+ )+ return Error(+ CredError.of_upstream_unavailable(f"token exchange failed with status {exc.response.status_code}")+ )+ except (httpx.RequestError, Timeout) as exc:+ verbose_proxy_logger.warning("MCP token endpoint %s unreachable: %s", endpoint, type(exc).__name__)+ return Error(+ CredError.of_upstream_unavailable(+ f"token exchange failed: token endpoint unreachable ({type(exc).__name__})"+ )+ )+ except json.JSONDecodeError:+ verbose_proxy_logger.warning("MCP token endpoint %s returned a non-JSON response", endpoint)+ return Error(+ CredError.of_upstream_unavailable("token exchange failed: token endpoint returned a non-JSON response")+ )+ if raw is None:+ verbose_proxy_logger.warning("MCP token endpoint %s returned no response", endpoint)+ return Error(CredError.of_upstream_unavailable("token exchange failed: no response from token endpoint"))+ try:+ parsed = _TokenEndpointResponse.model_validate(raw)+ except ValidationError:+ verbose_proxy_logger.warning("MCP token endpoint %s response missing access_token", endpoint)+ return Error(+ CredError.of_upstream_unavailable("token exchange failed: token endpoint response missing access_token")+ )+ return Ok(ExchangedToken(access_token=parsed.access_token, expires_in=parsed.expires_in))+++class ExchangedTokenCache:+ """Memoizes the final token string per key, single-flighting concurrent misses on one lock."""++ def __init__(self) -> None:+ self._cache = InMemoryCache(+ max_size_in_memory=MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE,+ default_ttl=MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL,+ )+ self._locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()++ async def get_or_compute(+ self,+ cache_key: str,+ compute: Callable[[], Awaitable[Result[ExchangedToken, CredError]]],+ ) -> Result[str, CredError]:+ cached = self._get(cache_key)+ if cached is not None:+ return Ok(cached)+ async with self._lock(cache_key):+ cached = self._get(cache_key)+ if cached is not None:+ return Ok(cached)+ match await compute():+ case Ok(token):+ self._cache.set_cache( # pyright: ignore[reportUnknownMemberType] # InMemoryCache is untyped+ cache_key,+ token.access_token,+ ttl=_cache_ttl_seconds(token.expires_in),+ )+ return Ok(token.access_token)+ case Error(err):+ return Error(err)++ def invalidate(self, cache_key: str) -> None:+ """Evict one cached token so the next `get_or_compute` re-mints (e.g. after an upstream 401)."""+ self._cache.delete_cache(cache_key) # pyright: ignore[reportUnknownMemberType] # InMemoryCache is untyped++ def _get(self, cache_key: str) -> str | None:+ value = self._cache.get_cache(cache_key) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType] # InMemoryCache is untyped; narrowed by isinstance below+ return value if isinstance(value, str) else None++ def _lock(self, cache_key: str) -> asyncio.Lock:+ lock = self._locks.get(cache_key)+ if lock is None:+ lock = asyncio.Lock()+ self._locks[cache_key] = lock+ return lock+++def _cache_ttl_seconds(expires_in: int | None) -> int:+ lifetime = expires_in if expires_in is not None else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL+ return max(+ lifetime - MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS,+ MCP_OAUTH2_TOKEN_CACHE_MIN_TTL,+ )+++async def _post_form(endpoint: str, data: dict[str, str]) -> object | None:+ # litellm's httpx handler and httpx.Response are only partially typed; the token endpoint+ # returns a JSON object that `_TokenEndpointResponse` validates, so the untyped boundary is+ # contained here. A non-2xx raises `httpx.HTTPStatusError`, an unreachable endpoint raises+ # `httpx.RequestError` (or litellm's `Timeout`, which the handler substitutes for+ # `httpx.TimeoutException`), and a non-JSON body raises `json.JSONDecodeError`; `fetch` maps+ # each to a CredError.+ client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) # pyright: ignore[reportUnknownVariableType] # litellm http handler is untyped+ response = await client.post(endpoint, data=data) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType] # litellm http handler is untyped+ if response is None:+ return None+ response.raise_for_status()+ return response.json() # pyright: ignore[reportAny] # untyped JSON; validated by _TokenEndpointResponse in fetch+++def _client_auth_params(endpoint: str, client_id: str, client_auth: ClientAuth) -> dict[str, str]:+ match client_auth:+ case PrivateKeyJwtAuth() as auth:+ return {+ "client_id": client_id,+ "client_assertion_type": CLIENT_ASSERTION_TYPE,+ "client_assertion": _client_assertion(endpoint, client_id, auth),+ }+ case ClientSecretAuth() as auth:+ return {+ "client_id": client_id,+ "client_secret": auth.client_secret.get_secret_value(),+ }+ assert_never(client_auth)+++def _client_assertion(endpoint: str, client_id: str, auth: PrivateKeyJwtAuth) -> str:+ now = int(time.time())+ return jwt.encode(+ {+ "iss": client_id,+ "sub": client_id,+ "aud": endpoint,+ "jti": uuid.uuid4().hex,+ "iat": now,+ "exp": now + CLIENT_ASSERTION_LIFETIME_SECONDS,+ },+ auth.private_key.get_secret_value(),+ algorithm=auth.signing_alg,+ headers={"kid": auth.key_id} if auth.key_id else None,+ )diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.pyindex 7e04be4f045..64a20255ab2 100644--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py@@ -56,6 +56,7 @@ class AuthSpecKind(str, Enum):authorization_code = "authorization_code" # per-user 3LO; gateway-stored tokenclient_credentials = "client_credentials" # gateway service account (M2M)token_exchange = "token_exchange" # RFC 8693: token endpoint + subject_token (OBO)+ id_jag = "id_jag" # draft-ietf-oauth-identity-assertion-authz-grant: two-leg exchange then jwt-bearerapi_key = "api_key" # static header, any scheme (BYOK = per-user-seeded source)passthrough = "passthrough" # client forwards an upstream-audience tokennone = "none" # no upstream credential; resolve yields a no-op auth, never an error@@ -225,6 +226,49 @@ class TokenExchangeConfig(BaseModel):scopes: tuple[str, ...] = ()+class PrivateKeyJwtAuth(BaseModel):+ """RFC 7523 private-key-JWT client authentication: the gateway signs a `client_assertion`."""++ model_config = ConfigDict(frozen=True)+ source: Literal["private_key_jwt"] = "private_key_jwt"+ private_key: SecretStr+ key_id: str | None = None+ signing_alg: str = "RS256"+++class ClientSecretAuth(BaseModel):+ """`client_secret_post` client authentication: the gateway posts `client_id` + `client_secret`."""++ model_config = ConfigDict(frozen=True)+ source: Literal["client_secret"] = "client_secret"+ client_secret: SecretStr+++ClientAuth = Annotated[PrivateKeyJwtAuth | ClientSecretAuth, Field(discriminator="source")]+++class IdJagConfig(BaseModel):+ """draft-ietf-oauth-identity-assertion-authz-grant (Okta "AI agent token exchange").++ Two legs: leg 1 is an RFC 8693 token exchange at the IdP org AS (`org_token_endpoint`) that+ swaps the caller's identity token for an ID-JAG assertion; leg 2 is an RFC 7523 jwt-bearer at+ the upstream resource AS (`resource_token_endpoint`) that swaps the assertion for the access+ token. The gateway authenticates to both endpoints as `client_id` via `client_auth`. Required+ fields are enforced at construction so a half-configured server cannot reach the arm.+ """++ model_config = ConfigDict(frozen=True)+ kind: Literal[AuthSpecKind.id_jag] = AuthSpecKind.id_jag+ org_token_endpoint: str+ resource_token_endpoint: str+ client_id: str+ client_auth: ClientAuth+ subject_token_type: str = "urn:ietf:params:oauth:token-type:id_token"+ audience: str | None = None+ resource: str | None = None+ scopes: tuple[str, ...] = ()++class SharedKey(BaseModel):"""A fixed key configured on the server, identical for every caller."""@@ -323,6 +367,7 @@ AuthConfig = Annotated[AuthorizationCodeConfig| ClientCredentialsConfig| TokenExchangeConfig+ | IdJagConfig| ApiKeyConfig| PassthroughConfig| NoneConfigdiff --git a/litellm/types/mcp.py b/litellm/types/mcp.pyindex ac411ad9d9a..377ba669082 100644--- a/litellm/types/mcp.py+++ b/litellm/types/mcp.py@@ -38,6 +38,7 @@ class MCPAuth(str, enum.Enum):aws_sigv4 = "aws_sigv4"token = "token"oauth2_token_exchange = "oauth2_token_exchange"+ oauth2_id_jag = "oauth2_id_jag"true_passthrough = "true_passthrough"oauth_delegate = "oauth_delegate"@@ -62,6 +63,7 @@ MCPAuthType = Optional[MCPAuth.aws_sigv4,MCPAuth.token,MCPAuth.oauth2_token_exchange,+ MCPAuth.oauth2_id_jag,MCPAuth.true_passthrough,MCPAuth.oauth_delegate,]@@ -159,6 +161,31 @@ class MCPCredentials(TypedDict, total=False):the top-level request field."""+ id_jag_resource_token_endpoint: Optional[str]+ """+ Resource authorization server JWT-bearer (RFC 7523) endpoint for ID-JAG leg 2+ """++ id_jag_resource: Optional[str]+ """+ Optional RFC 8707 resource indicator sent on ID-JAG leg 1+ """++ client_private_key: Optional[str]+ """+ PEM private key used to sign the private-key-JWT client_assertion (RFC 7523)+ """++ client_private_key_id: Optional[str]+ """+ Key id (kid) advertised in the client_assertion JWT header+ """++ client_assertion_signing_alg: Optional[str]+ """+ Signing algorithm for the client_assertion JWT. Default: RS256+ """+token_endpoint_auth_method: Optional[MCPTokenEndpointAuthMethod]"""How the gateway authenticates to the upstream token endpoint. "client_secret_basic"diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.pyindex d0d8cc4cb28..8ae974b19a6 100644--- a/litellm/types/mcp_server/mcp_server_manager.py+++ b/litellm/types/mcp_server/mcp_server_manager.py@@ -87,6 +87,15 @@ class MCPServer(BaseModel):token_exchange_endpoint: Optional[str] = Noneaudience: Optional[str] = Nonesubject_token_type: str = DEFAULT_SUBJECT_TOKEN_TYPE+ # ID-JAG fields (draft-ietf-oauth-identity-assertion-authz-grant).+ # Leg 1 reuses token_exchange_endpoint (IdP org-AS), audience (resource-AS+ # identifier), scopes, subject_token_type, client_id/client_secret. Leg 2+ # posts the ID-JAG assertion to id_jag_resource_token_endpoint.+ id_jag_resource_token_endpoint: Optional[str] = None+ id_jag_resource: Optional[str] = None+ client_private_key: Optional[str] = None+ client_private_key_id: Optional[str] = None+ client_assertion_signing_alg: str = "RS256"# Wire dialect: "rfc8693" (standard token-exchange grant) or "entra_obo" (Microsoft Entra# On-Behalf-Of, the RFC 7523 jwt-bearer grant + requested_token_use extension)token_exchange_profile: str = "rfc8693"diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.pyindex 17960e917a4..707374e7061 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_adapter.py@@ -21,9 +21,12 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter importfrom litellm.proxy._experimental.mcp_server.outbound_credentials.types import (ApiKeyConfig,AuthorizationCodeConfig,+ ClientSecretAuth,CredError,+ IdJagConfig,NoneConfig,PassthroughConfig,+ PrivateKeyJwtAuth,SharedKey,TokenExchangeConfig,)@@ -35,6 +38,21 @@ def _server(**kwargs) -> MCPServer:return MCPServer(server_id="s", name="n", transport=MCPTransport.http, **kwargs)+def _id_jag_server(**overrides) -> MCPServer:+ defaults = dict(+ auth_type=MCPAuth.oauth2_id_jag,+ url="https://mcp.example.com/mcp",+ client_id="litellm-client-id",+ client_secret="litellm-client-secret",+ token_exchange_endpoint="https://idp.example.com/token",+ id_jag_resource_token_endpoint="https://mcp-as.example.com/token",+ audience="api://mcp-server",+ scopes=["mcp.read", "mcp.write"],+ )+ defaults.update(overrides)+ return _server(**defaults)++def test_none_maps_to_none_config():spec = to_server_spec(_server(auth_type=None))assert spec is not None@@ -413,3 +431,63 @@ def test_raise_token_exchange_challenge_uses_insufficient_claims_with_claims_preassert 'error="invalid_token"' not in wwwassert f'claims="{base64.b64encode(claims.encode()).decode()}"' in wwwassert claims not in www # raw JSON never appears; only the base64 form+++def test_id_jag_client_secret_maps_to_config():+ spec = to_server_spec(_id_jag_server())+ assert spec is not None and isinstance(spec.config, IdJagConfig)+ assert spec.config.org_token_endpoint == "https://idp.example.com/token"+ assert spec.config.resource_token_endpoint == "https://mcp-as.example.com/token"+ assert spec.config.client_id == "litellm-client-id"+ assert spec.config.audience == "api://mcp-server"+ assert spec.config.scopes == ("mcp.read", "mcp.write")+ # ID-JAG asserts the user's id_token; the access_token default maps to id_token.+ assert spec.config.subject_token_type == "urn:ietf:params:oauth:token-type:id_token"+ assert isinstance(spec.config.client_auth, ClientSecretAuth)+ assert spec.config.client_auth.client_secret.get_secret_value() == (+ "litellm-client-secret"+ )+++def test_id_jag_private_key_maps_to_private_key_jwt_auth():+ spec = to_server_spec(+ _id_jag_server(+ client_secret=None,+ client_private_key="PEM-DATA",+ client_private_key_id="kid-1",+ client_assertion_signing_alg="RS384",+ )+ )+ assert spec is not None and isinstance(spec.config, IdJagConfig)+ assert isinstance(spec.config.client_auth, PrivateKeyJwtAuth)+ assert spec.config.client_auth.private_key.get_secret_value() == "PEM-DATA"+ assert spec.config.client_auth.key_id == "kid-1"+ assert spec.config.client_auth.signing_alg == "RS384"+++def test_id_jag_private_key_wins_over_client_secret():+ spec = to_server_spec(_id_jag_server(client_private_key="PEM-DATA"))+ assert spec is not None and isinstance(spec.config, IdJagConfig)+ assert isinstance(spec.config.client_auth, PrivateKeyJwtAuth)+++def test_id_jag_honors_explicit_subject_token_type():+ spec = to_server_spec(+ _id_jag_server(subject_token_type="urn:ietf:params:oauth:token-type:saml2")+ )+ assert spec is not None and isinstance(spec.config, IdJagConfig)+ assert spec.config.subject_token_type == "urn:ietf:params:oauth:token-type:saml2"+++ "server",+ [+ _id_jag_server(token_exchange_endpoint=None),+ _id_jag_server(id_jag_resource_token_endpoint=None),+ _id_jag_server(client_id=None),+ _id_jag_server(client_secret=None, client_private_key=None),+ ],+)+def test_id_jag_half_configured_defers_to_v1(server):+ # A half-configured server must defer (None) rather than 500 at IdJagConfig construction.+ assert to_server_spec(server) is Nonediff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.pyindex c88027abcd4..ba7720ffd51 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_resolver.py@@ -16,8 +16,10 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials import (AwsSigV4Config,Byok,ClientCredentialsConfig,+ ClientSecretAuth,CredError,Error,+ IdJagConfig,NoneConfig,NoOpAuth,Ok,@@ -34,10 +36,40 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_stoOAuthToken,TokenStoreUnavailable,)+from litellm.proxy._experimental.mcp_server.outbound_credentials.token_endpoint import (+ ExchangedToken,+)_SUBJECT = Subject(tenant_id="", subject_id="")+def _id_jag_config() -> IdJagConfig:+ return IdJagConfig(+ org_token_endpoint="https://idp.example.com/token",+ resource_token_endpoint="https://mcp-as.example.com/token",+ client_id="litellm",+ client_auth=ClientSecretAuth(client_secret=SecretStr("s")),+ audience="api://mcp",+ scopes=("mcp.read",),+ )+++class _FakeTokenEndpoint:+ """Records each fetch and returns the next canned Result, leg by leg."""++ def __init__(self, results: list[Result[ExchangedToken, CredError]]) -> None:+ self._results = list(results)+ self.calls: list[tuple[str, str, dict[str, str]]] = []++ async def fetch(self, endpoint, client_id, grant_params, client_auth):+ self.calls.append((endpoint, client_id, dict(grant_params)))+ return self._results.pop(0)+++def _with_inbound(token: str) -> Subject:+ return Subject(tenant_id="", subject_id="alice", inbound_token=SecretStr(token))++def _spec(config):return ServerSpec(server_id="s", resource="https://upstream.example.com", config=config)@@ -305,3 +337,183 @@ async def test_unbuilt_arms_fail_closed_with_not_implemented(label, config):result = await UpstreamCredentialProvider().resolve_credentials(_SUBJECT, _spec(config))assert isinstance(result, Error)assert result.error.tag == "not_implemented"+++async def test_id_jag_runs_both_legs_and_returns_the_leg2_bearer():+ endpoint = _FakeTokenEndpoint(+ [+ Ok(ExchangedToken(access_token="the-id-jag", expires_in=300)),+ Ok(ExchangedToken(access_token="final-access", expires_in=3600)),+ ]+ )+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)+ result = await provider.resolve_credentials(+ _with_inbound("user-id-token"), _spec(_id_jag_config())+ )++ assert isinstance(result, Ok)+ assert _emitted(result.ok)["Authorization"] == "Bearer final-access"++ leg1_endpoint, _, leg1_params = endpoint.calls[0]+ assert leg1_endpoint == "https://idp.example.com/token"+ assert (+ leg1_params["grant_type"] == "urn:ietf:params:oauth:grant-type:token-exchange"+ )+ assert (+ leg1_params["requested_token_type"] == "urn:ietf:params:oauth:token-type:id-jag"+ )+ assert leg1_params["subject_token"] == "user-id-token"++ leg2_endpoint, _, leg2_params = endpoint.calls[1]+ assert leg2_endpoint == "https://mcp-as.example.com/token"+ assert leg2_params["grant_type"] == "urn:ietf:params:oauth:grant-type:jwt-bearer"+ # The leg-1 token is forwarded verbatim as the leg-2 assertion.+ assert leg2_params["assertion"] == "the-id-jag"+++async def test_id_jag_without_inbound_token_is_precondition_required_no_http():+ endpoint = _FakeTokenEndpoint([])+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)+ result = await provider.resolve_credentials(+ Subject(tenant_id="", subject_id="alice"), _spec(_id_jag_config())+ )++ assert isinstance(result, Error)+ assert result.error.tag == "precondition_required"+ assert endpoint.calls == []+++async def test_id_jag_propagates_a_leg1_error_without_calling_leg2():+ endpoint = _FakeTokenEndpoint(+ [Error(CredError.of_upstream_unavailable("leg1 down"))]+ )+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)+ result = await provider.resolve_credentials(+ _with_inbound("user-id-token"), _spec(_id_jag_config())+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+ assert "leg1 down" in result.error.summary+ assert len(endpoint.calls) == 1+++async def test_id_jag_propagates_a_leg2_error():+ endpoint = _FakeTokenEndpoint(+ [+ Ok(ExchangedToken(access_token="the-id-jag", expires_in=300)),+ Error(CredError.of_upstream_unavailable("leg2 forbidden")),+ ]+ )+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)+ result = await provider.resolve_credentials(+ _with_inbound("user-id-token"), _spec(_id_jag_config())+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+ assert "leg2 forbidden" in result.error.summary+ assert len(endpoint.calls) == 2+++def _two_leg_ok(bearer: str) -> list:+ return [+ Ok(ExchangedToken(access_token="the-id-jag", expires_in=300)),+ Ok(ExchangedToken(access_token=bearer, expires_in=3600)),+ ]+++async def test_id_jag_reuses_the_cached_bearer_for_an_unchanged_config():+ endpoint = _FakeTokenEndpoint(_two_leg_ok("first-bearer"))+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)++ first = await provider.resolve_credentials(_with_inbound("user-id-token"), _spec(_id_jag_config()))+ second = await provider.resolve_credentials(_with_inbound("user-id-token"), _spec(_id_jag_config()))++ assert isinstance(first, Ok) and isinstance(second, Ok)+ assert _emitted(second.ok)["Authorization"] == "Bearer first-bearer"+ assert len(endpoint.calls) == 2+++ "changed",+ [+ _id_jag_config().model_copy(update={"audience": "api://other"}),+ _id_jag_config().model_copy(update={"resource": "https://other.example.com/mcp"}),+ _id_jag_config().model_copy(update={"scopes": ("mcp.read", "mcp.write")}),+ _id_jag_config().model_copy(update={"org_token_endpoint": "https://idp.example.com/v2/token"}),+ _id_jag_config().model_copy(update={"resource_token_endpoint": "https://mcp-as.example.com/v2/token"}),+ _id_jag_config().model_copy(update={"client_id": "litellm-rotated"}),+ _id_jag_config().model_copy(update={"client_auth": ClientSecretAuth(client_secret=SecretStr("rotated"))}),+ _id_jag_config().model_copy(update={"subject_token_type": "urn:ietf:params:oauth:token-type:saml2"}),+ ],+ ids=[+ "audience",+ "resource",+ "scopes",+ "org_token_endpoint",+ "resource_token_endpoint",+ "client_id",+ "client_auth",+ "subject_token_type",+ ],+)+async def test_id_jag_config_change_forces_a_fresh_exchange(changed):+ endpoint = _FakeTokenEndpoint(_two_leg_ok("old-policy-bearer") + _two_leg_ok("new-policy-bearer"))+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)++ before = await provider.resolve_credentials(_with_inbound("user-id-token"), _spec(_id_jag_config()))+ after = await provider.resolve_credentials(_with_inbound("user-id-token"), _spec(changed))++ assert isinstance(before, Ok) and isinstance(after, Ok)+ assert _emitted(after.ok)["Authorization"] == "Bearer new-policy-bearer"+ assert len(endpoint.calls) == 4+++async def test_id_jag_does_not_share_the_cached_bearer_across_caller_tokens():+ endpoint = _FakeTokenEndpoint(_two_leg_ok("alice-bearer") + _two_leg_ok("bob-bearer"))+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)++ alice = await provider.resolve_credentials(_with_inbound("alice-id-token"), _spec(_id_jag_config()))+ bob = await provider.resolve_credentials(_with_inbound("bob-id-token"), _spec(_id_jag_config()))++ assert isinstance(alice, Ok) and isinstance(bob, Ok)+ assert _emitted(bob.ok)["Authorization"] == "Bearer bob-bearer"+ assert len(endpoint.calls) == 4+++async def test_invalidate_credentials_evicts_the_id_jag_bearer_so_the_next_resolve_re_exchanges():+ endpoint = _FakeTokenEndpoint(_two_leg_ok("rejected-bearer") + _two_leg_ok("fresh-bearer"))+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)+ subject = _with_inbound("user-id-token")++ first = await provider.resolve_credentials(subject, _spec(_id_jag_config()))+ await provider.invalidate_credentials(subject, _spec(_id_jag_config()))+ second = await provider.resolve_credentials(subject, _spec(_id_jag_config()))++ assert isinstance(first, Ok) and isinstance(second, Ok)+ assert _emitted(second.ok)["Authorization"] == "Bearer fresh-bearer"+ assert len(endpoint.calls) == 4+++async def test_invalidate_credentials_for_id_jag_is_a_noop_without_a_caller_token():+ endpoint = _FakeTokenEndpoint(_two_leg_ok("cached-bearer"))+ provider = UpstreamCredentialProvider(token_endpoint=endpoint)+ subject = _with_inbound("user-id-token")++ first = await provider.resolve_credentials(subject, _spec(_id_jag_config()))+ await provider.invalidate_credentials(Subject(tenant_id="", subject_id="alice"), _spec(_id_jag_config()))+ second = await provider.resolve_credentials(subject, _spec(_id_jag_config()))++ assert isinstance(first, Ok) and isinstance(second, Ok)+ assert _emitted(second.ok)["Authorization"] == "Bearer cached-bearer"+ assert len(endpoint.calls) == 2diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_endpoint.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_endpoint.pynew file mode 100644index 00000000000..f100bd56f8f--- /dev/null+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_endpoint.py@@ -0,0 +1,408 @@+"""Tests for the v2 token-endpoint collaborator.++`TokenEndpointClient.fetch` makes one authenticated POST and returns the minted token as a value;+`ExchangedTokenCache` memoizes it with per-key single-flight. These pin the grant/client-auth wire+shape, the private-key-JWT vs client_secret authentication, the error-as-value mapping, and the+cache's hit/single-flight behavior. Each assertion fails under a real mutation of the feature.+"""++import asyncio+import json+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import jwt+import litellm+import pytest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa++from litellm.proxy._experimental.mcp_server.outbound_credentials.result import (+ Error,+ Ok,+ Result,+)+from litellm.proxy._experimental.mcp_server.outbound_credentials.token_endpoint import (+ CLIENT_ASSERTION_TYPE,+ ExchangedToken,+ ExchangedTokenCache,+ TokenEndpointClient,+)+from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (+ ClientSecretAuth,+ CredError,+ PrivateKeyJwtAuth,+)+from pydantic import SecretStr++_PATCH_TARGET = (+ "litellm.proxy._experimental.mcp_server.outbound_credentials."+ "token_endpoint.get_async_httpx_client"+)++_ENDPOINT = "https://idp.example.com/oauth2/token"+_CLIENT_ID = "litellm-client-id"++_RSA_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+_PRIVATE_PEM = _RSA_KEY.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+).decode()+_PUBLIC_PEM = (+ _RSA_KEY.public_key()+ .public_bytes(+ serialization.Encoding.PEM,+ serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ .decode()+)+++def _resp(token="access", expires_in=3600):+ resp = MagicMock()+ resp.json.return_value = {"access_token": token, "expires_in": expires_in}+ resp.raise_for_status = MagicMock()+ return resp+++def _client(response):+ client = AsyncMock()+ client.post.return_value = response+ return client+++def _posted_data(client):+ return client.post.call_args.kwargs["data"]+++async def test_fetch_forwards_grant_params_and_client_secret():+ client = _client(_resp("the-token", expires_in=1200))+ with patch(_PATCH_TARGET, return_value=client):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g", "subject_token": "user-jwt"},+ ClientSecretAuth(client_secret=SecretStr("shhh")),+ )++ assert isinstance(result, Ok)+ assert result.ok == ExchangedToken(access_token="the-token", expires_in=1200)+ assert client.post.call_args.args[0] == _ENDPOINT+ data = _posted_data(client)+ assert data["grant_type"] == "g"+ assert data["subject_token"] == "user-jwt"+ assert data["client_id"] == _CLIENT_ID+ assert data["client_secret"] == "shhh"+ assert "client_assertion" not in data+++async def test_fetch_private_key_jwt_client_assertion():+ client = _client(_resp())+ with patch(_PATCH_TARGET, return_value=client):+ await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ PrivateKeyJwtAuth(+ private_key=SecretStr(_PRIVATE_PEM),+ key_id="kid-1",+ signing_alg="RS256",+ ),+ )++ data = _posted_data(client)+ assert data["client_assertion_type"] == CLIENT_ASSERTION_TYPE+ assert "client_secret" not in data+ decoded = jwt.decode(+ data["client_assertion"],+ _PUBLIC_PEM,+ algorithms=["RS256"],+ audience=_ENDPOINT,+ )+ assert decoded["iss"] == _CLIENT_ID+ assert decoded["sub"] == _CLIENT_ID+ assert decoded["aud"] == _ENDPOINT+ assert "exp" in decoded+ assert jwt.get_unverified_header(data["client_assertion"])["kid"] == "kid-1"+++async def test_fetch_http_error_maps_to_upstream_unavailable_with_status():+ error_resp = MagicMock()+ error_resp.status_code = 403+ error_resp.raise_for_status.side_effect = httpx.HTTPStatusError(+ "Forbidden", request=MagicMock(), response=error_resp+ )+ with patch(_PATCH_TARGET, return_value=_client(error_resp)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+ assert "403" in result.error.summary+++ "raised",+ [+ httpx.ConnectError("connection refused", request=MagicMock()),+ httpx.ReadTimeout("timed out", request=MagicMock()),+ litellm.Timeout(+ message="Connection timed out",+ model="default-model-name",+ llm_provider="litellm-httpx-handler",+ ),+ ],+)+async def test_fetch_network_error_maps_to_upstream_unavailable(raised):+ client = AsyncMock()+ client.post.side_effect = raised+ with patch(_PATCH_TARGET, return_value=client):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+ assert _ENDPOINT not in result.error.summary+ assert "idp.example.com" not in result.error.summary+++ "auth",+ [+ PrivateKeyJwtAuth(private_key=SecretStr("not-a-pem-key"), signing_alg="RS256"),+ PrivateKeyJwtAuth(private_key=SecretStr(_PRIVATE_PEM), signing_alg="XX999"),+ ],+ ids=["garbage-key", "unknown-alg"],+)+async def test_fetch_unsignable_client_assertion_is_misconfigured_not_a_crash(auth):+ client = AsyncMock()+ with patch(_PATCH_TARGET, return_value=client):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ auth,+ )++ assert isinstance(result, Error)+ assert result.error.tag == "misconfigured"+ client.post.assert_not_called()+ assert _ENDPOINT not in result.error.summary+ assert "idp.example.com" not in result.error.summary+++async def test_fetch_invalid_json_maps_to_upstream_unavailable():+ bad = MagicMock()+ bad.raise_for_status = MagicMock()+ bad.json.side_effect = json.JSONDecodeError("Expecting value", "<html>", 0)+ with patch(_PATCH_TARGET, return_value=_client(bad)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+ assert _ENDPOINT not in result.error.summary+ assert "idp.example.com" not in result.error.summary+++async def test_fetch_none_response_is_upstream_unavailable():+ with patch(_PATCH_TARGET, return_value=_client(None)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+++async def test_fetch_missing_access_token_is_upstream_unavailable():+ bad = MagicMock()+ bad.json.return_value = {"token_type": "Bearer"}+ bad.raise_for_status = MagicMock()+ with patch(_PATCH_TARGET, return_value=_client(bad)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert result.error.tag == "upstream_unavailable"+++async def test_fetch_http_error_does_not_leak_endpoint_url():+ error_resp = MagicMock()+ error_resp.status_code = 403+ error_resp.raise_for_status.side_effect = httpx.HTTPStatusError(+ "Forbidden", request=MagicMock(), response=error_resp+ )+ with patch(_PATCH_TARGET, return_value=_client(error_resp)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert _ENDPOINT not in result.error.summary+ assert "idp.example.com" not in result.error.summary+++async def test_fetch_none_response_does_not_leak_endpoint_url():+ with patch(_PATCH_TARGET, return_value=_client(None)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert _ENDPOINT not in result.error.summary+ assert "idp.example.com" not in result.error.summary+++async def test_fetch_missing_access_token_does_not_leak_endpoint_url():+ bad = MagicMock()+ bad.json.return_value = {"token_type": "Bearer"}+ bad.raise_for_status = MagicMock()+ with patch(_PATCH_TARGET, return_value=_client(bad)):+ result = await TokenEndpointClient().fetch(+ _ENDPOINT,+ _CLIENT_ID,+ {"grant_type": "g"},+ ClientSecretAuth(client_secret=SecretStr("s")),+ )++ assert isinstance(result, Error)+ assert _ENDPOINT not in result.error.summary+ assert "idp.example.com" not in result.error.summary+++def _ok_token(value="cached") -> Result[ExchangedToken, CredError]:+ return Ok(ExchangedToken(access_token=value, expires_in=3600))+++async def test_cache_hit_skips_the_second_compute():+ cache = ExchangedTokenCache()+ calls = 0++ async def compute():+ nonlocal calls+ calls += 1+ return _ok_token("tok")++ first = await cache.get_or_compute("k", compute)+ second = await cache.get_or_compute("k", compute)++ assert isinstance(first, Ok) and first.ok == "tok"+ assert isinstance(second, Ok) and second.ok == "tok"+ assert calls == 1+++async def test_cache_single_flights_concurrent_misses():+ cache = ExchangedTokenCache()+ calls = 0++ async def compute():+ nonlocal calls+ calls += 1+ await asyncio.sleep(0.01)+ return _ok_token("shared")++ results = await asyncio.gather(+ cache.get_or_compute("k", compute),+ cache.get_or_compute("k", compute),+ )++ assert [r.ok for r in results] == ["shared", "shared"]+ assert calls == 1+++async def test_cache_invalidate_forces_the_next_compute():+ cache = ExchangedTokenCache()+ calls = 0++ async def compute():+ nonlocal calls+ calls += 1+ return _ok_token(f"tok-{calls}")++ first = await cache.get_or_compute("k", compute)+ cache.invalidate("k")+ second = await cache.get_or_compute("k", compute)++ assert isinstance(first, Ok) and first.ok == "tok-1"+ assert isinstance(second, Ok) and second.ok == "tok-2"+ assert calls == 2+++async def test_cache_invalidate_only_evicts_the_named_key():+ cache = ExchangedTokenCache()+ calls = 0++ async def compute():+ nonlocal calls+ calls += 1+ return _ok_token(f"tok-{calls}")++ await cache.get_or_compute("keep", compute)+ await cache.get_or_compute("evict", compute)+ cache.invalidate("evict")+ kept = await cache.get_or_compute("keep", compute)++ assert isinstance(kept, Ok) and kept.ok == "tok-1"+ assert calls == 2+++async def test_cache_does_not_store_a_failed_compute():+ cache = ExchangedTokenCache()+ calls = 0++ async def compute():+ nonlocal calls+ calls += 1+ if calls == 1:+ return Error(CredError.of_upstream_unavailable("down"))+ return _ok_token("recovered")++ first = await cache.get_or_compute("k", compute)+ second = await cache.get_or_compute("k", compute)++ assert isinstance(first, Error)+ assert isinstance(second, Ok) and second.ok == "recovered"+ assert calls == 2diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.pyindex 43b3612a5f2..bb25ab6bd3c 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py@@ -17,10 +17,13 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials import (AuthSpecKind,AwsSigV4Config,Byok,+ ClientSecretAuth,CredError,Error,+ IdJagConfig,NoneConfig,Ok,+ PrivateKeyJwtAuth,ServerSpec,SharedKey,StaticKeys,@@ -29,6 +32,14 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials import (_AUTH_CONFIG = TypeAdapter(AuthConfig)+_ID_JAG_MINIMAL = {+ "kind": "id_jag",+ "org_token_endpoint": "https://idp.example.com/token",+ "resource_token_endpoint": "https://mcp-as.example.com/token",+ "client_id": "litellm",+ "client_auth": {"source": "client_secret", "client_secret": "s"},+}+def test_parse_auth_spec_kind_accepts_known_mode():result = parse_auth_spec_kind("token_exchange")@@ -148,3 +159,73 @@ def test_secrets_do_not_leak_in_repr():key = SharedKey(value=SecretStr("super-secret"))assert "super-secret" not in repr(key)assert key.value.get_secret_value() == "super-secret"+++ "missing",+ ["org_token_endpoint", "resource_token_endpoint", "client_id", "client_auth"],+)+def test_id_jag_config_requires_each_endpoint_client_and_auth(missing):+ payload = {k: v for k, v in _ID_JAG_MINIMAL.items() if k != missing}+ with pytest.raises(ValidationError):+ _AUTH_CONFIG.validate_python(payload)+++def test_id_jag_client_auth_discriminates_on_source():+ by_secret = _AUTH_CONFIG.validate_python(_ID_JAG_MINIMAL)+ assert isinstance(by_secret, IdJagConfig)+ assert isinstance(by_secret.client_auth, ClientSecretAuth)+ assert by_secret.client_auth.client_secret.get_secret_value() == "s"++ by_key = _AUTH_CONFIG.validate_python(+ {+ **_ID_JAG_MINIMAL,+ "client_auth": {+ "source": "private_key_jwt",+ "private_key": "PEM",+ "key_id": "kid-1",+ "signing_alg": "RS384",+ },+ }+ )+ assert isinstance(by_key, IdJagConfig)+ assert isinstance(by_key.client_auth, PrivateKeyJwtAuth)+ assert by_key.client_auth.private_key.get_secret_value() == "PEM"+ assert by_key.client_auth.key_id == "kid-1"+ assert by_key.client_auth.signing_alg == "RS384"+++def test_id_jag_client_auth_rejects_unknown_source():+ with pytest.raises(ValidationError):+ _AUTH_CONFIG.validate_python(+ {**_ID_JAG_MINIMAL, "client_auth": {"source": "mystery"}}+ )+++def test_id_jag_config_defaults_id_token_subject_and_empty_optionals():+ config = _AUTH_CONFIG.validate_python(_ID_JAG_MINIMAL)+ assert isinstance(config, IdJagConfig)+ assert config.subject_token_type == "urn:ietf:params:oauth:token-type:id_token"+ assert config.audience is None+ assert config.resource is None+ assert config.scopes == ()+++def test_id_jag_secrets_do_not_leak_in_repr():+ config = IdJagConfig(+ org_token_endpoint="https://idp.example.com/token",+ resource_token_endpoint="https://mcp-as.example.com/token",+ client_id="litellm",+ client_auth=PrivateKeyJwtAuth(private_key=SecretStr("super-secret-pem")),+ )+ assert "super-secret-pem" not in repr(config)+++def test_id_jag_server_spec_derives_auth_spec_kind():+ config = _AUTH_CONFIG.validate_python(_ID_JAG_MINIMAL)+ spec = ServerSpec(+ server_id="s",+ resource="https://mcp.example.com/mcp",+ config=config,+ )+ assert spec.auth_spec_kind is AuthSpecKind.id_jagdiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.pyindex a245200c4d1..56ca855c814 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_db_credentials.py@@ -19,6 +19,8 @@ import pytestfrom litellm.proxy._experimental.mcp_server.db import (_decode_user_credential,_prepare_mcp_server_data,+ decrypt_credentials,+ encrypt_credentials,get_user_credential,get_user_oauth_credential,is_oauth_credential_expired,@@ -332,6 +334,29 @@ def _stored_value(prisma) -> str:return create_value+# ── MCP server credentials at rest ──────────────────────────────────────────────+++def test_client_private_key_encrypted_at_rest():+ """An ID-JAG client_private_key is a secret and must be encrypted in the stored+ credentials blob, never persisted in plaintext, and must round-trip back. The+ pre-fix code left client_private_key out of encrypt_credentials, so it was stored+ verbatim."""+ private_key = (+ "-----BEGIN PRIVATE KEY-----\nsensitive-rsa-material\n-----END PRIVATE KEY-----"+ )+ credentials = {"client_secret": "shh", "client_private_key": private_key}++ encrypted = encrypt_credentials(dict(credentials), encryption_key=None)+ assert encrypted["client_private_key"] != private_key+ assert private_key not in encrypted["client_private_key"]+ assert encrypted["client_secret"] != "shh"++ decrypted = decrypt_credentials(dict(encrypted))+ assert decrypted["client_private_key"] == private_key+ assert decrypted["client_secret"] == "shh"++# ── BYOK round-trip ───────────────────────────────────────────────────────────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 55b6bbbdbc2..491fa023031 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@@ -176,6 +176,89 @@ class TestMCPServerManager:assert calls == [("", "authz-srv")]assert client is not None+ @pytest.mark.asyncio+ async def test_caller_auth_header_cannot_bypass_id_jag_exchange(self):+ """A caller-supplied per-request override must not disable the ID-JAG exchange and forward an+ arbitrary bearer upstream: _create_mcp_client keeps the v2 spec and resolves through the+ injected provider rather than deferring to the v1 caller-override path."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (+ StaticHeaderAuth,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import (+ Ok,+ )+ from litellm.types.mcp import MCPAuth++ calls = []++ class _FakeProvider:+ async def resolve_credentials(self, subject, server):+ calls.append((subject.subject_id, server.server_id))+ return Ok(StaticHeaderAuth("Bearer minted-id-jag-token"))++ manager = MCPServerManager(cred_provider=_FakeProvider())+ server = MCPServer(+ server_id="id-jag-srv",+ name="id-jag",+ url="https://upstream.example/mcp",+ transport=MCPTransport.sse,+ auth_type=MCPAuth.oauth2_id_jag,+ client_id="gateway-client",+ client_secret="gateway-secret",+ token_exchange_endpoint="https://org-idp.example/oauth2/token",+ id_jag_resource_token_endpoint="https://resource-as.example/oauth2/token",+ )++ client = await manager._create_mcp_client(+ server,+ mcp_auth_header="Bearer caller-supplied-token",+ subject_token="caller-id-token",+ )++ assert calls == [("", "id-jag-srv")]+ assert client is not None++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "missing_field",+ ["token_exchange_endpoint", "id_jag_resource_token_endpoint", "client_id", "client_secret"],+ )+ async def test_half_configured_id_jag_fails_closed_instead_of_deferring_to_v1(self, missing_field):+ """ID-JAG has no v1 arm, so a half-configured oauth2_id_jag server must not silently fall+ through to resolve_mcp_auth, where a caller x-mcp-* override or the static+ authentication_token would bypass the per-user identity assertion. It must be refused as an+ operator misconfiguration (HTTP 500) before any client is built."""+ from fastapi import HTTPException++ from litellm.types.mcp import MCPAuth++ fields = {+ "client_id": "gateway-client",+ "client_secret": "gateway-secret",+ "token_exchange_endpoint": "https://org-idp.example/oauth2/token",+ "id_jag_resource_token_endpoint": "https://resource-as.example/oauth2/token",+ }+ fields.pop(missing_field)+ server = MCPServer(+ server_id="id-jag-srv",+ name="id-jag",+ url="https://upstream.example/mcp",+ transport=MCPTransport.sse,+ auth_type=MCPAuth.oauth2_id_jag,+ authentication_token="static-server-secret",+ **fields,+ )++ with pytest.raises(HTTPException) as exc_info:+ await MCPServerManager()._create_mcp_client(+ server,+ mcp_auth_header="Bearer caller-supplied-token",+ subject_token="caller-id-token",+ )++ assert exc_info.value.status_code == 500+ assert "oauth2_id_jag" in str(exc_info.value.detail)+async def test_create_mcp_client_stdio_injects_npm_config_cache(self):"""Test that _create_mcp_client injects NPM_CONFIG_CACHE when not already set,and preserves user-provided NPM_CONFIG_CACHE when present."""@@ -257,6 +340,35 @@ class TestMCPServerManager:assert env == {}@pytest.mark.asyncio+ async def test_load_servers_from_config_debug_dump_redacts_secrets(self, caplog):+ """The registry debug dump must not leak long-lived credentials: the ID-JAG signing key,+ client secret, and static token are masked while non-secret fields stay readable."""++ manager = MCPServerManager()+ config = {+ "idjag": {+ "url": "https://example.com/mcp",+ "transport": MCPTransport.http,+ "auth_type": MCPAuth.oauth2_id_jag,+ "client_id": "gateway-client",+ "client_secret": "SECRET-CLIENT-SECRET",+ "client_private_key": "-----BEGIN PRIVATE KEY-----SECRET-PEM-----END PRIVATE KEY-----",+ "token_exchange_endpoint": "https://org-idp.example/oauth2/token",+ "id_jag_resource_token_endpoint": "https://resource-as.example/oauth2/token",+ "authentication_token": "SECRET-STATIC-TOKEN",+ }+ }++ with caplog.at_level(logging.DEBUG, logger="LiteLLM"):+ await manager.load_servers_from_config(config)++ dump = next(m for m in caplog.messages if "Loaded MCP Servers" in m)+ assert "SECRET-PEM" not in dump+ assert "SECRET-CLIENT-SECRET" not in dump+ assert "SECRET-STATIC-TOKEN" not in dump+ assert "gateway-client" in dump+ assert "https://org-idp.example/oauth2/token" in dump+async def test_load_servers_from_config_warns_on_invalid_alias(self, caplog):"""Invalid aliases from config should emit warnings during load."""@@ -8122,6 +8234,86 @@ class TestOBOCallToolRetry:manager._create_mcp_client.assert_awaited_once()assert first.attempts == 1 and retry.attempts == 1+ @pytest.mark.asyncio+ async def test_upstream_401_on_id_jag_evicts_the_cached_bearer_and_retries(self):+ """The retry path must invalidate the ID-JAG leg-2 bearer too: without eviction the rebuilt+ client resolves the same rejected token from the cache and the retry 401s identically."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (+ IdJagConfig,+ )++ manager = self._manager()+ success = CallToolResult(content=[], isError=False)+ first = _RetryFakeClient(raises=_UpstreamAuthError(401))+ retry = _RetryFakeClient(result=success)+ manager._create_mcp_client = AsyncMock(return_value=retry)+ server = MCPServer(+ server_id="id-jag-srv",+ name="id-jag",+ url="https://upstream.example/mcp",+ transport=MCPTransport.sse,+ auth_type=MCPAuth.oauth2_id_jag,+ client_id="gateway-client",+ client_secret="gateway-secret",+ token_exchange_endpoint="https://org-idp.example/oauth2/token",+ id_jag_resource_token_endpoint="https://resource-as.example/oauth2/token",+ )++ result = await manager._obo_call_tool_with_retry(+ client=first,+ call_tool_params=MagicMock(),+ host_progress_callback=None,+ mcp_server=server,+ server_auth_header=None,+ extra_headers=None,+ stdio_env=None,+ subject_token="caller-id-token",+ user_api_key_auth=None,+ )++ assert result is success+ manager._cred_provider.invalidate_credentials.assert_awaited_once()+ invalidated_spec = manager._cred_provider.invalidate_credentials.await_args.args[1]+ assert isinstance(invalidated_spec.config, IdJagConfig)+ assert first.attempts == 1 and retry.attempts == 1++ @pytest.mark.asyncio+ async def test_call_regular_routes_id_jag_through_the_retry_path(self):+ """An oauth2_id_jag tool call with a subject token must take the invalidate-and-retry branch+ of _call_regular_mcp_tool, not the plain single call, so an upstream 401 re-exchanges."""+ manager = self._manager()+ success = CallToolResult(content=[], isError=False)+ first = _RetryFakeClient(raises=_UpstreamAuthError(401))+ retry = _RetryFakeClient(result=success)+ manager._create_mcp_client = AsyncMock(side_effect=[first, retry])+ server = MCPServer(+ server_id="id-jag-srv",+ name="id-jag",+ url="https://upstream.example/mcp",+ transport=MCPTransport.sse,+ auth_type=MCPAuth.oauth2_id_jag,+ client_id="gateway-client",+ client_secret="gateway-secret",+ token_exchange_endpoint="https://org-idp.example/oauth2/token",+ id_jag_resource_token_endpoint="https://resource-as.example/oauth2/token",+ )++ result = await manager._call_regular_mcp_tool(+ mcp_server=server,+ original_tool_name="tool",+ arguments={},+ tasks=[],+ mcp_auth_header=None,+ mcp_server_auth_headers=None,+ oauth2_headers={"Authorization": "Bearer caller-id-token"},+ raw_headers=None,+ proxy_logging_obj=None,+ )++ assert result is success+ manager._cred_provider.invalidate_credentials.assert_awaited_once()+ assert first.attempts == 1 and retry.attempts == 1+@pytest.mark.asyncioasync def test_non_auth_error_does_not_retry(self):manager = self._manager()diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 6dc63762e5c..daba5639a4f 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -27288,7 +27288,7 @@ export interface components {/** Alias */alias?: string | null;/** Auth Type */- auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token" | "oauth2_token_exchange" | "true_passthrough" | "oauth_delegate") | null;+ auth_type?: ("none" | "api_key" | "bearer_token" | "basic" | "authorization" | "oauth2" | "aws_sigv4" | "token" | "oauth2_token_exchange" | "oauth2_id_jag" | "true_passthrough" | "oauth_delegate") | null;/** Mcp Info */mcp_info?: {[key: string]: unknown;