Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(mcp): add entra_obo profile to the token_exchange (OBO) arm (#31983)

tin-berri2e38da6b3e00
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index 8451f6dff6f..b2128cb0553 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -756,7 +756,12 @@ class MCPServerManager:
else:
mcp_oauth_metadata = None
- resolved_scopes = server_config.get("scopes") or (mcp_oauth_metadata.scopes if mcp_oauth_metadata else None)
+ # Filter blank scopes (e.g. YAML ``scopes: [""]``) the same way the DB-build path does, so
+ # an all-blank list normalizes to None rather than a ``("",)`` tuple that skips the
+ # entra_obo fail-closed scope precondition and POSTs an empty scope to the IdP.
+ resolved_scopes = self._extract_scopes(server_config.get("scopes")) or (
+ mcp_oauth_metadata.scopes if mcp_oauth_metadata else None
+ )
resolved_authorization_url = server_config.get("authorization_url") or (
mcp_oauth_metadata.authorization_url if mcp_oauth_metadata else None
)
@@ -825,6 +830,7 @@ class MCPServerManager:
"subject_token_type",
"urn:ietf:params:oauth:token-type:access_token",
),
+ 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)),
timeout=server_config.get("timeout", None),
@@ -1212,6 +1218,8 @@ class MCPServerManager:
audience=(credentials_dict.get("audience") if credentials_dict else None),
subject_token_type=(credentials_dict.get("subject_token_type") if credentials_dict else None)
or "urn:ietf:params:oauth:token-type:access_token",
+ token_exchange_profile=(credentials_dict.get("token_exchange_profile") if credentials_dict else None)
+ or "rfc8693",
timeout=getattr(mcp_server, "timeout", None),
max_concurrent_requests=getattr(mcp_server, "max_concurrent_requests", None),
)
@@ -2000,8 +2008,13 @@ class MCPServerManager:
if err.tag == "unauthorized" and isinstance(spec.config, TokenExchangeConfig):
# token_exchange (OBO): a missing/rejected subject token -> the RFC 9728 challenge
# pointing at the IdP the client must SSO with to obtain one, rather than an opaque
- # 401. No gateway-side browser flow.
- raise_token_exchange_challenge(server, root_path=get_server_root_path())
+ # 401. No gateway-side browser flow. An IdP step-up rejection (Entra Conditional
+ # Access) threads its claims blob into the challenge for the client to satisfy.
+ raise_token_exchange_challenge(
+ server,
+ root_path=get_server_root_path(),
+ claims=err.unauthorized.claims,
+ )
raise_public(err)
async def preflight_token_exchange(
@@ -2031,7 +2044,11 @@ class MCPServerManager:
return
case Error(err):
if err.tag == "unauthorized":
- raise_token_exchange_challenge(server, root_path=get_server_root_path())
+ raise_token_exchange_challenge(
+ server,
+ root_path=get_server_root_path(),
+ claims=err.unauthorized.claims,
+ )
raise_public(err)
async def _create_mcp_client(
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py
index 3ba8baab427..169a1a5d707 100644
--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py
@@ -12,7 +12,7 @@ every other mode so the caller defers to v1 (parity-safe); it grows one branch p
from __future__ import annotations
import base64
-from typing import TYPE_CHECKING, NoReturn, Optional
+from typing import TYPE_CHECKING, Literal, NoReturn, Optional
from fastapi import HTTPException
from pydantic import SecretStr
@@ -63,7 +63,7 @@ def to_server_spec(server: MCPServer) -> Optional[ServerSpec]:
explicitly mapped or explicitly deferred, rather than silently falling through to v1. Live
modes: ``none``, the static-header family (``api_key`` plus the Authorization schemes,
all shared-key), ``oauth2`` per-user tokens (``authorization_code``), and
- ``oauth2_token_exchange`` (RFC 8693 OBO); client_credentials (M2M), delegated/passthrough
+ ``oauth2_token_exchange`` (OBO); client_credentials (M2M), delegated/passthrough
oauth2, and SigV4 return None and stay on v1.
"""
if server.is_byok:
@@ -102,22 +102,28 @@ def to_server_spec(server: MCPServer) -> Optional[ServerSpec]:
def _token_exchange_spec(server: MCPServer, resource: str) -> Optional[ServerSpec]:
- """Build a token_exchange (RFC 8693 OBO) spec, or defer (None) when it is not OBO-configured.
+ """Build a token_exchange (OBO) spec, or defer (None) when it is not OBO-configured.
An OBO server with ``client_id``/``client_secret`` is owned by the v2 arm even if the
``token_exchange_endpoint``/``token_url`` is absent: a missing endpoint then fails closed (412) at
the exchanger rather than silently deferring to v1 and connecting unauthenticated, since the
gateway must not guess the IdP or fall back to a weaker source. Without client credentials there is
- nothing to own, so the server stays on v1 (parity-safe). ``audience`` is forwarded only when the
- operator set it; a missing one is omitted, not derived.
+ nothing to own, so the server stays on v1 (parity-safe). ``profile`` selects the wire dialect
+ (``rfc8693`` default, ``entra_obo`` for Microsoft Entra On-Behalf-Of); an unrecognized value
+ normalizes to ``rfc8693`` so a bad config value cannot crash spec-building. ``audience`` is
+ forwarded only when the operator set it; a missing one is omitted, not derived.
"""
endpoint = server.token_exchange_endpoint or server.token_url
if not server.client_id or not server.client_secret:
return None
+ profile: Literal["rfc8693", "entra_obo"] = (
+ "entra_obo" if server.token_exchange_profile == "entra_obo" else "rfc8693"
+ )
return ServerSpec(
server_id=server.server_id,
resource=resource,
config=TokenExchangeConfig(
+ profile=profile,
subject_token_type=server.subject_token_type or "urn:ietf:params:oauth:token-type:access_token",
token_exchange_endpoint=endpoint,
audience=server.audience,
@@ -208,7 +214,12 @@ def raise_user_oauth_challenge(server: MCPServer, *, root_path: str) -> NoReturn
)
-def raise_token_exchange_challenge(server: MCPServer, *, root_path: str) -> NoReturn:
+def raise_token_exchange_challenge(
+ server: MCPServer,
+ *,
+ root_path: str,
+ claims: str | None = None,
+) -> NoReturn:
"""Raise the RFC 9728 / RFC 6750 challenge an OBO (``token_exchange``) server returns when the
caller's subject token is missing or the IdP rejected it.
@@ -217,12 +228,30 @@ def raise_token_exchange_challenge(server: MCPServer, *, root_path: str) -> NoRe
spec-compliant MCP client to discover that AS and retry with a fresh bearer. Mirrors
``raise_user_oauth_challenge`` but for the exchange flow: there is no gateway-side browser OAuth —
the client re-authenticates directly with the IdP, and LiteLLM then exchanges the resulting token.
+
+ An IdP step-up rejection (Entra Conditional Access / CAE) passes its ``claims`` blob. Per the
+ Microsoft claims-challenge format the challenge then uses ``error="insufficient_claims"`` (the
+ value MSAL-family clients key on) and carries the claims base64-encoded in a ``claims`` parameter
+ the client replays to the IdP to satisfy the step-up. Without a claims blob the challenge keeps
+ ``error="invalid_token"`` and is byte-identical to the static one. Both the error value (one of
+ two literals) and the base64 claims draw from a fixed alphabet, so nothing from the IdP body
+ reaches the header unescaped.
"""
resource_metadata = oauth_protected_resource_path(root_path, server)
- www_authenticate = (
- f'Bearer resource_metadata="{resource_metadata}", '
- 'error="invalid_token", '
- 'error_description="Missing or invalid subject token; authenticate with the IdP and retry"'
+ encoded_claims = base64.b64encode(claims.encode()).decode() if claims else None
+ error = "insufficient_claims" if encoded_claims else "invalid_token"
+ error_description = (
+ "Step-up authentication required; satisfy the returned claims challenge with the IdP and retry"
+ if encoded_claims
+ else "Missing or invalid subject token; authenticate with the IdP and retry"
+ )
+ www_authenticate = ", ".join(
+ (
+ f'Bearer resource_metadata="{resource_metadata}"',
+ f'error="{error}"',
+ f'error_description="{error_description}"',
+ *((f'claims="{encoded_claims}"',) if encoded_claims else ()),
+ )
)
raise HTTPException(
status_code=401,
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchange_provider.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchange_provider.py
index 7161dbb32d4..e49de4559c6 100644
--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchange_provider.py
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchange_provider.py
@@ -1,6 +1,6 @@
"""Composition root for the v2-native token_exchange (OBO) exchanger.
-Wires the pure ``Rfc8693TokenExchanger`` to its runtime edges: the real httpx POST against the IdP and
+Wires the pure ``OboTokenExchanger`` to its runtime edges: the real httpx POST against the IdP and
the configured cache sizing/TTL constants. ``build_token_exchanger`` is built once at egress
construction and reused, so the in-process exchanged-token cache survives across requests. Unlike the
per-user store, nothing here reads a runtime global at build time (the httpx client is acquired per
@@ -22,7 +22,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_sto
InMemoryTokenCacheBackend,
)
from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger import (
- Rfc8693TokenExchanger,
+ OboTokenExchanger,
SubjectTokenRejected,
TokenExchangeClientError,
)
@@ -34,21 +34,27 @@ _GATEWAY_FAULT_OAUTH_ERRORS = frozenset(
)
-def _oauth_error_code(response: httpx.Response) -> str | None:
- """Read the RFC 6749 5.2 ``error`` code from a token-endpoint error body, or None if absent.
+def _oauth_error_fields(response: httpx.Response) -> tuple[str | None, str | None]:
+ """Read the RFC 6749 5.2 ``error`` code and the IdP's step-up ``claims`` blob from a
+ token-endpoint error body, as ``(error, claims)`` with None for whatever is absent.
- The ``error_description`` is deliberately not read: it can carry IdP internals and must never
- reach the caller. Only the standard machine code drives classification.
+ ``claims`` is the Entra Conditional Access / CAE challenge (a JSON string the client must
+ replay to the IdP to satisfy the step-up); it is the caller's own requirement, not an IdP
+ internal, so it may travel to the caller. The ``error_description`` is deliberately not read:
+ it can carry IdP internals and must never reach the caller.
"""
try:
body: object = response.json()
except Exception: # noqa: BLE001
- return None
- if isinstance(body, dict):
- code = body.get("error")
- if isinstance(code, str):
- return code
- return None
+ return None, None
+ if not isinstance(body, dict):
+ return None, None
+ code = body.get("error")
+ claims = body.get("claims")
+ return (
+ code if isinstance(code, str) else None,
+ claims if isinstance(claims, str) and claims else None,
+ )
async def _post_exchange_endpoint(
@@ -72,7 +78,7 @@ async def _post_exchange_endpoint(
except httpx.HTTPStatusError as status_err:
status_code = status_err.response.status_code
if 400 <= status_code < 500:
- oauth_error = _oauth_error_code(status_err.response)
+ oauth_error, claims = _oauth_error_fields(status_err.response)
if oauth_error in _GATEWAY_FAULT_OAUTH_ERRORS:
verbose_logger.warning(
"MCP token exchange rejected as %s (HTTP %d); check the gateway client credentials, "
@@ -81,7 +87,10 @@ async def _post_exchange_endpoint(
status_code,
)
raise TokenExchangeClientError(oauth_error) from status_err
- raise SubjectTokenRejected(f"IdP rejected the subject token (HTTP {status_code})") from status_err
+ raise SubjectTokenRejected(
+ f"IdP rejected the subject token (HTTP {status_code})",
+ claims=claims,
+ ) from status_err
verbose_logger.warning("MCP token exchange request failed: %s", status_err)
return None
except Exception as exc: # noqa: BLE001
@@ -95,8 +104,8 @@ async def _post_exchange_endpoint(
return parsed # pyright: ignore
-def build_token_exchanger() -> Rfc8693TokenExchanger:
- return Rfc8693TokenExchanger(
+def build_token_exchanger() -> OboTokenExchanger:
+ return OboTokenExchanger(
_post_exchange_endpoint,
cache=InMemoryTokenCacheBackend(max_size=MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE),
default_ttl_seconds=MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL,
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchanger.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchanger.py
index 9f1787da612..02b6d4eafb1 100644
--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchanger.py
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_exchanger.py
@@ -1,11 +1,14 @@
-"""v2-native RFC 8693 token exchange (OBO): swap the caller's token for an upstream one.
-
-The pure core of the ``token_exchange`` mode. Given the caller's ``subject_token`` and the server's
-``TokenExchangeConfig``, ``Rfc8693TokenExchanger.exchange`` POSTs the RFC 8693 token-exchange grant to
-the configured endpoint and returns the upstream-bound ``access_token`` as a typed ``OAuthToken``, or a
-typed ``CredError`` - never a raise (the HTTP edge is the injected ``ExchangeHttpPost``, whose adapter
-contains the I/O). The exchanged token is cached and single-flighted per ``(subject_token, server)`` so
-a repeated caller token skips the IdP round-trip and concurrent calls collapse to one exchange, reusing
+"""v2-native OBO token exchange: swap the caller's token for an upstream-bound one.
+
+The pure core of the ``token_exchange`` mode. Given the caller's inbound token and the server's
+``TokenExchangeConfig``, ``OboTokenExchanger.exchange`` POSTs the grant selected by ``config.profile``
+to the configured endpoint and returns the upstream-bound ``access_token`` as a typed ``OAuthToken``,
+or a typed ``CredError`` - never a raise (the HTTP edge is the injected ``ExchangeHttpPost``, whose
+adapter contains the I/O). Two profiles share this one engine: ``rfc8693`` (the RFC 8693 token-exchange
+grant) and ``entra_obo`` (Microsoft Entra On-Behalf-Of, which is the RFC 7523 ``jwt-bearer`` grant);
+only the request form differs, so the cache, single-flight, and TTL machinery are dialect-agnostic. The
+exchanged token is cached and single-flighted per ``(subject_token, tenant, config, server)`` so a
+repeated caller token skips the IdP round-trip and concurrent calls collapse to one exchange, reusing
the shared in-process cache + coordinator foundation. A rotated caller token hashes to a new key and
re-exchanges. Pure v2 apart from the shared RFC 6749 client-auth helper, which carries no v1 state.
@@ -19,7 +22,9 @@ from __future__ import annotations
import hashlib
import time
from collections.abc import Awaitable, Callable
-from typing import Protocol
+from typing import Literal, Protocol
+
+from typing_extensions import assert_never
from litellm._logging import verbose_logger
from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import (
@@ -51,6 +56,10 @@ _MIN_TTL_SECONDS = 10.0
_EXPIRY_BUFFER_SECONDS = 60.0
_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
+# Microsoft Entra On-Behalf-Of speaks the RFC 7523 jwt-bearer grant, not RFC 8693, and gates delegation
+# behind ``requested_token_use=on_behalf_of`` (a Microsoft extension present in neither RFC).
+_JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
+_REQUESTED_TOKEN_USE_OBO = "on_behalf_of"
# RFC 8693 3 token-type URNs that are not usable as an upstream Bearer access token. token_type
# already rejects the common non-access case (N_A); this catches a malformed STS that mints one of
@@ -77,8 +86,15 @@ class SubjectTokenRejected(Exception):
Distinct from a transport / IdP-availability failure, which the post adapter maps to ``None`` ->
``upstream_unavailable`` -> 503 (retryable). A rejected subject is the caller's problem, not the
gateway's, so the arm surfaces it as a non-retryable 401 (the OBO challenge) instead.
+ ``claims`` is the IdP's step-up challenge blob (Entra Conditional Access / CAE) from the
+ rejection body; it threads into the 401 challenge so the client can satisfy the step-up and
+ retry. The ``error_description`` is never carried (it can leak IdP internals).
"""
+ def __init__(self, detail: str, *, claims: str | None = None) -> None:
+ super().__init__(detail)
+ self.claims = claims
+
class TokenExchangeClientError(Exception):
"""The IdP rejected the exchange for a reason that is the gateway's fault, not the caller's.
@@ -106,16 +122,18 @@ class TokenExchanger(Protocol):
def _cache_key(subject_token: str, tenant_id: str, config: TokenExchangeConfig) -> str:
"""Bind the cache entry to the caller token, the tenant, AND the exchange config that minted it.
- A rotated caller token, a different tenant, endpoint, audience, scope, client_id, secret, auth
- method, or subject_token_type all change the key, so two tenants behind the same opaque token
- never share an entry and a config change forces a fresh exchange instead of serving a token
- minted for the old config until TTL. Everything is hashed, so no secret is held in the key.
+ A rotated caller token, a different tenant, profile, endpoint, audience, scope, client_id, secret,
+ auth method, or subject_token_type all change the key, so two tenants behind the same opaque token
+ never share an entry and a config change (including a profile flip that alters the wire form)
+ forces a fresh exchange instead of serving a token minted for the old config until TTL. Everything
+ is hashed, so no secret is held in the key.
"""
secret = config.client_secret.get_secret_value() if config.client_secret else ""
material = "\x00".join(
(
subject_token,
tenant_id,
+ config.profile,
config.token_exchange_endpoint or "",
config.audience or "",
config.subject_token_type,
@@ -141,7 +159,7 @@ def _parse_expires_in(raw: object) -> int | None:
return None
-def _build_exchange_form(
+def _rfc8693_form(
*,
subject_token: str,
subject_token_type: str,
@@ -157,8 +175,53 @@ def _build_exchange_form(
}
-class Rfc8693TokenExchanger:
- """``TokenExchanger`` that runs the RFC 8693 grant once per caller token, then caches the result.
+def _entra_obo_form(
+ *,
+ subject_token: str,
+ scopes: tuple[str, ...],
+) -> dict[str, str]:
+ # Microsoft Entra On-Behalf-Of (RFC 7523 jwt-bearer, not RFC 8693): the caller's inbound access
+ # token rides as ``assertion`` (its ``aud`` must be this gateway's ``client_id``); the target
+ # resource is carried in ``scope`` (e.g. api://<app-id>/.default), since Entra has no audience
+ # parameter and ignores subject_token_type; ``requested_token_use=on_behalf_of`` is the Microsoft
+ # extension that turns the jwt-bearer grant into a delegation. ``scope`` is required, and the
+ # exchange precondition rejects an empty one, so it is always present here. Client authentication
+ # (client_id/client_secret via post, or Basic) is layered on by the caller through
+ # build_token_endpoint_client_auth, so it is not built into the form here.
+ return {
+ "grant_type": _JWT_BEARER_GRANT_TYPE,
+ "assertion": subject_token,
+ "scope": " ".join(scopes),
+ "requested_token_use": _REQUESTED_TOKEN_USE_OBO,
+ }
+
+
+def _build_exchange_form(
+ *,
+ profile: Literal["rfc8693", "entra_obo"],
+ subject_token: str,
+ subject_token_type: str,
+ audience: str | None,
+ scopes: tuple[str, ...],
+) -> dict[str, str]:
+ match profile:
+ case "rfc8693":
+ return _rfc8693_form(
+ subject_token=subject_token,
+ subject_token_type=subject_token_type,
+ audience=audience,
+ scopes=scopes,
+ )
+ case "entra_obo":
+ return _entra_obo_form(
+ subject_token=subject_token,
+ scopes=scopes,
+ )
+ assert_never(profile)
+
+
+class OboTokenExchanger:
+ """``TokenExchanger`` that runs the profile's OBO grant once per caller token, then caches the result.
The HTTP post is injected (``None`` on any IdP failure, mirroring v1: a failed exchange is a miss,
not a 500). The cache and single-flight coordinator default to the in-process foundation; a
@@ -199,6 +262,13 @@ class Rfc8693TokenExchanger:
)
if not client_id or client_secret is None:
return Error(CredError.of_misconfigured("token_exchange requires client_id and client_secret"))
+ if config.profile == "entra_obo" and not config.scopes:
+ # Entra carries the target resource in ``scope`` (api://<app-id>/.default); with no scope the
+ # IdP cannot resolve an audience, so fail closed as misconfigured rather than POST a form the
+ # IdP will reject.
+ return Error(
+ CredError.of_misconfigured("entra_obo token exchange requires a scope (e.g. api://<app-id>/.default)")
+ )
cache_key = _cache_key(subject_token, tenant_id, config)
server_id = server.server_id
@@ -214,6 +284,7 @@ class Rfc8693TokenExchanger:
)
form = {
**_build_exchange_form(
+ profile=config.profile,
subject_token=subject_token,
subject_token_type=config.subject_token_type,
audience=config.audience,
@@ -247,7 +318,14 @@ class Rfc8693TokenExchanger:
except SubjectTokenRejected as rejected:
# The IdP rejected the subject token (4xx). This is non-retryable: the caller must
# re-authenticate with the IdP, so it surfaces as a 401 (the OBO challenge), not a 503.
- return Error(CredError.of_unauthorized(str(rejected) or "subject token rejected by the IdP"))
+ # A step-up rejection (Entra Conditional Access) carries the claims blob through so the
+ # edge's challenge tells the client how to satisfy it.
+ return Error(
+ CredError.of_unauthorized(
+ str(rejected) or "subject token rejected by the IdP",
+ claims=rejected.claims,
+ )
+ )
except TokenExchangeClientError:
# RFC 6749 5.2 gateway-fault code (invalid_client / invalid_target / ...): the caller can't
# fix it by re-authenticating, so surface a 500 rather than the OBO 401 challenge. The
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py
index d475f931a25..49e3973d363 100644
--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py
@@ -67,11 +67,15 @@ class Unauthorized:
``detail`` is the human message; ``www_authenticate`` and ``body`` carry a scheme-specific
challenge (e.g. BYOK's provisioning prompt) so the edge can reproduce it verbatim.
+ ``claims`` carries an IdP step-up challenge (e.g. Entra Conditional Access) so the edge can
+ fold it into the ``WWW-Authenticate`` it builds; the client replays the claims to the IdP to
+ satisfy the step-up, then retries with the fresh token.
"""
detail: str
www_authenticate: str | None = None
body: Mapping[str, str] | None = None
+ claims: str | None = None
@tagged_union(frozen=True)
@@ -104,8 +108,16 @@ class CredError:
*,
www_authenticate: str | None = None,
body: Mapping[str, str] | None = None,
+ claims: str | None = None,
) -> CredError:
- return CredError(unauthorized=Unauthorized(detail=detail, www_authenticate=www_authenticate, body=body))
+ return CredError(
+ unauthorized=Unauthorized(
+ detail=detail,
+ www_authenticate=www_authenticate,
+ body=body,
+ claims=claims,
+ )
+ )
@staticmethod
def of_misconfigured(detail: str) -> CredError:
@@ -182,18 +194,27 @@ class ClientCredentialsConfig(BaseModel):
class TokenExchangeConfig(BaseModel):
- """RFC 8693 OBO; swap the caller's live subject_token for a token bound to the upstream's
- audience. The gateway authenticates to the exchange endpoint as an OAuth client
- (`client_id`/`client_secret`); the inbound token is sent only to that endpoint, never to the
- upstream.
-
- `audience` is the RFC 8693 target; it is optional and sent only when the operator configured
- one, since both `audience` and `resource` are optional in the spec and the authorization server
- applies its own default when neither is sent (fabricating one risks `invalid_target`).
+ """OBO: swap the caller's live inbound token for a token bound to the upstream's audience. The
+ gateway authenticates to the exchange endpoint as an OAuth client (`client_id`/`client_secret`);
+ the inbound token is sent only to that endpoint, never to the upstream.
+
+ `profile` selects the wire dialect, since not every IdP speaks RFC 8693:
+ - `rfc8693` (default) is the standard token-exchange grant: the inbound token is the
+ `subject_token` (typed by `subject_token_type`), the target is the optional `audience`.
+ - `entra_obo` is Microsoft Entra On-Behalf-Of, which is the RFC 7523 `jwt-bearer` grant rather
+ than 8693: the inbound token rides as `assertion`, the target resource is carried in `scopes`
+ (`api://<app-id>/.default`, since Entra has no audience parameter), and the Microsoft-only
+ `requested_token_use=on_behalf_of` extension makes the jwt-bearer grant a delegation.
+ `subject_token_type` and `audience` are unused in this profile.
+
+ `audience` (rfc8693 only) is optional and sent only when the operator configured one, since both
+ `audience` and `resource` are optional in RFC 8693 and the authorization server applies its own
+ default when neither is sent (fabricating one risks `invalid_target`).
"""
model_config = ConfigDict(frozen=True)
kind: Literal[AuthSpecKind.token_exchange] = AuthSpecKind.token_exchange
+ profile: Literal["rfc8693", "entra_obo"] = "rfc8693"
subject_token_type: str = "urn:ietf:params:oauth:token-type:access_token"
token_exchange_endpoint: str | None = None
audience: str | None = None
diff --git a/litellm/types/mcp.py b/litellm/types/mcp.py
index e9a6bfa602e..6cd8044c2ec 100644
--- a/litellm/types/mcp.py
+++ b/litellm/types/mcp.py
@@ -142,6 +142,13 @@ class MCPCredentials(TypedDict, total=False):
sends HTTP Basic; defaults to "client_secret_post" when unset.
"""
+ token_exchange_profile: Optional[str]
+ """
+ Token exchange wire dialect: "rfc8693" (default, the standard token-exchange grant) or
+ "entra_obo" (Microsoft Entra On-Behalf-Of, the RFC 7523 jwt-bearer grant + requested_token_use
+ extension). Not a secret; stored unencrypted.
+ """
+
class MCPServerCostInfo(TypedDict, total=False):
default_cost_per_query: Optional[float]
diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.py
index c4e37b236ae..f0600ade3b8 100644
--- a/litellm/types/mcp_server/mcp_server_manager.py
+++ b/litellm/types/mcp_server/mcp_server_manager.py
@@ -65,10 +65,13 @@ class MCPServer(BaseModel):
aws_service_name: Optional[str] = None # defaults to "bedrock-agentcore"
aws_role_name: Optional[str] = None # IAM role ARN for STS AssumeRole
aws_session_name: Optional[str] = None # session name for CloudTrail auditing
- # Token Exchange (OBO) fields — RFC 8693
+ # Token Exchange (OBO) fields
token_exchange_endpoint: Optional[str] = None
audience: Optional[str] = None
subject_token_type: str = "urn:ietf:params:oauth:token-type:access_token"
+ # 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"
# Stdio-specific fields
command: Optional[str] = None
args: Optional[List[str]] = None
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.py
index cdd88c59923..fbe768e07c6 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
@@ -160,6 +160,50 @@ def test_token_exchange_with_creds_but_no_endpoint_is_owned_for_fail_closed():
assert spec.config.token_exchange_endpoint is None
+def test_token_exchange_maps_entra_obo_profile():
+ spec = to_server_spec(
+ _server(
+ auth_type=MCPAuth.oauth2_token_exchange,
+ token_exchange_endpoint="https://login.microsoftonline.com/tid/oauth2/v2.0/token",
+ client_id="cid",
+ client_secret="csec",
+ token_exchange_profile="entra_obo",
+ scopes=["api://target/.default"],
+ )
+ )
+ assert spec is not None and isinstance(spec.config, TokenExchangeConfig)
+ assert spec.config.profile == "entra_obo"
+
+
+def test_token_exchange_defaults_to_rfc8693_profile():
+ spec = to_server_spec(
+ _server(
+ auth_type=MCPAuth.oauth2_token_exchange,
+ token_exchange_endpoint="https://idp/token",
+ client_id="cid",
+ client_secret="csec",
+ )
+ )
+ assert spec is not None and isinstance(spec.config, TokenExchangeConfig)
+ assert spec.config.profile == "rfc8693"
+
+
[email protected]("bogus", ["", "RFC8693", "jwt_bearer", "entra", "unknown"])
+def test_token_exchange_unknown_profile_normalizes_to_rfc8693(bogus):
+ # A bad DB/config value must normalize to rfc8693, not raise a ValidationError building the spec.
+ spec = to_server_spec(
+ _server(
+ auth_type=MCPAuth.oauth2_token_exchange,
+ token_exchange_endpoint="https://idp/token",
+ client_id="cid",
+ client_secret="csec",
+ token_exchange_profile=bogus,
+ )
+ )
+ assert spec is not None and isinstance(spec.config, TokenExchangeConfig)
+ assert spec.config.profile == "rfc8693"
+
+
def test_token_exchange_omits_audience_when_unset():
spec = to_server_spec(
_server(
@@ -330,3 +374,35 @@ def test_raise_token_exchange_challenge_includes_server_root_path():
raise_token_exchange_challenge(_server(alias="obo-srv"), root_path="/api/v1")
www = exc_info.value.headers["WWW-Authenticate"]
assert 'resource_metadata="/.well-known/oauth-protected-resource/api/v1/mcp/obo-srv"' in www
+
+
+def test_raise_token_exchange_challenge_static_form_is_unchanged_without_step_up():
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import (
+ raise_token_exchange_challenge,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ raise_token_exchange_challenge(_server(alias="obo-srv"), root_path="")
+ assert exc_info.value.headers["WWW-Authenticate"] == (
+ 'Bearer resource_metadata="/.well-known/oauth-protected-resource/mcp/obo-srv", '
+ 'error="invalid_token", '
+ 'error_description="Missing or invalid subject token; authenticate with the IdP and retry"'
+ )
+
+
+def test_raise_token_exchange_challenge_uses_insufficient_claims_with_claims_present():
+ # Per the Microsoft claims-challenge format, a claims challenge MUST use error=insufficient_claims
+ # (the value MSAL-family clients key on), and the claims ride base64-encoded, never raw.
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import (
+ raise_token_exchange_challenge,
+ )
+
+ claims = '{"access_token":{"acrs":{"essential":true,"value":"c1"}}}'
+ with pytest.raises(HTTPException) as exc_info:
+ raise_token_exchange_challenge(_server(alias="obo-srv"), root_path="", claims=claims)
+ www = exc_info.value.headers["WWW-Authenticate"]
+ assert 'resource_metadata="/.well-known/oauth-protected-resource/mcp/obo-srv"' in www
+ assert 'error="insufficient_claims"' in www
+ assert 'error="invalid_token"' not in www
+ assert f'claims="{base64.b64encode(claims.encode()).decode()}"' in www
+ assert claims not in www # raw JSON never appears; only the base64 form
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchange_provider.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchange_provider.py
index 7cea99f0b5f..cf15fdb3e26 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchange_provider.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchange_provider.py
@@ -13,7 +13,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchange_
build_token_exchanger,
)
from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger import (
- Rfc8693TokenExchanger,
+ OboTokenExchanger,
SubjectTokenRejected,
TokenExchangeClientError,
)
@@ -41,7 +41,7 @@ def _client_raising_4xx(body: object):
def test_build_token_exchanger_returns_an_exchanger():
- assert isinstance(build_token_exchanger(), Rfc8693TokenExchanger)
+ assert isinstance(build_token_exchanger(), OboTokenExchanger)
def test_build_gives_each_caller_an_independent_cache():
@@ -116,3 +116,38 @@ async def test_post_returns_none_on_non_object_json(payload):
with patch(_HTTP_CLIENT, return_value=_Client()):
result = await _post_exchange_endpoint("https://idp/token", {"grant_type": "x"}, {})
assert result is None
+
+
+async def test_post_threads_step_up_error_and_claims_into_subject_rejected():
+ # Entra Conditional Access: the 4xx body's machine code and claims blob must ride on the
+ # rejection so the edge challenge can drive the client's step-up; error_description never does.
+ claims = '{"access_token":{"acrs":{"essential":true,"value":"c1"}}}'
+ body = {
+ "error": "interaction_required",
+ "error_description": "AADSTS50079: the user must enroll MFA",
+ "claims": claims,
+ }
+ with patch(_HTTP_CLIENT, return_value=_client_raising_4xx(body)):
+ with pytest.raises(SubjectTokenRejected) as exc_info:
+ await _post_exchange_endpoint("https://idp/token", {"grant_type": "x"}, {})
+ assert exc_info.value.claims == claims
+ assert "AADSTS50079" not in str(exc_info.value)
+
+
+async def test_post_subject_rejection_without_claims_carries_none_claims():
+ with patch(_HTTP_CLIENT, return_value=_client_raising_4xx({"error": "invalid_grant"})):
+ with pytest.raises(SubjectTokenRejected) as exc_info:
+ await _post_exchange_endpoint("https://idp/token", {"grant_type": "x"}, {})
+ assert exc_info.value.claims is None
+
+
+async def test_post_gateway_fault_still_wins_when_claims_are_present():
+ # A gateway-fault code stays a 500-class TokenExchangeClientError even if the body carries
+ # claims; the caller cannot fix invalid_client by stepping up.
+ body = {"error": "invalid_client", "claims": '{"access_token":{}}'}
+ with patch(_HTTP_CLIENT, return_value=_client_raising_4xx(body)):
+ with pytest.raises(TokenExchangeClientError):
+ await _post_exchange_endpoint("https://idp/token", {"grant_type": "x"}, {})
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchanger.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchanger.py
index 13a0652474b..1fa394e1249 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchanger.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_exchanger.py
@@ -1,6 +1,6 @@
"""Tests for the pure RFC 8693 token exchanger: the OBO swap, caching, and single-flight.
-Drives `Rfc8693TokenExchanger` through an injected fake HTTP post and clock, so the exchange, the
+Drives `OboTokenExchanger` through an injected fake HTTP post and clock, so the exchange, the
form it sends, the per-caller-token cache, and the failure mapping are pinned without a live IdP.
"""
@@ -15,7 +15,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials import (
ServerSpec,
)
from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger import (
- Rfc8693TokenExchanger,
+ OboTokenExchanger,
)
from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (
TokenExchangeConfig,
@@ -32,6 +32,18 @@ _CONFIG = TokenExchangeConfig(
)
_SERVER = ServerSpec(server_id="srv", resource="https://up.example.com", config=_CONFIG)
+_JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer"
+# audience + a non-default subject_token_type are set deliberately: the entra_obo form must drop both.
+_ENTRA_CONFIG = TokenExchangeConfig(
+ profile="entra_obo",
+ token_exchange_endpoint="https://login.microsoftonline.com/tid/oauth2/v2.0/token",
+ audience="ignored-in-entra-obo",
+ subject_token_type="urn:ietf:params:oauth:token-type:jwt",
+ client_id="cid",
+ client_secret=SecretStr("csec"),
+ scopes=("api://target-api/.default",),
+)
+
class _Clock:
def __init__(self, now: float = 1000.0) -> None:
@@ -60,7 +72,7 @@ def _spec(config: TokenExchangeConfig) -> ServerSpec:
@pytest.mark.asyncio
async def test_exchange_emits_token_and_sends_rfc8693_form():
post = _RecordingPost({"access_token": "exchanged", "expires_in": 3600})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("caller-jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("caller-jwt", _SERVER, _CONFIG)
assert isinstance(result, Ok)
assert result.ok.access_token == "exchanged"
url, form = post.calls[0]
@@ -89,7 +101,7 @@ async def test_client_secret_basic_sends_authorization_header_and_omits_body_cre
token_endpoint_auth_method="client_secret_basic",
)
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
assert isinstance(result, Ok)
_, form = post.calls[0]
assert "client_id" not in form and "client_secret" not in form
@@ -105,7 +117,7 @@ async def test_client_secret_post_keeps_creds_in_body_with_no_auth_header():
token_endpoint_auth_method="client_secret_post",
)
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
+ await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
_, form = post.calls[0]
assert form["client_id"] == "cid" and form["client_secret"] == "csec"
assert "Authorization" not in post.headers[0]
@@ -122,7 +134,7 @@ async def test_exchange_maps_idp_rejection_to_unauthorized():
async def _rejecting_post(url, form, headers):
raise SubjectTokenRejected("IdP rejected the token exchange (HTTP 400)")
- result = await Rfc8693TokenExchanger(_rejecting_post, clock=_Clock()).exchange("bad-jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(_rejecting_post, clock=_Clock()).exchange("bad-jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "unauthorized"
@@ -139,7 +151,7 @@ async def test_exchange_maps_gateway_fault_to_misconfigured():
async def _client_error_post(url, form, headers):
raise TokenExchangeClientError("invalid_client")
- result = await Rfc8693TokenExchanger(_client_error_post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(_client_error_post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "misconfigured"
@@ -147,7 +159,7 @@ async def test_exchange_maps_gateway_fault_to_misconfigured():
@pytest.mark.asyncio
async def test_exchange_maps_transport_failure_to_upstream_unavailable():
"""A post returning None (5xx / network / timeout / malformed body) stays retryable: 503."""
- result = await Rfc8693TokenExchanger(_RecordingPost(None), clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(_RecordingPost(None), clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "upstream_unavailable"
@@ -155,7 +167,7 @@ async def test_exchange_maps_transport_failure_to_upstream_unavailable():
@pytest.mark.asyncio
async def test_exchange_caches_per_caller_token():
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
await exchanger.exchange("jwt", _SERVER, _CONFIG)
second = await exchanger.exchange("jwt", _SERVER, _CONFIG)
assert isinstance(second, Ok) and second.ok.access_token == "x"
@@ -165,7 +177,7 @@ async def test_exchange_caches_per_caller_token():
@pytest.mark.asyncio
async def test_rotated_caller_token_re_exchanges():
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
await exchanger.exchange("jwt-1", _SERVER, _CONFIG)
await exchanger.exchange("jwt-2", _SERVER, _CONFIG)
assert len(post.calls) == 2
@@ -176,7 +188,7 @@ async def test_same_token_different_tenant_does_not_share_cache():
# Two tenants presenting the same opaque token (e.g. a shared/service token) must not collide on
# one cache entry: tenant_id is part of the key, so each tenant gets its own exchange.
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
await exchanger.exchange("jwt", _SERVER, _CONFIG, tenant_id="acme")
await exchanger.exchange("jwt", _SERVER, _CONFIG, tenant_id="globex")
assert len(post.calls) == 2
@@ -188,7 +200,7 @@ async def test_same_token_different_tenant_does_not_share_cache():
@pytest.mark.asyncio
async def test_invalidate_forces_re_exchange():
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
await exchanger.exchange("jwt", _SERVER, _CONFIG, tenant_id="acme")
await exchanger.invalidate("jwt", _SERVER, _CONFIG, tenant_id="acme")
await exchanger.exchange("jwt", _SERVER, _CONFIG, tenant_id="acme")
@@ -198,7 +210,7 @@ async def test_invalidate_forces_re_exchange():
@pytest.mark.asyncio
async def test_invalidate_targets_only_the_matching_tenant():
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
await exchanger.exchange("jwt", _SERVER, _CONFIG, tenant_id="acme")
await exchanger.exchange("jwt", _SERVER, _CONFIG, tenant_id="globex")
await exchanger.invalidate("jwt", _SERVER, _CONFIG, tenant_id="acme")
@@ -213,7 +225,7 @@ async def test_rotated_config_re_exchanges_before_ttl():
# Same caller token + server, but the operator rotated the audience/scope: the cached token was
# minted for the old config, so it must re-exchange (not serve the stale token) before TTL.
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
rotated = _CONFIG.model_copy(update={"audience": "https://new.example.com", "scopes": ("s3",)})
await exchanger.exchange("jwt", _SERVER, _CONFIG)
await exchanger.exchange("jwt", _SERVER, rotated)
@@ -226,7 +238,7 @@ async def test_rotated_config_re_exchanges_before_ttl():
@pytest.mark.asyncio
async def test_rotated_token_endpoint_auth_method_re_exchanges_before_ttl():
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
rotated = _CONFIG.model_copy(update={"token_endpoint_auth_method": "client_secret_basic"})
await exchanger.exchange("jwt", _SERVER, _CONFIG)
await exchanger.exchange("jwt", _SERVER, rotated)
@@ -251,7 +263,7 @@ async def test_concurrent_callers_single_flight_one_exchange():
return {"access_token": "x", "expires_in": 3600}
post = _Blocking()
- exchanger = Rfc8693TokenExchanger(post, clock=_Clock())
+ exchanger = OboTokenExchanger(post, clock=_Clock())
first = asyncio.create_task(exchanger.exchange("jwt", _SERVER, _CONFIG))
second = asyncio.create_task(exchanger.exchange("jwt", _SERVER, _CONFIG))
await asyncio.sleep(0.02)
@@ -263,7 +275,7 @@ async def test_concurrent_callers_single_flight_one_exchange():
@pytest.mark.asyncio
async def test_idp_failure_is_upstream_unavailable():
- result = await Rfc8693TokenExchanger(_RecordingPost(None), clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(_RecordingPost(None), clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "upstream_unavailable"
@@ -271,7 +283,7 @@ async def test_idp_failure_is_upstream_unavailable():
@pytest.mark.asyncio
async def test_missing_access_token_is_upstream_unavailable():
post = _RecordingPost({"token_type": "Bearer"})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "upstream_unavailable"
@@ -282,7 +294,7 @@ async def test_non_bearer_token_type_is_refused(token_type):
# RFC 8693 2.2.1: the resolver forwards the exchanged token as `Bearer`. A non-Bearer token_type
# (e.g. N_A = not a standalone access token) must fail closed, not be minted as a bogus Bearer.
post = _RecordingPost({"access_token": "x", "token_type": token_type, "expires_in": 3600})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "upstream_unavailable"
@@ -295,7 +307,7 @@ async def test_non_bearer_token_type_is_logged():
with patch(
"litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger.verbose_logger"
) as mock_logger:
- await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert mock_logger.warning.called
assert "N_A" in repr(mock_logger.warning.call_args)
@@ -304,7 +316,7 @@ async def test_non_bearer_token_type_is_logged():
@pytest.mark.parametrize("token_type", ["Bearer", "bearer", "BEARER"])
async def test_bearer_token_type_is_accepted_case_insensitively(token_type):
post = _RecordingPost({"access_token": "x", "token_type": token_type, "expires_in": 3600})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Ok) and result.ok.access_token == "x"
@@ -312,7 +324,7 @@ async def test_bearer_token_type_is_accepted_case_insensitively(token_type):
async def test_absent_token_type_defaults_to_bearer():
# Many IdPs omit token_type; absence must not fail the exchange (RFC 6750 default is Bearer).
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Ok) and result.ok.access_token == "x"
@@ -331,7 +343,7 @@ async def test_non_access_issued_token_type_is_refused_even_when_bearer(issued_t
post = _RecordingPost(
{"access_token": "x", "token_type": "Bearer", "issued_token_type": issued_token_type, "expires_in": 3600}
)
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Error)
assert result.error.tag == "upstream_unavailable"
@@ -347,7 +359,7 @@ async def test_access_or_unknown_issued_token_type_is_accepted(issued_token_type
body: dict[str, object] = {"access_token": "x", "token_type": "Bearer", "expires_in": 3600}
if issued_token_type is not None:
body["issued_token_type"] = issued_token_type
- result = await Rfc8693TokenExchanger(_RecordingPost(body), clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ result = await OboTokenExchanger(_RecordingPost(body), clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Ok) and result.ok.access_token == "x"
@@ -361,7 +373,7 @@ async def test_access_or_unknown_issued_token_type_is_accepted(issued_token_type
)
async def test_incomplete_config_is_misconfigured_without_hitting_idp(config):
post = _RecordingPost({"access_token": "x"})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
assert isinstance(result, Error)
assert result.error.tag == "misconfigured"
assert post.calls == []
@@ -373,7 +385,7 @@ async def test_missing_endpoint_is_precondition_required_without_hitting_idp():
# rather than guessing an IdP or falling back. The subject token is never POSTed anywhere.
config = TokenExchangeConfig(client_id="c", client_secret=SecretStr("s"))
post = _RecordingPost({"access_token": "x"})
- result = await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
assert isinstance(result, Error)
assert result.error.tag == "precondition_required"
assert post.calls == []
@@ -384,7 +396,7 @@ async def test_cached_token_expires_after_its_ttl():
clock = _Clock(1000.0)
# expires_in=120, buffer=60 -> ttl 60 -> cached until t=1060.
post = _RecordingPost({"access_token": "x", "expires_in": 120})
- exchanger = Rfc8693TokenExchanger(post, clock=clock)
+ exchanger = OboTokenExchanger(post, clock=clock)
await exchanger.exchange("jwt", _SERVER, _CONFIG)
clock.now = 1059.0
await exchanger.exchange("jwt", _SERVER, _CONFIG)
@@ -402,7 +414,7 @@ async def test_audience_and_scope_omitted_when_unset():
client_secret=SecretStr("csec"),
)
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- await Rfc8693TokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
+ await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
_, form = post.calls[0]
assert "audience" not in form
assert "scope" not in form
@@ -414,7 +426,7 @@ async def test_numeric_expires_in_is_honored(expires_in):
# A JSON int/float/numeric-string expires_in must drive the TTL, not fall back to the default.
clock = _Clock(1000.0)
post = _RecordingPost({"access_token": "x", "expires_in": expires_in})
- exchanger = Rfc8693TokenExchanger(post, clock=clock) # ttl = max(120-60, 10) = 60 -> until 1060
+ exchanger = OboTokenExchanger(post, clock=clock) # ttl = max(120-60, 10) = 60 -> until 1060
await exchanger.exchange("jwt", _SERVER, _CONFIG)
clock.now = 1061.0
await exchanger.exchange("jwt", _SERVER, _CONFIG)
@@ -426,7 +438,7 @@ async def test_short_lived_token_is_not_cached_past_its_expiry():
# expires_in (5s) below the buffer/min floor must NOT be served stale: cache only until expiry.
clock = _Clock(1000.0)
post = _RecordingPost({"access_token": "x", "expires_in": 5})
- exchanger = Rfc8693TokenExchanger(post, clock=clock)
+ exchanger = OboTokenExchanger(post, clock=clock)
await exchanger.exchange("jwt", _SERVER, _CONFIG)
clock.now = 1004.0 # within the 5s lifetime -> still cached
await exchanger.exchange("jwt", _SERVER, _CONFIG)
@@ -449,13 +461,72 @@ async def test_short_lived_token_is_not_cached_past_its_expiry():
async def test_unusable_expires_in_falls_back_to_default_ttl(body):
clock = _Clock(1000.0)
post = _RecordingPost(body)
- exchanger = Rfc8693TokenExchanger(post, clock=clock, default_ttl_seconds=300.0)
+ exchanger = OboTokenExchanger(post, clock=clock, default_ttl_seconds=300.0)
await exchanger.exchange("jwt", _SERVER, _CONFIG)
clock.now = 1299.0
await exchanger.exchange("jwt", _SERVER, _CONFIG)
assert len(post.calls) == 1
+async def test_entra_obo_emits_rfc7523_jwt_bearer_form():
+ # Microsoft Entra OBO is the RFC 7523 jwt-bearer grant, not RFC 8693: the inbound token is the
+ # `assertion`, the target rides in `scope`, and `requested_token_use=on_behalf_of` is required.
+ # subject_token / subject_token_type / audience must NOT appear even though the config carries them.
+ post = _RecordingPost({"access_token": "minted", "expires_in": 3600})
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange(
+ "caller-entra-jwt", _spec(_ENTRA_CONFIG), _ENTRA_CONFIG
+ )
+ assert isinstance(result, Ok)
+ assert result.ok.access_token == "minted"
+ url, form = post.calls[0]
+ assert url == "https://login.microsoftonline.com/tid/oauth2/v2.0/token"
+ assert form == {
+ "grant_type": _JWT_BEARER_GRANT,
+ "assertion": "caller-entra-jwt",
+ "client_id": "cid",
+ "client_secret": "csec",
+ "scope": "api://target-api/.default",
+ "requested_token_use": "on_behalf_of",
+ }
+
+
+async def test_entra_obo_without_scope_is_misconfigured_without_hitting_idp():
+ # Entra carries the target resource in `scope`; with none, fail closed as misconfigured and never
+ # POST to the IdP (no fall-through to a weaker source).
+ config = TokenExchangeConfig(
+ profile="entra_obo",
+ token_exchange_endpoint="https://login.microsoftonline.com/tid/oauth2/v2.0/token",
+ client_id="cid",
+ client_secret=SecretStr("csec"),
+ )
+ post = _RecordingPost({"access_token": "x"})
+ result = await OboTokenExchanger(post, clock=_Clock()).exchange("jwt", _spec(config), config)
+ assert isinstance(result, Error)
+ assert result.error.tag == "misconfigured"
+ assert post.calls == []
+
+
+async def test_profile_is_part_of_the_cache_key():
+ # Same caller token, tenant, endpoint, creds, and scopes; only the profile differs. The two dialects
+ # mint different upstream tokens, so they must not collide on one cache entry.
+ post = _RecordingPost({"access_token": "x", "expires_in": 3600})
+ exchanger = OboTokenExchanger(post, clock=_Clock())
+ shared = dict(
+ token_exchange_endpoint="https://idp/token",
+ client_id="cid",
+ client_secret=SecretStr("csec"),
+ scopes=("api://target/.default",),
+ )
+ rfc8693 = TokenExchangeConfig(profile="rfc8693", **shared)
+ entra = TokenExchangeConfig(profile="entra_obo", **shared)
+ await exchanger.exchange("jwt", _spec(rfc8693), rfc8693)
+ await exchanger.exchange("jwt", _spec(entra), entra)
+ assert len(post.calls) == 2
+
+
@pytest.mark.asyncio
async def test_distributed_coordinator_refresh_and_reread_use_the_cache():
# Mimics the cross-replica coordinator contract: the winner's refresh populates the cache, a
@@ -470,7 +541,24 @@ async def test_distributed_coordinator_refresh_and_reread_use_the_cache():
return via_reread
post = _RecordingPost({"access_token": "x", "expires_in": 3600})
- exchanger = Rfc8693TokenExchanger(post, coordinator=_ReplayCoordinator(), clock=_Clock())
+ exchanger = OboTokenExchanger(post, coordinator=_ReplayCoordinator(), clock=_Clock())
result = await exchanger.exchange("jwt", _SERVER, _CONFIG)
assert isinstance(result, Ok) and result.ok.access_token == "x"
assert len(post.calls) == 1
+
+
+async def test_step_up_rejection_threads_claims_into_unauthorized():
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger import (
+ SubjectTokenRejected,
+ )
+
+ claims = '{"access_token":{"acrs":{"essential":true,"value":"c1"}}}'
+
+ async def _step_up_post(url, form, headers):
+ raise SubjectTokenRejected("IdP rejected the subject token (HTTP 400)", claims=claims)
+
+ result = await OboTokenExchanger(_step_up_post, clock=_Clock()).exchange("jwt", _SERVER, _CONFIG)
+ assert isinstance(result, Error)
+ assert result.error.tag == "unauthorized"
+ assert result.error.unauthorized.claims == claims
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
index 7c70bb24001..6d3e09c6b75 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
@@ -718,6 +718,41 @@ class TestMCPServerManager:
client_secret="csec",
)
+ @pytest.mark.asyncio
+ async def test_entra_obo_profile_survives_db_credentials_round_trip(self):
+ # A credentials blob from the management API / DB carries token_exchange_profile; the DB build
+ # must reconstruct it onto the MCPServer, and the v2 adapter must map it onto the resolver
+ # config. Without threading it through, an entra_obo server persisted via the API silently
+ # falls back to rfc8693 and posts the wrong grant to the IdP.
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import to_server_spec
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import TokenExchangeConfig
+
+ manager = MCPServerManager()
+ row = LiteLLM_MCPServerTable(
+ server_id="entra-db-1",
+ alias="entra_db",
+ description="entra obo from db",
+ url="https://up.example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2_token_exchange,
+ credentials={
+ "client_id": "cid",
+ "client_secret": "csec",
+ "token_exchange_endpoint": "https://login.microsoftonline.com/tid/oauth2/v2.0/token",
+ "scopes": ["api://target/.default"],
+ "token_exchange_profile": "entra_obo",
+ },
+ created_at=datetime.now(),
+ updated_at=datetime.now(),
+ )
+
+ built = await manager.build_mcp_server_from_table(row, credentials_are_encrypted=False)
+ assert built.token_exchange_profile == "entra_obo"
+
+ spec = to_server_spec(built)
+ assert spec is not None and isinstance(spec.config, TokenExchangeConfig)
+ assert spec.config.profile == "entra_obo"
+
async def _capture_subject_token(self, call) -> Optional[str]:
"""Run a manager method (via ``call(manager)``) and return the subject_token it threaded
into ``_create_mcp_client``."""
@@ -1615,6 +1650,47 @@ class TestMCPServerManager:
assert server.token_url == "https://discovered.example.com/token"
assert server.registration_url == "https://discovered.example.com/register"
+ @pytest.mark.asyncio
+ async def test_load_servers_from_config_filters_blank_scopes(self):
+ """A YAML ``scopes: [""]`` must normalize to None (matching the DB path), so a blank-only
+ list never becomes a ``("",)`` tuple that skips the entra_obo fail-closed scope check."""
+ manager = MCPServerManager()
+ config = {
+ "entra": {
+ "url": "https://up.example.com/mcp",
+ "transport": MCPTransport.http,
+ "auth_type": MCPAuth.oauth2_token_exchange,
+ "token_exchange_profile": "entra_obo",
+ "token_exchange_endpoint": "https://login.microsoftonline.com/t/oauth2/v2.0/token",
+ "client_id": "cid",
+ "client_secret": "csec",
+ "scopes": ["", " "],
+ }
+ }
+
+ await manager.load_servers_from_config(config)
+
+ server = next(iter(manager.config_mcp_servers.values()))
+ assert server.scopes is None
+
+ # And the exchange precondition now fails closed before any IdP call.
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import to_server_spec
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Error
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.token_exchanger import (
+ OboTokenExchanger,
+ )
+
+ spec = to_server_spec(server)
+ assert spec is not None
+ assert spec.config.scopes == ()
+
+ async def _must_not_post(url, form, headers):
+ raise AssertionError("entra_obo with blank scopes must fail closed before POSTing to the IdP")
+
+ result = await OboTokenExchanger(_must_not_post).exchange("subj", spec, spec.config)
+ assert isinstance(result, Error)
+ assert result.error.tag == "misconfigured"
+
@pytest.mark.asyncio
async def test_config_oauth_initialize_tool_name_to_mcp_server_name_mapping(self):
manager = MCPServerManager()
@@ -5913,3 +5989,72 @@ class TestOBOEndpointDiscovery:
if __name__ == "__main__":
pytest.main([__file__])
+
+
+async def test_preflight_challenge_carries_step_up_error_and_claims():
+ """An Entra Conditional Access rejection must surface error=insufficient_claims plus the base64
+ claims in the single-server 401 challenge, so an MSAL-family client can drive the step-up and retry."""
+ import base64
+
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.result import Error
+ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import CredError
+
+ claims = '{"access_token":{"acrs":{"essential":true,"value":"c1"}}}'
+
+ class _FakeProvider:
+ async def resolve_credentials(self, subject, server):
+ return Error(CredError.of_unauthorized("step-up required", claims=claims))
+
+ manager = MCPServerManager(cred_provider=_FakeProvider())
+ server = MCPServer(
+ server_id="te-ca",
+ name="te-ca-server",
+ url="https://up.example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2_token_exchange,
+ token_exchange_endpoint="https://idp.example.com/token",
+ client_id="cid",
+ client_secret="csec",
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ await manager.preflight_token_exchange(
+ server=server,
+ oauth2_headers={"Authorization": "Bearer subj"},
+ user_api_key_auth=None,
+ )
+ assert exc_info.value.status_code == 401
+ headers = exc_info.value.headers or {}
+ www = headers.get("WWW-Authenticate") or headers.get("www-authenticate") or ""
+ assert 'error="insufficient_claims"' in www
+ assert base64.b64encode(claims.encode()).decode() in www
+ assert "resource_metadata" in www
+
+
+async def test_aggregate_list_still_absorbs_step_up_challenged_server():
+ """A step-up (claims-bearing) 401 from one server must not change the aggregate contract: the
+ multi-server listing still absorbs it and returns the healthy servers' tools."""
+ from litellm.proxy._experimental.mcp_server.exceptions import MCPUpstreamAuthError
+
+ manager = MCPServerManager()
+ good = MCPServer(server_id="good", name="good", transport=MCPTransport.http)
+ ca = MCPServer(server_id="ca", name="ca", transport=MCPTransport.http)
+ manager.get_allowed_mcp_servers = AsyncMock(return_value=["good", "ca"])
+ manager.get_mcp_server_by_id = MagicMock(side_effect=lambda server_id: {"good": good, "ca": ca}.get(server_id))
+ good_tool = MCPTool(name="good-do_thing", description="do thing", inputSchema={})
+
+ async def fake_get_tools(server, **kwargs):
+ if server.server_id == "ca":
+ raise MCPUpstreamAuthError(
+ status_code=401,
+ www_authenticate=('Bearer resource_metadata="/x", error="insufficient_claims", claims="eyJhIjoxfQ=="'),
+ server_name="ca",
+ )
+ return [good_tool]
+
+ manager._get_tools_from_server = fake_get_tools
+
+ result = await manager.list_tools()
+
+ assert [t.name for t in result] == ["good-do_thing"]
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.py
index 32d0461439c..e223140b573 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
@@ -148,6 +148,34 @@ def patch_proxy_general_settings(settings: dict):
)
+class TestMCPCredentialsTokenExchangeProfile:
+ """token_exchange_profile must be a declared MCPCredentials field so the management API can
+ persist the entra_obo profile. An undeclared key is silently stripped by pydantic when the
+ credentials dict is validated against the TypedDict, so it would never reach the JSON blob."""
+
+ @pytest.mark.parametrize(
+ "build",
+ [
+ lambda creds: NewMCPServerRequest(
+ server_name="s", auth_type=MCPAuth.oauth2_token_exchange, credentials=creds
+ ),
+ lambda creds: UpdateMCPServerRequest(server_id="s", credentials=creds),
+ ],
+ ids=["new", "update"],
+ )
+ def test_request_preserves_token_exchange_profile_in_credentials(self, build):
+ creds = {
+ "client_id": "cid",
+ "client_secret": "sec",
+ "token_exchange_endpoint": "https://login.microsoftonline.com/tid/oauth2/v2.0/token",
+ "scopes": ["api://target/.default"],
+ "token_exchange_profile": "entra_obo",
+ }
+ request = build(creds)
+ assert request.credentials is not None
+ assert request.credentials.get("token_exchange_profile") == "entra_obo"
+
+
class TestListMCPServers:
"""Test suite for list MCP servers functionality"""