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): mint gateway-bound envelope at the token endpoint for dcr_bridge oauth_delegate
Tin Chi Lo34c6cce70562
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex ebceb320906..41ed49a7508 100644--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@ -10,7 +10,7 @@ from urllib.parse import parse_qsl, urlencode, urlparse, urlunparseimport httpxfrom fastapi import APIRouter, Form, HTTPException, Requestfrom fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response-from pydantic import BaseModel, ValidationError+from pydantic import BaseModel, SecretStr, ValidationErrorfrom litellm._logging import verbose_loggerfrom litellm.llms.custom_httpx.http_handler import (@@ -37,6 +37,9 @@ from litellm.types.mcp import MCPAuth, MCPCredentialsfrom litellm.types.mcp_server.mcp_server_manager import MCPServerif TYPE_CHECKING:+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import (+ UpstreamTokenGrant,+ )from litellm.proxy._types import LiteLLM_MCPServerTable, UserAPIKeyAuth# TTL cache for upstream OAuth metadata fetched from pass-through MCP servers.@@ -654,6 +657,86 @@ async def authorize_with_server(return response+def _bridge_grant_from_token_response(token_response: object) -> Optional["UpstreamTokenGrant"]:+ """Validate an upstream OAuth token response into a typed grant, or None when it lacks a usable+ access token. Each field is isinstance-checked so nothing untyped from ``response.json()`` flows+ into the grant."""+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import ( # noqa: PLC0415 # inline import avoids a module-load circular import+ UpstreamTokenGrant,+ )++ if not isinstance(token_response, dict):+ return None+ access = token_response.get("access_token")+ if not isinstance(access, str) or not access:+ return None+ token_type = token_response.get("token_type")+ refresh = token_response.get("refresh_token")+ scope = token_response.get("scope")+ expires_in = token_response.get("expires_in")+ return UpstreamTokenGrant(+ access_token=SecretStr(access),+ token_type=token_type if isinstance(token_type, str) and token_type else "Bearer",+ refresh_token=SecretStr(refresh) if isinstance(refresh, str) and refresh else None,+ scope=scope if isinstance(scope, str) and scope else None,+ expires_in=expires_in if isinstance(expires_in, int) and expires_in > 0 else None,+ )+++async def _mint_bridge_delegate_token_response(+ request: Request, mcp_server: MCPServer, token_response: object+) -> JSONResponse:+ """Return the client-held envelope bearer for a DCR-bridge ``oauth_delegate`` token exchange.++ The envelope binds the caller's litellm identity (resolved from the token request) to the+ upstream grant, so the client holds one bearer that later admits it and forwards the upstream+ token, with nothing stored server-side. Fails closed with an OAuth ``invalid_request`` when no+ litellm identity accompanies the token request rather than minting an identity-less credential.+ """+ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import ( # noqa: PLC0415 # inline import avoids a module-load circular import+ build_bridge_token_response,+ envelope_keys_from_master_key,+ )+ from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import ( # noqa: PLC0415 # inline import avoids a module-load circular import+ EnvelopeIdentity,+ SealedEnvelope,+ )+ from litellm.proxy.proxy_server import (+ master_key, # noqa: PLC0415 # inline import avoids a module-load circular import+ )++ if not master_key:+ raise HTTPException(status_code=500, detail="Server misconfigured: master_key is not set")++ user_id = await _extract_user_id_from_request(request)+ if not user_id:+ raise HTTPException(+ status_code=400,+ detail={+ "error": "invalid_request",+ "error_description": (+ "this server issues a gateway-bound credential; send a litellm credential "+ "(x-litellm-api-key or Authorization) on the token request"+ ),+ },+ )++ grant = _bridge_grant_from_token_response(token_response)+ if grant is None:+ raise HTTPException(status_code=502, detail="Upstream token response has no usable access_token")++ now = datetime.now(timezone.utc)+ keys = envelope_keys_from_master_key(master_key)+ identity = EnvelopeIdentity(user_id=user_id, server_id=mcp_server.server_id)+ sealed = build_bridge_token_response(identity, grant, keys, now)+ if not isinstance(sealed, SealedEnvelope):+ raise HTTPException(status_code=500, detail="Failed to mint the gateway-bound credential")++ expires_in = max(1, int((sealed.expires_at - now).total_seconds()))+ body = {"access_token": sealed.token.get_secret_value(), "token_type": "Bearer", "expires_in": expires_in}+ return JSONResponse(body, headers=TOKEN_NO_CACHE_HEADERS)++async def exchange_token_with_server(request: Request,mcp_server: MCPServer,@@ -791,6 +874,12 @@ async def exchange_token_with_server(mcp_server.server_id,)+ # A DCR-bridge oauth_delegate server hands the client a gateway-bound envelope (identity plus the+ # upstream token) instead of the raw upstream token, so the one bearer both admits the caller and+ # forwards the upstream credential. Only this mode mints; every other server returns the raw token.+ if mcp_server.is_oauth_delegate and mcp_server.is_dcr_bridge:+ return await _mint_bridge_delegate_token_response(request, mcp_server, token_response)+result = {"access_token": access_token,"token_type": token_response.get("token_type", "Bearer"),diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.pyindex c55a631c7b3..a2e8d693fab 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py@@ -4362,6 +4362,122 @@ async def test_register_bridge_relay_never_persists():mock_persist.assert_not_called()+_BRIDGE_MASTER_KEY = "sk-bridge-producer-master-key-0123456789abcdef"+++async def _exchange_for_bridge_server(server, upstream_body, user_id):+ from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ exchange_token_with_server,+ )++ fake_http_response = MagicMock()+ fake_http_response.json.return_value = upstream_body+ fake_http_response.raise_for_status = MagicMock()+ fake_http_client = MagicMock()+ fake_http_client.post = AsyncMock(return_value=fake_http_response)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",+ return_value=fake_http_client,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.discoverable_endpoints._extract_user_id_from_request",+ new=AsyncMock(return_value=user_id),+ ),+ patch("litellm.proxy.proxy_server.master_key", _BRIDGE_MASTER_KEY),+ ):+ return await exchange_token_with_server(+ request=_bridge_mock_request(),+ mcp_server=server,+ grant_type="authorization_code",+ code="auth-code",+ redirect_uri="https://claude.ai/api/mcp/auth_callback",+ client_id="dcr-client-123",+ client_secret=None,+ code_verifier="verifier",+ )+++async def test_oauth_delegate_bridge_token_exchange_mints_envelope_not_raw_token():+ """A dcr_bridge oauth_delegate token exchange returns a gateway-bound envelope, not the raw+ upstream token: the response access_token opens (under the same master-key-derived keys and the+ server_id) to the caller's identity and the upstream Authorization, and the raw upstream token+ never appears in the bearer the client receives."""+ from datetime import datetime, timezone++ from litellm.proxy._experimental.mcp_server.outbound_credentials.bridge_credentials import (+ BridgeEnvelopeAdmitted,+ envelope_keys_from_master_key,+ resolve_bridge_envelope,+ )+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ upstream = {"access_token": "UPSTREAM-SECRET-TOKEN", "token_type": "Bearer", "expires_in": 3600}+ response = await _exchange_for_bridge_server(server, upstream, user_id="user-77")++ body = json.loads(response.body)+ token = body["access_token"]+ assert body["token_type"] == "Bearer"+ assert body["expires_in"] > 0+ assert token.startswith("llm_env_")+ assert "UPSTREAM-SECRET-TOKEN" not in token+ assert "refresh_token" not in body++ keys = envelope_keys_from_master_key(_BRIDGE_MASTER_KEY)+ opened = resolve_bridge_envelope(token, keys, datetime.now(timezone.utc), server.server_id)+ assert isinstance(opened, BridgeEnvelopeAdmitted)+ assert opened.identity.user_id == "user-77"+ assert opened.upstream_authorization.get_secret_value() == "Bearer UPSTREAM-SECRET-TOKEN"+++async def test_oauth_delegate_bridge_token_exchange_fails_closed_without_litellm_identity():+ """Without a resolvable litellm identity on the token request, the exchange must not mint an+ identity-less envelope; it returns an OAuth invalid_request so the client sends a credential."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate)+ upstream = {"access_token": "UPSTREAM-SECRET-TOKEN", "token_type": "Bearer", "expires_in": 3600}++ with pytest.raises(HTTPException) as exc:+ await _exchange_for_bridge_server(server, upstream, user_id=None)++ assert exc.value.status_code == 400+ assert exc.value.detail["error"] == "invalid_request"+++async def test_true_passthrough_bridge_token_exchange_returns_raw_upstream_token():+ """Only oauth_delegate mints. A true_passthrough dcr_bridge server relays the raw upstream token+ to the client, since that mode has no litellm identity to bind and the caller owns the token."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.true_passthrough)+ upstream = {"access_token": "UPSTREAM-SECRET-TOKEN", "token_type": "Bearer", "expires_in": 3600}+ response = await _exchange_for_bridge_server(server, upstream, user_id="user-77")++ body = json.loads(response.body)+ assert body["access_token"] == "UPSTREAM-SECRET-TOKEN"+ assert not body["access_token"].startswith("llm_env_")+++async def test_non_bridge_oauth_delegate_token_exchange_returns_raw_upstream_token():+ """An oauth_delegate server without dcr_bridge keeps the pre-change contract: the raw upstream+ token is returned, so flag-off behavior is byte-identical."""+ from litellm.types.mcp import MCPAuth++ server = _bridge_server(auth_type=MCPAuth.oauth_delegate, dcr_bridge=None)+ upstream = {"access_token": "UPSTREAM-SECRET-TOKEN", "token_type": "Bearer", "expires_in": 3600}+ response = await _exchange_for_bridge_server(server, upstream, user_id="user-77")++ body = json.loads(response.body)+ assert body["access_token"] == "UPSTREAM-SECRET-TOKEN"++async def _exchange_persistence_attempted_for_auth_type(auth_type) -> bool:"""Run exchange_token_with_server for a server of ``auth_type`` and report whether it attemptedto persist the exchanged token server-side. The client-forwarded token modes must not persist: