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
refactor(mcp): classify upstream OAuth faults once and derive status, code, and prose from the value
Tin Chi Lo9e94f2be14b4
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex 42677229add..6435db37645 100644--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@ -24,6 +24,14 @@ from litellm.proxy._experimental.mcp_server.auth.token_endpoint_auth import (TokenEndpointAuthConfigError,build_token_endpoint_client_auth,)+from litellm.proxy._experimental.mcp_server.faults import (+ CredentialSource,+ UpstreamProtocolFault,+ classify_upstream_dcr_rejection,+ classify_upstream_token_rejection,+ dcr_fault_detail,+ render_token_fault,+)from litellm.proxy._experimental.mcp_server.oauth_utils import (TOKEN_NO_CACHE_HEADERS,get_request_base_url,@@ -980,55 +988,11 @@ def _finish_bridge_mint(return JSONResponse(body, headers=TOKEN_NO_CACHE_HEADERS)-def _response_json_or_none(response: httpx.Response) -> object:- try:- return response.json()- except ValueError:- return None---def _upstream_token_fault_response(description: str) -> JSONResponse:- """502 token-endpoint response for an upstream fault, in the RFC 6749 §5.2 shape the gateway's- token callers parse, with the §5.1 no-store headers."""- return JSONResponse(- status_code=502,- content={"error": "server_error", "error_description": description},- headers=TOKEN_NO_CACHE_HEADERS,- )---def _upstream_token_error_response(response: httpx.Response) -> JSONResponse:- """Relay an upstream token-endpoint rejection to the client instead of letting the raw- ``httpx.HTTPStatusError`` escape to the global handler as an opaque 500 (the IdP's own- ``error_description``, e.g. Google's "client_secret is missing.", is the message the caller needs).- Only the RFC 6749 §5.2 fields (``error`` / ``error_description`` / ``error_uri``) are relayed,- each bounded, on the upstream's own 400/401 status; a rejection outside the §5.2 contract- (no JSON ``error`` field, or a status §5.2 does not define) maps to 502 so a broken upstream- is not misattributed to the caller's request. Out-of-contract bodies (HTML error pages, proxy- banners, stack traces) never cross the trust boundary: these endpoints serve unauthenticated- OAuth clients, so the body is logged server-side and the client sees only the upstream status."""- parsed = _response_json_or_none(response)- error_code = parsed.get("error") if isinstance(parsed, dict) else None- if not isinstance(error_code, str) or not error_code:- verbose_logger.warning(- "MCP upstream token endpoint returned HTTP %s with a non-RFC6749 body (first %s chars): %s",- response.status_code,- _MAX_UPSTREAM_ERROR_CHARS,- (response.text or "")[:_MAX_UPSTREAM_ERROR_CHARS],- )- return _upstream_token_fault_response(f"upstream token endpoint returned HTTP {response.status_code}")- fields = parsed if isinstance(parsed, dict) else {}- relayed = {- key: value[:_MAX_UPSTREAM_ERROR_CHARS]- for key, value in (- ("error", error_code),- ("error_description", fields.get("error_description")),- ("error_uri", fields.get("error_uri")),- )- if isinstance(value, str) and value- }- status_code = response.status_code if response.status_code in (400, 401) else 502- return JSONResponse(status_code=status_code, content=relayed, headers=TOKEN_NO_CACHE_HEADERS)+def _token_credential_source(mcp_server: MCPServer) -> CredentialSource:+ """Mirrors the resolved-client rule in :func:`exchange_token_with_server`: when the server has a+ stored client_id the gateway presents its own credentials upstream, so a credential rejection is+ the operator's fault, not the caller's."""+ return "gateway_stored" if mcp_server.client_id else "caller_supplied"async def exchange_token_with_server(@@ -1124,14 +1088,13 @@ async def exchange_token_with_server(if response is not None:response.raise_for_status()except httpx.HTTPStatusError as exc:- if "invalid_target" in exc.response.text:- verbose_logger.warning(- "MCP server %s: the upstream authorization server rejected the token request with "- "invalid_target; it may require RFC 8707 resource indicators, which the gateway "- "does not send yet (tracked as LIT-4339)",- mcp_server.server_id,+ return render_token_fault(+ classify_upstream_token_rejection(+ exc.response,+ credential_source=_token_credential_source(mcp_server),+ log_context=mcp_server.server_id,)- return _upstream_token_error_response(exc.response)+ )if response is None:raise HTTPException(status_code=502,@@ -1188,7 +1151,7 @@ async def exchange_token_with_server(raw_access_token = token_response.get("access_token") if isinstance(token_response, dict) else Noneif not isinstance(raw_access_token, str) or not raw_access_token:- return _upstream_token_fault_response("the upstream token response has no usable access_token")+ return render_token_fault(UpstreamProtocolFault(note="the upstream token response has no usable access_token"))result = {"access_token": raw_access_token,@@ -1447,31 +1410,6 @@ async def _persist_dcr_client_registration(return "failed"-_MAX_UPSTREAM_ERROR_CHARS = 500---def _safe_upstream_error_detail(response: httpx.Response) -> str:- """Client-safe summary of an upstream registration failure: only the RFC 7591 §3.2.2 fields- (``error`` / ``error_description``) cross the trust boundary, each bounded, since these endpoints- serve unauthenticated OAuth clients. A body outside that contract (HTML error pages, proxy- banners, stack traces) is logged server-side and summarized by status so upstream internals are- never relayed to callers."""- parsed = _response_json_or_none(response)- error_code = parsed.get("error") if isinstance(parsed, dict) else None- if isinstance(error_code, str) and error_code:- description = parsed.get("error_description") if isinstance(parsed, dict) else None- if isinstance(description, str) and description:- return f"{error_code[:_MAX_UPSTREAM_ERROR_CHARS]}: {description[:_MAX_UPSTREAM_ERROR_CHARS]}"- return error_code[:_MAX_UPSTREAM_ERROR_CHARS]- verbose_logger.warning(- "MCP upstream registration endpoint returned HTTP %s with a non-RFC7591 body (first %s chars): %s",- response.status_code,- _MAX_UPSTREAM_ERROR_CHARS,- (response.text or "")[:_MAX_UPSTREAM_ERROR_CHARS],- )- return f"upstream registration failed with HTTP {response.status_code}"--async def register_client_with_server(request: Request,mcp_server: MCPServer,@@ -1540,9 +1478,10 @@ async def register_client_with_server(if response is not None:response.raise_for_status()except httpx.HTTPStatusError as exc:- raise HTTPException(- status_code=exc.response.status_code, detail=_safe_upstream_error_detail(exc.response)- ) from exc+ status_code, detail = dcr_fault_detail(+ classify_upstream_dcr_rejection(exc.response, log_context=mcp_server.server_id)+ )+ raise HTTPException(status_code=status_code, detail=detail) from excif response is None:raise HTTPException(status_code=502,diff --git a/litellm/proxy/_experimental/mcp_server/faults/__init__.py b/litellm/proxy/_experimental/mcp_server/faults/__init__.pynew file mode 100644index 00000000000..ccbba308012--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/faults/__init__.py@@ -0,0 +1,36 @@+"""Typed fault values for upstream OAuth/DCR failures (phase 1 of the MCP error-handling framework).++The invariant this package exists to enforce: an upstream failure is classified ONCE into a single+fault value, and the response status, wire error code, and prose are all derived from that value.+Deriving all three from one classification makes contradictory pairings (a caller-fault error code on+a server-fault status) unrepresentable, and gives the trust-boundary rule one enforcement point:+spec-defined machine fields may cross to callers, upstream prose and raw bodies go to server logs.+"""++from litellm.proxy._experimental.mcp_server.faults.classify import (+ classify_upstream_dcr_rejection,+ classify_upstream_token_rejection,+)+from litellm.proxy._experimental.mcp_server.faults.render_oauth import (+ dcr_fault_detail,+ render_token_fault,+)+from litellm.proxy._experimental.mcp_server.faults.types import (+ CallerRejected,+ CredentialSource,+ GatewayCredentialsRejected,+ UpstreamOAuthFault,+ UpstreamProtocolFault,+)++__all__ = [+ "CallerRejected",+ "CredentialSource",+ "GatewayCredentialsRejected",+ "UpstreamOAuthFault",+ "UpstreamProtocolFault",+ "classify_upstream_dcr_rejection",+ "classify_upstream_token_rejection",+ "dcr_fault_detail",+ "render_token_fault",+]diff --git a/litellm/proxy/_experimental/mcp_server/faults/classify.py b/litellm/proxy/_experimental/mcp_server/faults/classify.pynew file mode 100644index 00000000000..a816b8e2a96--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/faults/classify.py@@ -0,0 +1,107 @@+"""The single place that reads upstream OAuth/DCR failure responses.++Every accessor here is total: an upstream that lies about its content encoding, sends an undecodable+body, or omits the spec fields yields a classified fault, never an exception. Nothing outside this+module should touch a failed upstream response's body.+"""++from __future__ import annotations++import httpx++from litellm._logging import verbose_logger+from litellm.proxy._experimental.mcp_server.faults.types import (+ GATEWAY_RESPONSIBILITY_CODES,+ MAX_WIRE_FIELD_CHARS,+ CallerRejected,+ CredentialSource,+ GatewayCredentialsRejected,+ UpstreamOAuthFault,+ UpstreamProtocolFault,+)+++def _safe_text(response: httpx.Response) -> str:+ try:+ return response.text+ except Exception:+ return ""+++def _safe_json(response: httpx.Response) -> object:+ try:+ return response.json()+ except Exception:+ return None+++def _bounded_field(value: object) -> "str | None":+ if not isinstance(value, str) or not value:+ return None+ return value[:MAX_WIRE_FIELD_CHARS]+++def _log_out_of_contract(endpoint_kind: str, response: httpx.Response, log_context: str) -> None:+ verbose_logger.warning(+ "MCP upstream %s endpoint (%s) returned HTTP %s outside the OAuth error contract (first %s chars): %s",+ endpoint_kind,+ log_context,+ response.status_code,+ MAX_WIRE_FIELD_CHARS,+ _safe_text(response)[:MAX_WIRE_FIELD_CHARS],+ )+++def classify_upstream_token_rejection(+ response: httpx.Response,+ credential_source: CredentialSource,+ log_context: str,+) -> UpstreamOAuthFault:+ """Classify a token-endpoint rejection into exactly one fault.++ A body with an RFC 6749 §5.2 ``error`` field is a contract-conformant rejection: it indicts the+ gateway when the code blames the client credentials the gateway itself presented+ (``GATEWAY_RESPONSIBILITY_CODES`` with ``gateway_stored`` credentials), and the caller otherwise.+ The upstream's HTTP status is deliberately not consulted for blame: status is derived from the+ classification at render time, which is what keeps status and code from contradicting each other.+ Anything without a usable ``error`` field is an upstream protocol fault."""+ parsed = _safe_json(response)+ fields = parsed if isinstance(parsed, dict) else {}+ code = _bounded_field(fields.get("error"))+ if code is None:+ _log_out_of_contract("token", response, log_context)+ return UpstreamProtocolFault(note=f"upstream token endpoint returned HTTP {response.status_code}")+ if code == "invalid_target":+ verbose_logger.warning(+ "MCP server %s: the upstream authorization server rejected the token request with "+ "invalid_target; it may require RFC 8707 resource indicators, which the gateway "+ "does not send yet (tracked as LIT-4339)",+ log_context,+ )+ if credential_source == "gateway_stored" and code in GATEWAY_RESPONSIBILITY_CODES:+ verbose_logger.warning(+ "MCP server %s: upstream authorization server rejected the gateway's configured client "+ "credentials (%s): %s",+ log_context,+ code,+ _bounded_field(fields.get("error_description")) or "<no description>",+ )+ return GatewayCredentialsRejected(code=code)+ return CallerRejected(+ code=code,+ description=_bounded_field(fields.get("error_description")),+ error_uri=_bounded_field(fields.get("error_uri")),+ )+++def classify_upstream_dcr_rejection(response: httpx.Response, log_context: str) -> UpstreamOAuthFault:+ """Classify a dynamic-client-registration rejection. RFC 7591 §3.2.2 errors carry+ ``error`` / ``error_description`` and are caller-actionable (the registration metadata was+ rejected); anything else is an upstream protocol fault."""+ parsed = _safe_json(response)+ fields = parsed if isinstance(parsed, dict) else {}+ code = _bounded_field(fields.get("error"))+ if code is None:+ _log_out_of_contract("registration", response, log_context)+ return UpstreamProtocolFault(note=f"upstream registration failed with HTTP {response.status_code}")+ return CallerRejected(code=code, description=_bounded_field(fields.get("error_description")))diff --git a/litellm/proxy/_experimental/mcp_server/faults/render_oauth.py b/litellm/proxy/_experimental/mcp_server/faults/render_oauth.pynew file mode 100644index 00000000000..5fc82819dc0--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/faults/render_oauth.py@@ -0,0 +1,74 @@+"""Render upstream OAuth/DCR faults onto the wire. The only place that chooses statuses and bodies+for these faults, so every consumer emits the same contract: RFC 6749 §5.2-shaped JSON with the §5.1+no-store headers on token endpoints, HTTPException details on registration. Status, code, and prose+all derive from the fault tag; exhaustive matches keep a new fault arm from shipping unrendered.+"""++from __future__ import annotations++from fastapi.responses import JSONResponse+from typing_extensions import assert_never++from litellm.proxy._experimental.mcp_server.faults.types import UpstreamOAuthFault+from litellm.proxy._experimental.mcp_server.oauth_utils import TOKEN_NO_CACHE_HEADERS+++def _gateway_credentials_description(code: str) -> str:+ if code == "invalid_target":+ return (+ "the upstream authorization server rejected the token request (invalid_target); "+ "it may require RFC 8707 resource indicators, which the gateway does not send yet"+ )+ return (+ f"the upstream authorization server rejected the gateway's configured client credentials "+ f"({code}); verify the MCP server's client_id and client_secret"+ )+++def render_token_fault(fault: UpstreamOAuthFault) -> JSONResponse:+ """RFC 6749 §5.2 response for a token-endpoint fault. Caller-actionable rejections relay the+ upstream's code on the status that code implies (401 for invalid_client per §5.2, else 400);+ gateway-side faults are 502 ``server_error`` with gateway-authored prose so a caller is never+ blamed for, or shown the internals of, a failure only the operator can fix."""+ match fault.tag:+ case "caller_rejected":+ content = {+ "error": fault.code,+ **({"error_description": fault.description} if fault.description else {}),+ **({"error_uri": fault.error_uri} if fault.error_uri else {}),+ }+ status_code = 401 if fault.code == "invalid_client" else 400+ return JSONResponse(status_code=status_code, content=content, headers=TOKEN_NO_CACHE_HEADERS)+ case "gateway_credentials_rejected":+ return JSONResponse(+ status_code=502,+ content={+ "error": "server_error",+ "error_description": _gateway_credentials_description(fault.code),+ },+ headers=TOKEN_NO_CACHE_HEADERS,+ )+ case "upstream_protocol_fault":+ return JSONResponse(+ status_code=502,+ content={"error": "server_error", "error_description": fault.note},+ headers=TOKEN_NO_CACHE_HEADERS,+ )+ case _:+ assert_never(fault.tag)+++def dcr_fault_detail(fault: UpstreamOAuthFault) -> "tuple[int, str]":+ """Status and detail string for a registration fault, raised as HTTPException by the caller.+ RFC 7591 §3.2.2 defines registration errors as 400, so a contract-conformant rejection is 400+ regardless of the status the upstream chose; everything else is a 502 upstream fault."""+ match fault.tag:+ case "caller_rejected":+ detail = f"{fault.code}: {fault.description}" if fault.description else fault.code+ return 400, detail+ case "gateway_credentials_rejected":+ return 502, _gateway_credentials_description(fault.code)+ case "upstream_protocol_fault":+ return 502, fault.note+ case _:+ assert_never(fault.tag)diff --git a/litellm/proxy/_experimental/mcp_server/faults/types.py b/litellm/proxy/_experimental/mcp_server/faults/types.pynew file mode 100644index 00000000000..2a200323024--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/faults/types.py@@ -0,0 +1,60 @@+"""Fault taxonomy for upstream OAuth token and DCR registration failures.++Each fault is a frozen model on a ``tag`` literal. The tag alone decides the HTTP status, the wire+error code, and whose prose the caller sees, so those three facts can never disagree the way they can+when an upstream's status and error code are relayed independently.+"""++from __future__ import annotations++from typing import Literal, Optional, TypeAlias++from pydantic import BaseModel, ConfigDict++MAX_WIRE_FIELD_CHARS = 500+"""Bound on every upstream-derived string that crosses to a caller or into a log line."""++CredentialSource: TypeAlias = Literal["gateway_stored", "caller_supplied"]+"""Whose client credentials the gateway presented upstream: the MCP server's stored configuration or+credentials the caller supplied on the request. Decides whether a credential rejection is the+caller's problem to fix or the gateway operator's."""++GATEWAY_RESPONSIBILITY_CODES: frozenset[str] = frozenset({"invalid_client", "unauthorized_client", "invalid_target"})+"""RFC 6749 error codes that indict the OAuth client itself (its credentials, its grant+authorization, or a gateway capability such as RFC 8707 resource indicators). When the gateway+presented its own stored credentials, these are gateway-side faults the caller cannot act on."""+++class CallerRejected(BaseModel):+ """The upstream spoke the OAuth error contract and the failure is actionable by our caller+ (e.g. ``invalid_grant``: re-run authorization). The code and its bounded prose relay on the+ 4xx status the code itself implies."""++ model_config = ConfigDict(frozen=True)+ tag: Literal["caller_rejected"] = "caller_rejected"+ code: str+ description: Optional[str] = None+ error_uri: Optional[str] = None+++class GatewayCredentialsRejected(BaseModel):+ """The upstream rejected the gateway's own stored client credentials or a gateway capability.+ Not actionable by the caller: rendered as 502 with gateway-authored prose naming the code;+ the upstream's prose goes to server logs only."""++ model_config = ConfigDict(frozen=True)+ tag: Literal["gateway_credentials_rejected"] = "gateway_credentials_rejected"+ code: str+++class UpstreamProtocolFault(BaseModel):+ """The upstream broke the error contract: no JSON ``error`` field, an undecodable body, or a+ success response without a usable token. Rendered as 502 with a gateway-authored note; the+ upstream body never crosses to the caller."""++ model_config = ConfigDict(frozen=True)+ tag: Literal["upstream_protocol_fault"] = "upstream_protocol_fault"+ note: str+++UpstreamOAuthFault: TypeAlias = CallerRejected | GatewayCredentialsRejected | UpstreamProtocolFaultdiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_classify.py b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_classify.pynew file mode 100644index 00000000000..32148e7a247--- /dev/null+++ b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_classify.py@@ -0,0 +1,108 @@+"""Classification matrix for upstream OAuth/DCR rejections: who is blamed depends only on the §5.2+code and whose credentials the gateway presented, never on the upstream's HTTP status."""++import httpx++from litellm.proxy._experimental.mcp_server.faults.classify import (+ classify_upstream_dcr_rejection,+ classify_upstream_token_rejection,+)+from litellm.proxy._experimental.mcp_server.faults.types import (+ CallerRejected,+ GatewayCredentialsRejected,+ UpstreamProtocolFault,+)+++def _response(status_code: int, *, json_body: object = None, text_body: str = "", headers: dict = None) -> httpx.Response:+ request = httpx.Request("POST", "https://idp.example.com/token")+ if json_body is not None:+ return httpx.Response(status_code, json=json_body, request=request)+ return httpx.Response(status_code, text=text_body, headers=headers or {}, request=request)+++def test_caller_fault_code_classifies_as_caller_rejected_regardless_of_status():+ fault = classify_upstream_token_rejection(+ _response(500, json_body={"error": "invalid_grant", "error_description": "Code expired."}),+ credential_source="gateway_stored",+ log_context="srv",+ )+ assert isinstance(fault, CallerRejected)+ assert fault.code == "invalid_grant"+ assert fault.description == "Code expired."+++def test_credential_code_with_gateway_stored_credentials_indicts_gateway():+ fault = classify_upstream_token_rejection(+ _response(401, json_body={"error": "invalid_client", "error_description": "not found"}),+ credential_source="gateway_stored",+ log_context="srv",+ )+ assert isinstance(fault, GatewayCredentialsRejected)+ assert fault.code == "invalid_client"+++def test_credential_code_with_caller_supplied_credentials_stays_caller_fault():+ fault = classify_upstream_token_rejection(+ _response(401, json_body={"error": "invalid_client"}),+ credential_source="caller_supplied",+ log_context="srv",+ )+ assert isinstance(fault, CallerRejected)+ assert fault.code == "invalid_client"+++def test_unknown_code_relays_as_caller_rejected():+ fault = classify_upstream_token_rejection(+ _response(400, json_body={"error": "slow_down", "error_description": "Polling too fast."}),+ credential_source="gateway_stored",+ log_context="srv",+ )+ assert isinstance(fault, CallerRejected)+ assert fault.code == "slow_down"+++def test_body_without_error_field_is_protocol_fault():+ fault = classify_upstream_token_rejection(+ _response(404, text_body="<html>not here</html>"),+ credential_source="gateway_stored",+ log_context="srv",+ )+ assert isinstance(fault, UpstreamProtocolFault)+ assert fault.note == "upstream token endpoint returned HTTP 404"+++def test_unreadable_body_is_protocol_fault_not_exception():+ unreadable = httpx.Response(+ 400,+ stream=httpx.ByteStream(b"\x1f\x8bnot-gzip"),+ headers={"content-encoding": "gzip"},+ request=httpx.Request("POST", "https://idp.example.com/token"),+ )+ fault = classify_upstream_token_rejection(unreadable, credential_source="gateway_stored", log_context="srv")+ assert isinstance(fault, UpstreamProtocolFault)+++def test_wire_fields_are_bounded():+ fault = classify_upstream_token_rejection(+ _response(400, json_body={"error": "invalid_request", "error_description": "x" * 5000}),+ credential_source="gateway_stored",+ log_context="srv",+ )+ assert isinstance(fault, CallerRejected)+ assert len(fault.description) == 500+++def test_dcr_rejection_with_rfc7591_code_is_caller_rejected():+ fault = classify_upstream_dcr_rejection(+ _response(400, json_body={"error": "invalid_redirect_uri", "error_description": "not allowed"}),+ log_context="srv",+ )+ assert isinstance(fault, CallerRejected)+ assert fault.code == "invalid_redirect_uri"+++def test_dcr_rejection_without_code_is_protocol_fault():+ fault = classify_upstream_dcr_rejection(_response(500, text_body="<html>trace</html>"), log_context="srv")+ assert isinstance(fault, UpstreamProtocolFault)+ assert fault.note == "upstream registration failed with HTTP 500"diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_render_oauth.py b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_render_oauth.pynew file mode 100644index 00000000000..a025cbe2b01--- /dev/null+++ b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_render_oauth.py@@ -0,0 +1,75 @@+"""Rendering contract: status, wire code, and prose all derive from the fault tag, so a caller-fault+code can never ship on a server-fault status and gateway-side faults never carry provider prose."""++import json++from litellm.proxy._experimental.mcp_server.faults.render_oauth import (+ dcr_fault_detail,+ render_token_fault,+)+from litellm.proxy._experimental.mcp_server.faults.types import (+ CallerRejected,+ GatewayCredentialsRejected,+ UpstreamProtocolFault,+)+++def test_caller_rejected_renders_code_derived_status():+ response = render_token_fault(CallerRejected(code="invalid_grant", description="Code expired."))+ assert response.status_code == 400+ assert json.loads(response.body) == {"error": "invalid_grant", "error_description": "Code expired."}+ assert response.headers["cache-control"] == "no-store"+++def test_caller_rejected_invalid_client_renders_401():+ response = render_token_fault(CallerRejected(code="invalid_client"))+ assert response.status_code == 401+ assert json.loads(response.body) == {"error": "invalid_client"}+++def test_caller_rejected_includes_error_uri_only_when_present():+ response = render_token_fault(+ CallerRejected(code="invalid_scope", description="bad scope", error_uri="https://idp.example.com/e")+ )+ assert json.loads(response.body) == {+ "error": "invalid_scope",+ "error_description": "bad scope",+ "error_uri": "https://idp.example.com/e",+ }+++def test_gateway_credentials_rejected_renders_502_with_gateway_prose():+ response = render_token_fault(GatewayCredentialsRejected(code="invalid_client"))+ assert response.status_code == 502+ body = json.loads(response.body)+ assert body["error"] == "server_error"+ assert "invalid_client" in body["error_description"]+ assert "client_id and client_secret" in body["error_description"]+++def test_gateway_invalid_target_prose_names_resource_indicators():+ response = render_token_fault(GatewayCredentialsRejected(code="invalid_target"))+ body = json.loads(response.body)+ assert response.status_code == 502+ assert "RFC 8707" in body["error_description"]+++def test_protocol_fault_renders_502_note():+ response = render_token_fault(UpstreamProtocolFault(note="upstream token endpoint returned HTTP 503"))+ assert response.status_code == 502+ assert json.loads(response.body) == {+ "error": "server_error",+ "error_description": "upstream token endpoint returned HTTP 503",+ }+++def test_dcr_caller_rejection_is_400_per_rfc7591_regardless_of_upstream_status():+ status_code, detail = dcr_fault_detail(CallerRejected(code="invalid_client_metadata", description="bad grant types"))+ assert status_code == 400+ assert detail == "invalid_client_metadata: bad grant types"+++def test_dcr_protocol_fault_is_502():+ status_code, detail = dcr_fault_detail(UpstreamProtocolFault(note="upstream registration failed with HTTP 500"))+ assert status_code == 502+ assert detail == "upstream registration failed with HTTP 500"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 d494e1c6cb3..a67579c79ca 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@@ -5979,9 +5979,10 @@ def _upstream_token_response(status_code: int, *, json_body: object = None, textreturn httpx.Response(status_code, text=text_body, request=request)-async def _exchange_with_upstream_response(upstream_response):+async def _exchange_with_upstream_response(upstream_response, *, server_client_id="web-client.apps.googleusercontent.com"):"""Run the raw (non-bridge) authorization_code exchange against a canned upstream token-endpoint- response and return what the gateway would hand the client."""+ response and return what the gateway would hand the client. ``server_client_id=None`` models the+ caller-supplied-credentials flow (no stored client on the server)."""from fastapi import Requestfrom litellm.proxy._experimental.mcp_server.discoverable_endpoints import (@@ -5998,7 +5999,7 @@ async def _exchange_with_upstream_response(upstream_response):alias="gcal",transport=MCPTransport.http,auth_type=MCPAuth.oauth2,- client_id="web-client.apps.googleusercontent.com",+ client_id=server_client_id,authorization_url="https://accounts.google.com/o/oauth2/v2/auth",token_url="https://oauth2.googleapis.com/token",)@@ -6025,20 +6026,55 @@ async def _exchange_with_upstream_response(upstream_response):@pytest.mark.asyncio-async def test_token_exchange_relays_upstream_rfc6749_rejection():- """The IdP's own RFC 6749 §5.2 rejection is the message the caller needs (e.g. Google refusing a- secret-less web client); before the relay the raw HTTPStatusError escaped to the global handler- and every upstream rejection surfaced as an opaque 500 Internal server error."""+async def test_token_exchange_gateway_credential_rejection_is_502_with_gateway_prose():+ """When the gateway presented the server's stored client credentials and the IdP rejected them+ (Google refusing a secret-less or unknown client), the fault is the operator's, not the caller's:+ 502 server_error with gateway-authored prose naming the code, and the IdP's own prose stays in+ server logs. Before the framework this either 500ed raw or relayed provider prose verbatim."""response = await _exchange_with_upstream_response(_upstream_token_response(401, json_body={"error": "invalid_client", "error_description": "The OAuth client was not found."}))+ assert response.status_code == 502+ body = json.loads(response.body)+ assert body["error"] == "server_error"+ assert "invalid_client" in body["error_description"]+ assert "client_id and client_secret" in body["error_description"]+ assert "The OAuth client was not found." not in body["error_description"]+ assert response.headers["cache-control"] == "no-store"+++async def test_token_exchange_caller_supplied_credential_rejection_relays_code():+ """When the caller supplied the client credentials themselves (no stored client on the server),+ an invalid_client rejection is theirs to act on: the §5.2 code relays on the 401 that code+ implies."""+ response = await _exchange_with_upstream_response(+ _upstream_token_response(+ 401, json_body={"error": "invalid_client", "error_description": "The OAuth client was not found."}+ ),+ server_client_id=None,+ )+assert response.status_code == 401body = json.loads(response.body)assert body == {"error": "invalid_client", "error_description": "The OAuth client was not found."}- assert response.headers["cache-control"] == "no-store"+++async def test_token_exchange_status_derives_from_error_code_not_upstream_status():+ """An upstream that pairs a caller-fault code with a server-fault status (invalid_grant on a 500)+ must not produce a contradictory response: status derives from the classified fault, so the+ caller sees 400 invalid_grant and knows to re-authorize rather than blaming the gateway."""+ response = await _exchange_with_upstream_response(+ _upstream_token_response(500, json_body={"error": "invalid_grant", "error_description": "Code expired."})+ )++ assert response.status_code == 400+ body = json.loads(response.body)+ assert body == {"error": "invalid_grant", "error_description": "Code expired."}@pytest.mark.asyncio@@ -6159,9 +6195,10 @@ async def test_token_exchange_relays_rejection_when_http_client_raises():code_verifier="verifier",)- assert response.status_code == 401+ assert response.status_code == 502body = json.loads(response.body)- assert body["error"] == "invalid_client"+ assert body["error"] == "server_error"+ assert "invalid_client" in body["error_description"]@pytest.mark.asyncio@@ -6268,6 +6305,27 @@ async def test_register_never_relays_out_of_contract_body_to_client():token_endpoint_auth_method=None,)- assert exc.value.status_code == 500+ assert exc.value.status_code == 502assert str(exc.value.detail) == "upstream registration failed with HTTP 500"assert "Tomcat" not in str(exc.value.detail)+++async def test_token_exchange_unreadable_body_still_renders_oauth_fault():+ """An upstream whose failure body cannot be read (unconsumed stream, lying content-encoding)+ makes response.text/.json raise; the classifier must stay total so the caller still gets the+ §5.2-shaped 502 instead of the opaque 500 this change set out to remove."""+ import httpx++ unreadable = httpx.Response(+ 400,+ stream=httpx.ByteStream(b"\x1f\x8bnot-actually-gzip"),+ headers={"content-encoding": "gzip"},+ request=httpx.Request("POST", "https://oauth2.googleapis.com/token"),+ )++ response = await _exchange_with_upstream_response(unreadable)++ assert response.status_code == 502+ body = json.loads(response.body)+ assert body == {"error": "server_error", "error_description": "upstream token endpoint returned HTTP 400"}