Skip to content

fix(mcp): return 401 challenge for REST token-exchange tool calls without a subject token - #42782

Merged
joshua-berri merged 3 commits into
mainfrom
litellm_lit8471_mcp_rest_token_exchange_401
Sep 23, 2026
Merged

joshua-berri merged 3 commits into
mainfrom
litellm_lit8471_mcp_rest_token_exchange_401

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • POST /mcp-rest/tools/call on a token-exchange server with no subject bearer returned 500
  • Only on a cold catalog; a warm catalog already returned the 401 challenge
  • The best-effort cold listing swallowed the upstream 401, then tool lookup failed as "not found"

How it solves it:

  • Before the cold listing, challenge when the target is token-exchange, allowed, and has no subject token
  • Reuses the existing RFC 9728 WWW-Authenticate challenge and subject-token extraction
  • Valid-subject OBO flow, unknown-tool handling, PKCE and other auth types are untouched

User Flow

Before: a client that authenticates to LiteLLM with a virtual key and has not yet obtained an IdP token gets a 500 instead of being told how to authenticate

  1. They send POST https://litellm-domain/mcp-rest/tools/call with x-litellm-api-key: sk-... and body {"server_id": "<id>", "name": "<alias>-add", "arguments": {"a": 2, "b": 3}}
  2. They get 500 {"error":"internal_server_error","message":"An unexpected error occurred: Tool add not found"} with no WWW-Authenticate header, so the client cannot discover the IdP
  3. Only after someone else has called that server with a valid token does the same request return 401 with the WWW-Authenticate challenge

After: the same request gets the 401 challenge on the first call, so the client can discover the IdP, sign in, and retry

  1. They send POST https://litellm-domain/mcp-rest/tools/call with x-litellm-api-key: sk-... and the same body
  2. They get 401 {"detail":"Unauthorized"} with WWW-Authenticate: Bearer resource_metadata="/.well-known/oauth-protected-resource/mcp/<alias>", error="invalid_token", error_description="Missing or invalid subject token; authenticate with the IdP and retry"
  3. They fetch the resource metadata, sign in with the IdP, and retry with Authorization: Bearer <user token>
  4. They get 200 with the tool result; LiteLLM exchanged their token for one scoped to the upstream server and never forwarded their own token
  5. In both Before and After the token endpoint and the upstream MCP server receive no request when the subject is missing

Relevant issues

Follow-up to the integration report in #42711

Affected release

Linear ticket

Resolves LIT-8471

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Setup: the integration stack from .circleci/scripts/run_integration.sh (real proxy on Postgres and Redis, the harness's scripted MCP peer and OAuth token endpoint as the protocol-edge upstreams), a fresh oauth2_token_exchange server registered through POST /v1/mcp/server, and a key scoped to it via POST /key/generate. The same three curls run in order on each side. Request and response headers unrelated to the fix are trimmed

Before (e0af991)

Cold catalog, no subject token

  1. curl -s -i -X POST http://127.0.0.1:4010/mcp-rest/tools/call -H 'x-litellm-api-key: sk-<key>' -H 'Content-Type: application/json' -d '{"server_id": "bd6409b9-1ed8-4b9c-98d5-fa612f2c632b", "name": "te01b7a945-add", "arguments": {"a": 2, "b": 3}}'
  2. HTTP/1.1 500 Internal Server Error and body {"detail":{"error":"internal_server_error","message":"An unexpected error occurred: Tool add not found"}}; peer tools/call 0, token requests 0

Control, valid subject token

  1. Same curl plus -H 'Authorization: Bearer subject-abc'
  2. HTTP/1.1 200 OK and body {"content":[{"type":"text","text":"5"}],"structuredContent":{"result":5},"isError":false,...}; peer tools/call 1, token requests 1

Warm catalog, no subject token

  1. Same curl as the cold case, repeated after the control
  2. HTTP/1.1 401 Unauthorized with www-authenticate: Bearer resource_metadata="/.well-known/oauth-protected-resource/mcp/te01b7a945", error="invalid_token", error_description="Missing or invalid subject token; authenticate with the IdP and retry"; peer tools/call 0, token requests 0

After (8353712, product code unchanged at tip 1d42560)

Cold catalog, no subject token

  1. curl -s -i -X POST http://127.0.0.1:4010/mcp-rest/tools/call -H 'x-litellm-api-key: sk-<key>' -H 'Content-Type: application/json' -d '{"server_id": "<id>", "name": "tee579b8a9-add", "arguments": {"a": 2, "b": 3}}'
  2. HTTP/1.1 401 Unauthorized with www-authenticate: Bearer resource_metadata="/.well-known/oauth-protected-resource/mcp/tee579b8a9", error="invalid_token", error_description="Missing or invalid subject token; authenticate with the IdP and retry" and body {"detail":"Unauthorized"}; peer tools/call 0, token requests 0

Control, valid subject token

  1. Same curl plus -H 'Authorization: Bearer subject-abc'
  2. HTTP/1.1 200 OK and body {"content":[{"type":"text","text":"5"}],"structuredContent":{"result":5},"isError":false,...}; peer tools/call 1, token requests 1

Warm catalog, no subject token

  1. Same curl as the cold case, repeated after the control
  2. HTTP/1.1 401 Unauthorized with the same www-authenticate challenge as the cold case; peer tools/call 0, token requests 0

Tests: tests/integration/mcp/test_mcp_oauth_flows.py::test_token_exchange_without_a_subject_token_is_rejected_before_any_upstream_request has its BUG skip removed and now asserts cold 401 + challenge, a valid-subject warm-up (200, one exchange, one peer call), warm 401 + challenge, and a virtual key placed in Authorization still challenging, with zero upstream requests on every no-subject leg. The whole tests/integration/mcp group passes against the fixed proxy (213 passed, 4 pre-existing skips). Unit coverage in tests/test_litellm/proxy/_experimental/mcp_server/test_operations.py was mutation-checked: dropping the auth-type guard, dropping the allowlist guard, swapping subject extraction for plain bearer extraction, dropping the server_id agreement guard, or removing the call each turn at least one test red

Type

🐛 Bug Fix

Caveats (if any)

Low

  • An allowed token-exchange server with no subject now 401s even when the tool name does not exist (401 before name resolution, by design, so the response does not reveal the catalog)
  • When server_id names a different server than the tool prefix, the challenge is skipped so the existing 403 tool_server_mismatch answer is kept
  • On the aggregate /mcp JSON-RPC route with no server pinned, a no-subject tools/call on a token-exchange server now maps to an unauthorized JSON-RPC error instead of "tool not found"

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/877d4ff0585540b88fb91e28de42fcb2
Open in Devin Desktop: https://app.devin.ai/desktop/session/877d4ff0585540b88fb91e28de42fcb2?variant=devin

…hout a subject token

Co-Authored-By: bot_apk <apk@cognition.ai>
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 19:28
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge, with both previous findings fully addressed and no new actionable defects found

Summary

This PR makes missing subject tokens return the existing OAuth challenge before cold MCP catalog discovery can hide the authentication failure

  • Restricts the early challenge to allowed token-exchange servers
  • Preserves the existing server ID mismatch response
  • Adds cold, warm, valid-subject, virtual-key, allowlist, and authentication-type coverage
  • Fully types the new unit-test helpers and parameters

Reviews (3) · Last reviewed commit: "test(mcp): type the token-exchange chall..."

@codecov

codecov Bot commented Sep 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit8471_mcp_rest_token_exchange_401 (1d42560) with main (5beac4f)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (966f695) during the generation of this report, so 5beac4f was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

… tool prefix

Co-Authored-By: bot_apk <apk@cognition.ai>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review the tip, the server_id mismatch finding is addressed in 8353712

Co-Authored-By: bot_apk <apk@cognition.ai>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review the tip, the test helper typing finding is addressed in 1d42560

@joshua-berri
joshua-berri merged commit dc14e76 into main Sep 23, 2026
100 of 101 checks passed
@joshua-berri
joshua-berri deleted the litellm_lit8471_mcp_rest_token_exchange_401 branch September 23, 2026 21:13

This branch had an error being deployed

1 failed deployment
e2e-changed — 1d42560d Deployed Sep 23, 2026 by devin-ai-integration[bot] via oauth #642
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants