Repository navigation
feat(proxy): grant MCP server and tool access from JWT scope mappings - #41896
devin-ai-integration[bot] wants to merge 9 commits into
Conversation
Extend litellm_jwtauth.scope_mappings with mcp_servers, mcp_access_groups and mcp_tool_permissions so a JWT scope claim can authorize MCP servers and tools without a pre-provisioned key or team row. The MCP resolver unions the scope-derived grants into the key level, so existing team, end-user, agent, user and org ceilings still apply. Unmatched, missing, malformed or absent claims grant nothing. Resolves LIT-4505 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
bugbot run |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…owlists Evaluate each matched scope mapping as its own grant so a tool allowlist from one scope no longer narrows a server another scope granted in full. Drops the explanatory docstrings flagged in review Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…r tools for MCP JWT scopes Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… reading the proxy global Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…KeyAuth Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…cope MCP grants additive Adds scope_jwt_field to LiteLLM_JWTAuth (default "scope", dot notation supported) so scope_mappings, model scope checks, MCP grants, and admin_jwt_scope all read the same configured claim. A missing path yields no scopes and a non string/list value is rejected, so MCP access fails closed either way. Key-owned and JWT-scope MCP grants on one server are now merged as independent grants: a whole-server grant from either side keeps every tool instead of being narrowed by the other side's tool allowlist, while team and higher-level ceilings still intersect the result. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
|
@veria-ai please review 393f5a4: JWT scope claims granting MCP servers and tools, configurable claim path, additive key and scope grants under team ceilings |
…ts next to scope tools A key granted a server through access_group_ids has no tool allowlist there, so a JWT scope tool allowlist on the same server must not narrow it. Drops the helper docstrings Greptile flagged. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
|
@veria-ai please review cdd73a1: key unified access group servers now count as whole-server grants next to JWT scope tool allowlists |
…grants the server Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
|
@veria-ai please review 766fd56: unified key access groups are whole-server grants, resolved only when direct grants miss |
|
@greptileai please review commit 9ed18c3 after the SDK 2 merge, checking JWT grants and preserved permission ceilings |
|
bugbot run Please review commit 9ed18c3 after the SDK 2 merge, checking JWT grants and permission enforcement |
|
@veria-ai please review commit 9ed18c3 after the SDK 2 merge, checking JWT claims, additive grants, and authorization boundaries |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 9ed18c3. Configure here.
tin-berri
left a comment
There was a problem hiding this comment.
Approving. Resolves MCP server and tool access from JWT scope mappings, unioning scope-derived grants into the key's allowed set and adding a per-server tool grant path alongside the existing key/team resolution. No migration and no spend-table access. Flagging for the author's awareness rather than blocking: this widens which servers and tools a JWT caller can reach, so the scope-to-grant mapping is the thing to keep an eye on in staging.
|
Thanks Tin. Agreed on the staging watch item: a mapping only widens access when the IdP issues the configured claim value, and every scope-derived grant is still capped by the team/org/end-user ceilings (precedence and the fail-closed rules are written up in BerriAI/litellm-docs#1565). The |
|
This mapping solves the decision half of gateway-level MCP authorization. Worth pairing it with the evidence half while the schema is being designed: when a JWT scope grants or denies a tool call, that resolution should leave a call_id-bound, signed receipt (scope source, decision, args digest) — otherwise enterprise deployments get authorization at the gateway but still can't answer an auditor's "prove what each agent was allowed to do and what actually ran". The join |
TLDR
Problem this solves:
scopeclaim; nested IdP claims likerealm_access.roleswere unusableHow it solves it:
scope_mappingsentries acceptmcp_servers,mcp_access_groups,mcp_tool_permissionsUserAPIKeyAuth.jwt_scope_mcp_grantsscope_jwt_field(defaultscope, dot notation) picks the claim that feedsscope_mappings, model scope checks, andadmin_jwt_scopeUser Flow
Before: a platform team fronts LiteLLM with their IdP and wants a JWT scope to decide which MCP servers a caller sees, but the proxy refuses the config and, without it, the caller sees nothing
mcp_servers: ["math_alpha"]under alitellm_jwtauth.scope_mappingsentry and starts the proxyValidationError ... Extra inputs are not permittedscope: litellm.mcp.alphasends GET http://litellm-domain/v1/mcp/server[], and POST http://litellm-domain/mcp/tools/listreturns{"tools": []}tools/callformath_alpha-addreturnsError: User not allowed to call this tool.After: the same scope now grants the servers and tools the admin mapped, with no team or key row involved
mcp_servers: ["math_alpha"]under thelitellm.mcp.alphaentry andmcp_tool_permissions: {math_beta: ["add"]}underlitellm.mcp.beta_add, and the proxy starts normallyscope: litellm.mcp.alphasends GET http://litellm-domain/v1/mcp/server and gets back themath_alphaservertools/listreturnsmath_alpha-addandmath_alpha-multiply, andtools/callonmath_alpha-addwith{"a": 2, "b": 3}returns5scope: litellm.mcp.beta_addsees onlymath_beta-add, can call it, and getsTool 'multiply' is not allowed for your key/team on server 'math_beta'when they trymath_beta-multiply[],{"tools": []}, andError: User not allowed to call this tool.realm_access.rolessetsscope_jwt_field: realm_access.roles; a token withscope: openidandrealm_access: {roles: [litellm.mcp.alpha, litellm.mcp.beta_add]}getsmath_alphaplusmath_beta-add, and a chat completion ongpt-4.1-minireturnspongRelevant issues
Affected release
Linear ticket
Resolves LIT-4505
Docs: BerriAI/litellm-docs#1565 (
scope_jwt_fieldand the MCP permission precedence section)Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Shared setup for both sides: one Postgres database with two teams and zero virtual keys, two real MCP upstreams on
127.0.0.1:25505(math_alpha) and127.0.0.1:25506(math_beta), a local JWKS endpoint, and RS256 tokens minted per run with fresh subjects that belong to no team. The proxy runs on127.0.0.1:20505with--use_prisma_db_push. The chat control hits the real OpenAI API. Thescope_mappingssection undergeneral_settings.litellm_jwtauthisThe MCP calls below are all the same shape, so
mcpstands forThe base tree refuses the two MCP lines (case 1), so cases 2 to 5 on the Before side ran with the same config minus
mcp_serversandmcp_tool_permissions. Before is the current merge baseeda1faba14(main after the MCP SDK 2 merge, #41718) checked out in a clean worktree; After is the current tip9ed18c3cb0, the merge of that main into this branch (proxy build markersha=9ed18c3cb0 dirty=0). Both sides ran onmcp==2.2.0, the SDK 2 lock, and the rig's upstreams were ported to the SDK 2MCPServerAPI for this run. Since the previous run at766fd564b3the only change is that merge; no production line of this PR changedBefore (eda1fab)
Case 1: proxy boots with MCP fields in scope_mappings
python litellm/proxy/proxy_cli.py --config config.yaml --port 20505 --use_prisma_db_pushCase 2: alice, scope litellm.mcp.alpha, no key or team row
curl -s http://127.0.0.1:20505/v1/mcp/server -H "Authorization: Bearer $ALICE"[]mcp "$ALICE" "$TL"{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}HTTP 200mcp "$ALICE" "$(call math_alpha-add)"{"content":[{"type":"text","text":"Error: User not allowed to call this tool."}],"isError":true}HTTP 200mcp "$ALICE" "$(call math_beta-add)"Error: User not allowed to call this tool.HTTP 200Case 3: bob, scope litellm.mcp.beta_add, no key or team row
mcp "$BOB" "$TL"{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}HTTP 200mcp "$BOB" "$(call math_beta-add)"Error: User not allowed to call this tool.HTTP 200mcp "$BOB" "$(call math_beta-multiply)"Error: User not allowed to call this tool.HTTP 200Case 4: carol, unrelated scope
curl -s http://127.0.0.1:20505/v1/mcp/server -H "Authorization: Bearer $CAROL"thenmcp "$CAROL" "$TL"[]and{"tools":[]}HTTP 200mcp "$CAROL" "$(call math_alpha-add)"Error: User not allowed to call this tool.HTTP 200Case 5: controls
mcp sk-1234 "$TL"math_alpha-add,math_alpha-multiply,math_beta-add,math_beta-multiplyHTTP 200curl -s http://127.0.0.1:20505/v1/chat/completions -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' -d '{"model":"gpt-4.1-mini","messages":[{"role":"user","content":"Reply with the single word pong"}],"max_tokens":5}'"model":"gpt-4.1-mini"..."content":"pong"HTTP 200psql ... -c "select count(*) from \"LiteLLM_VerificationToken\""and a membership query for the three subjectskeys_total|0,teams_with_these_members|0,user_rows_with_teams|0After (9ed18c3)
Case 1: proxy boots with MCP fields in scope_mappings
python litellm/proxy/proxy_cli.py --config config.yaml --port 20505 --use_prisma_db_push/health/readinessreturns 200, serving treesha=9ed18c3cb0 dirty=0 config=config.yamlCase 2: alice, scope litellm.mcp.alpha, no key or team row
curl -s http://127.0.0.1:20505/v1/mcp/server -H "Authorization: Bearer $ALICE""server_name":"math_alpha"mcp "$ALICE" "$TL""tools":[{"name":"math_alpha-add",...},{"name":"math_alpha-multiply",...}]HTTP 200mcp "$ALICE" "$(call math_alpha-add)"{"content":[{"type":"text","text":"5"}],"isError":false}HTTP 200mcp "$ALICE" "$(call math_beta-add)"Error: User not allowed to call this tool.HTTP 200Case 3: bob, scope litellm.mcp.beta_add, no key or team row
mcp "$BOB" "$TL"{"jsonrpc":"2.0","id":1,"result":{"_meta":{"litellm.ai/server_outcomes":{"math_beta":{"status":"ok","tool_count":1}}},"tools":[{"name":"math_beta-add",...}]}}HTTP 200mcp "$BOB" "$(call math_beta-add)"{"content":[{"type":"text","text":"5"}],"isError":false}HTTP 200mcp "$BOB" "$(call math_beta-multiply)"Error: Tool 'multiply' is not allowed for your key/team on server 'math_beta'. Contact proxy admin for access.HTTP 200Case 4: carol, unrelated scope
curl -s http://127.0.0.1:20505/v1/mcp/server -H "Authorization: Bearer $CAROL"thenmcp "$CAROL" "$TL"[]and{"tools":[]}HTTP 200mcp "$CAROL" "$(call math_alpha-add)"Error: User not allowed to call this tool.HTTP 200Case 5: controls
mcp sk-1234 "$TL"math_alpha-add,math_alpha-multiply,math_beta-add,math_beta-multiplyHTTP 200$ALICE"model":"gpt-4.1-mini"..."content":"pong"HTTP 200keys_total|0,teams_with_these_members|0,user_rows_with_teams|0Case 6: custom claim path,
scope_jwt_field: realm_access.roles, no key or team row (9ed18c3)Same config plus
scope_jwt_field: realm_access.rolesunderlitellm_jwtauth. Tokens carry a decoy top-levelscopeand put the real entitlements underrealm_access.rolesscope: openid,realm_access.roles: [offline_access, litellm.mcp.alpha, litellm.mcp.beta_add]:curl -s http://127.0.0.1:20505/v1/mcp/server -H "Authorization: Bearer $ERIN"['math_alpha', 'math_beta']mcp "$ERIN" "$TL"math_alpha-add,math_alpha-multiply,math_beta-addHTTP 200mcp "$ERIN" "$(call math_alpha-multiply)"thenmcp "$ERIN" "$(call math_beta-multiply)"6withisError: false, thenError: Tool 'multiply' is not allowed for your key/team on server 'math_beta'. Contact proxy admin for access.curl -s http://127.0.0.1:20505/v1/chat/completions -H "Authorization: Bearer $ERIN" ... -d '{"model":"gpt-4.1-mini",...}'{'model': 'gpt-4.1-mini', 'content': 'pong'}HTTP 200 (the model scope check reads the same nested claim)realm_access.roles: [offline_access]but literalscope: litellm.mcp.alpha: server list[],tools: [],tools/call math_alpha-addreturnsError: User not allowed to call this tool.(the literal claim is ignored once a path is configured)realm_accessclaim at all, literalscope: litellm.mcp.alpha:tools: [], and the chat completion returns HTTP 403The requested model 'gpt-4.1-mini' is not available for this API keyrealm_access.rolesis an object:/mcp/returns HTTP 401authentication_requiredrealm_access.roles: "openid litellm.mcp.beta_add"(space separated string):tools: ['math_beta-add'],tools/call math_beta-addreturns5keys_total|0,user_rows_with_teams|0,user_rows_with_object_permission|0for erin, fred, gina, ivyCase 7: key plus scope on the same server, both directions, driven over HTTP with a mapped key (9ed18c3)
Same config plus
virtual_key_claim_field: suband alitellm.mcp.betamapping withmcp_servers: ["math_beta"]. Two keys are issued and mapped to JWT subjects, so a JWT caller carries a real key object permissioncurl -s http://127.0.0.1:20505/key/generate -H "Authorization: Bearer sk-1234" -d '{"object_permission":{"mcp_servers":["math_beta"]}}'(K1, whole server) and the same with"mcp_tool_permissions":{"math_beta":["multiply"]}(K2), thenPOST /jwt/key/mapping/newwith{"jwt_claim_name":"sub","jwt_claim_value":"kim...","key":K1}andleo...to K2is_active: True, andGET /jwt/key/mapping/listreturns both subjectsscope: litellm.mcp.beta_add:mcp "$KIM" "$TL"returnsmath_beta-add,math_beta-multiply;tools/call math_beta-multiplyreturns6(key whole-server grant is not narrowed by the scope allowlist)tools/liststill returns both beta tools[multiply]) withscope: litellm.mcp.beta:tools/listreturns both beta tools andtools/call math_beta-addreturns5(scope whole-server grant is not narrowed by the key allowlist)scope: litellm.mcp.beta_add:tools/listreturns both beta tools (two allowlists union)tools/listreturns onlymath_beta-multiply, andtools/call math_beta-addreturnsError: Tool 'add' is not allowed for your key/team on server 'math_beta'. Contact proxy admin for access.scope: litellm.mcp.beta_addcallingmath_alpha-add:Error: User not allowed to call this tool.3 validation errors for LiteLLM_JWTAuth ... Extra inputs are not permitted), so there is no Before for this case beyond case 1Extra legs
Scope mappings are config only, with no Admin UI page, so the HTTP transcript above is the complete user-facing proof. These legs run on the After tree only because they need the new fields. Legs 3 and 5 were rerun at
9ed18c3cb0with the same outcomes; legs 1, 2 and 4 were last run at766fd564b3and the merge did not touch the code they exercise, but they were not rerun on this tipmcp_access_groups: ["ops-tools"]on alitellm.mcp.opsmapping withmath_betataggedops-tools.tools/listreturnsmath_beta-add,math_beta-multiply;tools/call math_beta-multiplyreturns6;tools/call math_alpha-addreturnsError: User not allowed to call this tool.{"scope":5}returns HTTP 401 at the auth layer;"", a 5000 char scope,litellm.mcp.alpha%20litellm.mcp.beta_add, andLITELLM.MCP.ALPHAeach returntools:[];["litellm.mcp.alpha"](list form) and a duplicated scope return the alpha tools onlyteam_id_jwt_fieldset, teamlitfix-team-betagrantsmath_betawith no tool restriction): a member with no scope sees both beta tools; a member withlitellm.mcp.beta_addsees onlymath_beta-addandmath_beta-multiplyis refused; a member withlitellm.mcp.alphagetstools:[]andmath_alpha-addis refused; a member of a team that grantsmath_alphakeeps both alpha tools; chat completion returnspongALTER DATABASE ... CONNECTION LIMIT 0plus backend termination): direct server scope, tool scope, access group scope, and a brand new subject all keep exactly their scope's tools, nothing wider, and the same results return after the limit is liftedlitellm.mcp.beta(mcp_servers: ["math_beta"]) andlitellm.mcp.beta_addlistsmath_beta-addandmath_beta-multiplyandtools/call math_beta-multiplyreturns6, while a token withlitellm.mcp.beta_addalone still sees onlyaddand gets theTool 'multiply' is not allowedrefusalBoth key plus scope directions are driven over HTTP in case 7 via JWT to key mappings, and with and without a team ceiling by the regression tests in
test_user_api_key_auth_mcp.py::TestJwtScopeMcpGrants. Before the fix the first direction returned["add"]and the second["multiply"]instead of the unrestricted server. A key that reaches the server through a unified access group (access_group_ids) or a tag-stylemcp_access_groupsentry is treated as the same whole-server grant, with its own regression tests, and the access group lookup only runs when the key's direct grants do not already name the serverLive regression check, base eda1fab vs tip 9ed18c3
Same config without the new fields (
team_id_jwt_fieldset,scope_mappingswith models only), same scenario order, both trees on real Postgres and real upstreams, outputs normalized to sorted tool names plus status and diffed. The diff has two lines: the build marker, and the malformed{"scope":5}chat error, which now readsUnmapped scope type at 'scope' - <class 'int'>instead ofUnmapped scope type - <class 'int'>(same HTTP 401, the message names the configured claim path). Cases covered: team member via JWTteam_idclaim (server list,tools/list,tools/call, chat completionpong), master keytools/list, team member refused on a server the team does not grant, unknownteam_idclaim, hostile scopes (5, list form, empty, space separated, 5000 chars) on both MCP and chat, and no Authorization header. The slow upstream and Postgres refusing connection legs were last run at766fd564b3against basebc6b540205and were not rerun on this tipteam_idclaim: server list,tools/list,tools/call, chat completion (pong)tools/list, team member refused on a server the team does not grant, unknownteam_idclaim returns HTTP 404Team doesn't exist in db{"scope":5}HTTP 401 on both MCP and chat, list form scope accepted, empty scope refused on chat with HTTP 403 and unchanged on MCP, 5000 char scope, no Authorization header HTTP 401SIGSTOPon themath_betaupstream): master keytools/listreturns alpha tools withmath_betamarked"status":"timeout"after 30s on both trees, team member listing and calls stay at 0.1s,tools/call math_beta-addhits the 45s client timeout identically, and both recover afterSIGCONTtools/listx3, master keytools/list, and both after restore, identical on both treesDependent paths of the changed symbols:
ScopeMappingis consumed only byLiteLLM_JWTAuth.scope_mappingsandJWTAuthManager.check_scope_based_access(verified live via the chat control on both trees).get_mcp_server_access,get_allowed_mcp_servers, andget_allowed_tools_for_serverare reached from/v1/mcp/server(verified live),/mcp/tools/listandtools/call(verified live), and from paths that share the same resolver but were not driven live here: the Responses API MCP handler (tools: [{"type": "mcp"}]), MCP tool search, the MCP OAuth discovery endpoints, the MCP management endpoints, and the Admin UI MCP pages. Those are covered through the unit tests on the shared resolver only. Dashboard, SDK, DB columns, and docs do not reference the new fields, so there is nothing to update thereLocal gates at 9ed18c3 on the SDK 2 lock (
uv sync --inexact --frozen --extra proxy --group proxy-dev --group e2e-dev,mcp==2.2.0):make lintexit 0 (ruff prod and tests, format, strict-rule, type-discipline, test-quality and basedpyright budgets all OK against origin/main, e2e basedpyright 0 errors, circular import and import safety clean). Tests in separate processes: the mapped MCP auth test file plus the JWT handler tests, 652 passed; MCP server, REST endpoint, toolset scope and JWT enforcement tests, 478 passed, 4 skipped; JWT admission and key mapping tests fromtest_user_api_key_auth.py, 43 passed. Line and branch coverage from those three runs combined: 76 of 76 changed executable lines hit (44 inuser_api_key_auth_mcp.py, 24 inhandle_jwt.py, 6 in_types.py, 2 inuser_api_key_auth.py); every new helper has full branch coverage (get_scopes6/6,mcp_grants_from_claims2/2,_key_tool_grant_for_server4/4,_merge_additive_tool_grants2/2); the partial branches left inget_mcp_server_access,get_allowed_tools_for_serverandauthorize_jwtare pre-existing paths this PR does not touch. Targeted mutation run at 766fd56 overget_scopes,mcp_grants_from_claims, the key/scope grant helpers, the merge, and the admission wiring: 30 of 30 mutants killed; the merge changed none of those linesReview status at 9ed18c3: CI 96 passed, 0 failed, 1 skipped, codecov/patch passed. Greptile 5/5 with last reviewed commit 9ed18c3. Bugbot: no new issues for 9ed18c3. CodeQL passed, 0 open threads. Veria AI check run on 9ed18c3 completed with
No security issues found. All 6 review threads resolved, none open. An independent verifier run on this SHA is still in progress and is not claimed hereType
🆕 New Feature
Caveats (if any)
Severe
math_betawith no tool restriction, scope grantsmath_beta: ["add"], caller sees onlyaddmcp_servers: ["math_beta"]instead to keep the full server, documented in the precedence section of the docs PRscope_jwt_fieldmoves the claim for models andadmin_jwt_scopetoo, not only MCPscopeclaim is ignored entirely (case 6, fred and gina)scope_mappingsconsumer. Default staysscope, so existing configs do not changeMedium
scope_mappingsneeds a proxy restart, same as today for models and routesLow
eda1faba14(CI, price sync, a guardrail revert); none touch the files this PR changes, so the branch was not re-mergedtools: [{"type": "mcp"}]prefetch path and Admin UI MCP pages were not driven live, unit tests onlyFinal Attestation
ran /live-pr-risk and found no regressions/backward incompatible risks
Note
Medium Risk
Changes authorization for MCP and JWT scope handling; misconfigured scope mappings or
scope_jwt_fieldcould widen or narrow access, though team ceilings and fail-closed malformed claims limit blast radius.Overview
Extends JWT
scope_mappingsso OIDC scopes can grant MCP servers, access groups, and per-server tool allowlists without a virtual key or team row. At JWT admission, matching scopes are resolved intojwt_scope_mcp_grantsonUserAPIKeyAuthand folded into MCP server/tool checks alongside existing key and team permissions.Adds
scope_jwt_field(defaultscope, dot notation e.g.realm_access.roles) so the same claim drives model scope checks, admin scope, and the new MCP grants. Scope and key grants are additive (whole-server grants keep all tools; tool lists union), while team/org ceilings still cap the result; malformed or missing scope claims grant nothing.Includes broad unit coverage for JWT resolution, custom claim paths, and MCP admission precedence (including
no_mcp_serversopt-out).Reviewed by Cursor Bugbot for commit 9ed18c3. Bugbot is set up for automated code reviews on this repo. Configure here.
Link to Devin session: https://app.devin.ai/sessions/5b2fb9a6244045c2996cd6a3fd8d82ca
Open in Devin Desktop: https://app.devin.ai/desktop/session/5b2fb9a6244045c2996cd6a3fd8d82ca?variant=devin
Requested by: @joshua-berri