Repository navigation
fix(mcp): relay upstream OAuth token and DCR rejections instead of a generic 500 #33113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
tin-berri
merged 7 commits into
litellm_internal_staging
from
litellm_mcp_oauth_error_relay
Jul 14, 2026
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f903825
fix(mcp): relay upstream OAuth token and DCR rejections instead of a …
tin-berri e940199
refactor(mcp): drop bridge relay status check made unreachable by the…
tin-berri 0d9c3cf
fix(mcp): keep out-of-contract upstream error bodies out of client re…
tin-berri 9e94f2b
refactor(mcp): classify upstream OAuth faults once and derive status,…
tin-berri e809002
style(mcp): unquote annotations and use PEP 604 unions in the faults …
tin-berri 9335ede
fix(mcp): keep upstream self-blame codes and gateway capability gaps …
tin-berri b70de76
Merge origin/litellm_internal_staging (#32980 bridge refresh envelope…
tin-berri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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", | ||
| ] |
107 changes: 107 additions & 0 deletions
107
litellm/proxy/_experimental/mcp_server/faults/classify.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"))) | ||
74 changes: 74 additions & 0 deletions
74
litellm/proxy/_experimental/mcp_server/faults/render_oauth.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.