Repository navigation
fix(mcp): recover the tool-name prefix boundary from registered prefixes - #34673
Conversation
Greptile SummaryThis PR centralizes MCP tool-prefix recovery and policy identity matching.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains in the fixes associated with the prior review threads.
|
| Filename | Overview |
|---|---|
| litellm/proxy/_experimental/mcp_server/utils.py | Centralizes known-prefix matching, accepted tool spellings, and registration-compatible OpenAPI policy normalization; the previously reported identity-collision fixes are present. |
| litellm/proxy/_experimental/mcp_server/mcp_server_manager.py | Applies the shared naming primitives across routing, server policy enforcement, parameter restrictions, OpenAPI registration, and registry lookup. |
| litellm/proxy/_experimental/mcp_server/server.py | Aligns tool discovery filtering with the same server-aware identity matcher used during dispatch. |
| litellm/proxy/_experimental/mcp_server/rest_endpoints.py | Aligns REST discovery behavior with shared key/team and server-level filtering. |
| litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py | Centralizes exact bare-name key and team permission decisions so listing and calls use the same predicate. |
| tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py | Adds focused coverage for discovery/dispatch agreement, prefix-leading native names, case-distinct identities, and policy behavior. |
| tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py | Covers OpenAPI policy normalization, distinct operation identities, and registry-key agreement. |
Reviews (8): Last reviewed commit: "fix(mcp): make the operationId to tool-n..." | Re-trigger Greptile
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
2806c76 to
b818e95
Compare
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 3 · PR risk: 0/10 |
1f3c342 to
bb7eabd
Compare
1 similar comment
|
bugbot run |
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 bb7eabde18851dc3edf35bb9179664217f84af8e. Configure here.
bb7eabd to
35006e5
Compare
|
bugbot run |
|
QA of key/team tool grants ( Both grant shapes are stored as written and now work end to end on this branch, and both are broken on Key with A toolset created through One regression this branch introduced, now fixed in Fail-closed, so nothing unauthorized ran, but it is discovery disagreeing with dispatch on the key-level path, which is the defect this PR exists to remove. The fix routes REST listing through
|
|
Pushed Both findings were the same defect wearing two faces. Four sites ask "which configured entry names this tool on this server": the allow list, the deny list,
Picking one case rule surfaced a third fail-open that shipped code still has, and run 5 in the body reproduces it live: discovery lowercases before comparing, deliberately, for camelCase OpenAPI operationIds, while enforcement compares exactly. A On size, executable lines over the merge-base go from +9 to +4, and all four are the new function. This sits on top of |
df4ed1b to
e489574
Compare
|
bugbot run |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit c4312fd. Configure here.
The gateway publishes a tool as `<server prefix><separator><tool name>` and has to recover that boundary on the way back in, to compare a called name against a toolset or allow/deny list and to rebuild the native name sent upstream. Several sites recovered it by cutting at the FIRST separator and others reconstructed it by hand from `MCPServer.name` with a literal `-`, so both disagreed with the prefix the server actually publishes `get_server_prefix` publishes short_prefix, then alias, then server_name, then server_id; it never reads `name`. A server with no alias therefore publishes its hyphen-filled UUID `server_id` as the prefix, and cutting at the first separator leaves most of the UUID glued to the tool name. Every comparison against the stored `(server_id, tool_name)` toolset row then misses: an allowlist denies a tool the list endpoint just advertised, and a disallowed entry stops blocking, which fails open Recover the boundary in one place instead. `match_known_server_prefix` matches a name against the server's registered prefixes, longest first so a prefix that itself contains the separator beats a shorter prefix that is merely its leading segment, and returns None when the name carries none of them. `strip_known_server_prefix` and `is_tool_name_prefixed` both delegate to it, and the sites that receive a wire name call the owner rather than re-deriving the boundary. `split_server_prefix_from_name` stays for the routing pair it was written for, with a docstring saying so The server-level permission checks are the other half. They run after the boundary is already resolved, so their input is bare and the correction there is to derive the wire form rather than strip it back out; stripping a stored entry a second time cuts a boundary the caller already consumed, which breaks a native name that itself opens with the server prefix. Deriving from `get_server_prefix` alone is not enough either, because routing resolves an inbound name against every prefix from `iter_known_server_prefixes`, so enforcement keyed to the published spelling answers for fewer names than are reachable. Turning `LITELLM_USE_SHORT_MCP_TOOL_PREFIX` on republishes every tool under the short ID while an entry stored under the alias stays routable and silently stops being enforced, which is a fail-open on a config nobody edited. `iter_known_tool_name_spellings` yields the bare name plus the wire form under each accepted prefix, and the allow list, the deny list, `allowed_params` and the routing map that `_create_prefixed_tools` builds now all key off that one function, so the set of names enforcement honors and the set routing accepts cannot drift apart `_tool_name_matches` takes the server as a required argument, so a future caller cannot silently fall back to guessing, and it matches against that same spelling set, so `tools/list` hides exactly what dispatch refuses. Answering for fewer spellings in the filter than enforcement honors leaves a blocked tool advertised, which is how the alias-form entry above stayed listed even once the call was refused. The OpenAPI registry lookup builds its key the same way registration does, via `add_server_prefix_to_name` and `get_server_prefix`, because registration used exactly one key; a server whose `name` differs from its published prefix stops missing its own tools
The REST listing filter matched key/team grants through _tool_name_matches, which after the prefix-boundary change answers for every spelling routing accepts. Key-level entries in mcp_tool_permissions and toolset rows name a tool on one server and dispatch compares them bare, so a wire-form entry advertised a tool that tools/call then refused. REST listing now goes through filter_tools_by_key_team_permissions, the same function the MCP list path uses. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… matcher The allow list, the deny list, allowed_params and the discovery filter all ask the same question, "which configured entry names this tool on this server", and each answered it in its own idiom: any() over a spelling tuple, all() over the same tuple negated, a next() that pulled a value out of a dict, and a lowercased set membership. Two review findings on this PR were symptoms of that duplication. Deriving the operands differently at one site produced the over-strip; needing a value rather than a boolean at another produced a truthiness test that read an explicitly empty allowed_params list as "nothing configured" and allowed every parameter. match_known_tool_name returns the matching entry or None, and all four sites read it, so no site can test a container's values to decide membership and the empty-list fail-open is no longer representable. Matching is case-insensitive everywhere, which closes the last divergence between discovery and dispatch: a case-variant disallowed_tools entry used to hide a tool from tools/list while tools/call still executed it. Executable lines over the merge-base drop from +9 to +4, all of it the new owner; mcp_server_manager.py loses 12 lines and the discovery filter loses 17.
Bugbot flagged REST listing advertising key/team grants that tools/call then refuses. The listing side was fixed by routing through filter_tools_by_key_team_permissions, but the two paths still answered the question with separate implementations that only happened to agree: listing stripped the known prefix and compared bare, dispatch compared whatever name it was handed, and each carried its own reading of None and of an empty list. Changing either side silently diverges from the other, which is how this defect appeared in the first place. MCPRequestHandler.tool_is_granted owns the whole decision, and both is_tool_allowed_for_server and filter_tools_by_key_team_permissions read it. None still means no tool-level restriction and an empty list still grants nothing, now stated once. Grants are stored bare by every writer, so matching stays exact against the bare name, deliberately unlike the server-level lists, which honor every spelling routing accepts. test_key_team_listing_and_dispatch_agree drives both production paths over one matrix. It asserts the expected verdict as well as the agreement, because two paths reading one predicate makes equality alone tautological: a wrong predicate keeps them consistent and the agreement assertion alone survived two mutants that the verdict assertion kills.
… does Greptile flagged that match_known_tool_name case-folded both the configured entry and the derived spellings. Routing keeps two tools whose names differ only in case as two tools, so folding merged identities the dispatcher separates: on a server exposing getPet and getpet, an allowlist naming getPet also granted getpet, and a blocklist naming getPet also denied getpet. That is unauthorized execution on one arm and the wrong tool denied on the other. Matching is now exact, which is what identity means here. The case leniency it replaces was never typo tolerance; _register_openapi_tools rewrites every operationId through sanitize_openapi_tool_name, so an allowed_tools entry holding the spec's own spelling never equals the registered name. That link is recovered by replaying the same rewrite, and only on servers that carry a spec_path, which is how the rest of the manager already recognizes an OpenAPI server. Every name that rewrite produces is lowercased, so no two tools on such a server can differ only in case and the fold cannot merge anything. Native servers get no folding at all. test_case_folding_applies_to_openapi_ servers_and_not_to_native_ones pins both halves, and two tests pin that a policy naming one tool leaves its case-variant sibling alone. Dropping the spec_path guard, dropping the fold, and forcing the fold path are all killed. The two pre-existing case-insensitivity tests describe OpenAPI servers in their own docstrings but built fixtures without a spec_path, a shape production never produces for one; they now set it.
Greptile found that the OpenAPI fallback added a commit ago collapsed operation
IDs that registration keeps apart: foo/bar and foo.bar register as two tools but
sanitize_openapi_tool_name rewrites both to foo_bar, so a policy naming either
also decided the other.
The cause was two owners for one map, and picking the wrong one. Registration
names an operationId inline at _register_openapi_tools with
operation_id.replace(" ", "_").lower(), which keeps / and . ; the separate
sanitize_openapi_tool_name replaces every character outside [a-zA-Z0-9_-] and
belongs to register_tools_from_openapi, which has no production caller. Nothing
made the matcher use the one that actually registers, so it used the lookalike.
That inline expression is now openapi_tool_name in utils, and both registration
and the matcher call it. Replaying the registering function is the whole safety
argument, and it is structural rather than a claim: two operationIds that
register as two tools normalize to two names here by construction, because this
is the map that registered them. A coarser lookalike cannot be substituted
without a test failing.
The matcher also loses its exact-then-fallback split. The transform is identity
on native servers and idempotent on already-registered names, so normalizing
both sides is exact matching where no OpenAPI spec is involved. Executable lines
drop by three this round; the branch is +5 over the merge-base for four shared
owners that removed duplication at six call sites.
c4312fd to
179ebdb
Compare

TLDR
Problem this solves:
tools/listadvertises gets refused ontools/calldisallowed_toolsentry hides the tool from discovery and still lets it executeserver_id, and a UUID contains that separatorHow it solves it:
allowed_params, the routing map and the discovery filter all read it, so enforcement honors exactly the names that are reachable_tool_name_matchesnow requires the server, so the guess is structurally unavailable to a future caller, and discovery hides exactly what dispatch refusesRelevant issues
allowed_toolsentry matched nothing, so the tool neither listed nor calleddisallowed_toolsentry written in the wire form removed the tool fromtools/listbut left it fully callable; that one is live-reproduced below against shipped codeLinear ticket
LIT-3419, deliberately without a closing keyword. #34559 already shipped that ticket's toolset-side fix, and the reporter's effective
MCP_TOOL_PREFIX_SEPARATORis still unconfirmed, so a human should decide when the ticket closesPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)CI is green.
osv-scanwas red on earlier pushes of this branch, and was red onlitellm_internal_stagingitself at59f2bd7881,2c6c8d8b30andd19787e816; rebasing onto current staging picked up the upstream fix and it now passes, so the exception this section used to carry no longer appliesDelays 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
Live proxy on
127.0.0.1:4111against a real Postgres and the real public DeepWiki MCP server athttps://mcp.deepwiki.com/mcp, which exposes three tools (ask_question,read_wiki_contents,read_wiki_structure). Two independent runs follow: the first is the listed-then-refused defect, the second is the fail-open. Both compare this branch against its own base with nothing else changedRun 1: a tool that lists and then refuses
The server was created through the public API with
server_nameandaliasboth left null, which is what a config-driven or API-driven deployment produces and what makes the prefix fall back to theserver_id. A virtual key scoped to that server does the probingcurl -sS http://127.0.0.1:4111/v1/mcp/server -H "Authorization: Bearer $MASTER_KEY"[ { "server_id": "3c6f6617-d23c-4f48-bfb0-f205e3b27bab", "alias": null, "server_name": null, "url": "https://mcp.deepwiki.com/mcp", "allowed_tools": [ "read_wiki_contents" ] } ]The probe script, unchanged between the two runs:
Before, with the four production files at
215f05588d, this PR's base:Step 1 prints nothing: the allowlist granted
read_wiki_contents, the filter matched zero tools, and the client is offered none of the three. Step 2 shows why, in the leaked named23c-4f48-bfb0-f205e3b27bab-read_wiki_contents; the first-of the UUID was taken for the prefix boundary, the first UUID segment was discarded as the server name, and the rest travelled upstream as if it were the tool. Step 3 is the same mistake surfacing as an authorization refusal on a name the caller supplied verbatimAfter, at
b818e95400:Exactly one of the three upstream tools is offered, it is the one the allowlist grants, and the name the client is handed works on both the MCP and the REST call path. The negative control still refuses, and the refusal now names
ask_questionrather than a mangled fragment, which is the same boundary resolving correctly on the denial pathBecause an admin reading their client sees the prefixed name, the same run was repeated with
allowed_toolsset to the wire spelling instead of the bare one, changing nothing else:Both spellings grant the same one tool, and the negative control still refuses under the wire-form entry, so accepting the second spelling did not widen the grant
Run 2: the fail-open, reproduced on shipped code
disallowed_toolshas no column inschema.prismaand no UI writer; its only sources areserver_config.get("disallowed_tools")in the config loader and a carry-forwardgetattr. It is therefore hand-authored YAML, which is exactly where the wire spelling is most likely, since that is the spelling the admin sees in their client. This run uses a config-defined server underLITELLM_USE_SHORT_MCP_TOOL_PREFIX=true, where the published prefix is the computed short prefix and so can never equalserver.nameeiGis the prefix the proxy itself published for that server, read out of a priortools/listrather than guessed. The probe lists the server's tools and then calls the banned one:The blocklist works on the list path and does nothing on the call path.
read_wiki_contentsis hidden from discovery and returns real upstream content to anyone who names it, which is a ban that only holds against clients that do not guess. Same config, same request, this branch:Run 3: discovery and dispatch agreeing on one entry
Same config server and same probe as run 2, with the blocklist entry written in the alias form the admin typed into their own YAML rather than the short prefix the proxy computed at boot. Both spellings name the same tool on the same server:
The ban holds on the call path here, through the
f"{server.name}-{tool_name}"arm, and the list path advertises the banned tool anyway because it recovered the boundary the other way. A client discoverseiG-read_wiki_contents, calls the exact name it was handed, and is refused, which is run 1's defect landing on a denial instead of a grant. Same config, this branch:The two runs together are why the fix is the whole spelling set rather than one derived spelling. Run 2's entry is the published form and run 3's is the alias form; shipped code gets each one half right and in opposite halves, and only enforcement that honors every spelling routing accepts gets both cells right on both paths
Run 4: an explicitly empty parameter allowlist
This one is a regression an earlier commit on this branch introduced and review caught, rather than shipped behavior, and it is reported here because its fix is in the diff.
allowed_paramshas exactly one writer,server_config.get("allowed_params", None)in the config loader, and one reader, so{tool: []}can only be an administrator saying that tool accepts no parametersBase refuses it, because
.get(a) or .get(b)yields the second operand when the first is falsy and both lookups find the same empty list:The rewritten lookup tested the value instead of the key, so an empty list read as nothing configured and the call reached the real upstream:
This branch restores the refusal, and the negative control in the same session shows the gate is filtering parameters rather than blocking the tool, since an argument-free call passes it and reaches upstream's own validation:
Run 5: a case-variant deny entry, hidden from discovery but still callable
Collapsing the four sites onto one matcher forced a single case rule, and getting it wrong first is what made the right answer legible. Discovery lowercases before comparing; enforcement compares exactly. So on shipped code an entry differing from the published name only in case is honored by
tools/listand ignored bytools/call. Folding case everywhere makes the two agree, and review caught that it buys the agreement at too high a price: routing dispatches two names differing only in case as two tools, so a folded matcher lets one policy decide bothThe banned tool is absent from the listing and returns the full wiki page when called by the exact name the proxy publishes. An administrator reading
tools/listsees the ban working. Same config, this branch:The branch above folded case on every server, and that is the version this run was first written against. On a server exposing both
getPetandgetpetit grantedgetpetfrom an allowlist naming onlygetPet, and deniedgetpetfrom a blocklist naming onlygetPet; unauthorized execution on one arm, the wrong tool denied on the other. Driven through the real functions:Matching is exact now, and the same probe reads
getpet allowed=Falseunder the allowlist andgetpet allowed=Trueunder the blocklist. Live, with a deny entry that names no tool that exists, the branch that folded case hid the real tool fromtools/listand refused the call, while this one lists it and calls it:What the fold was actually for survives, in the one place it is provably safe, and getting that place right took a second correction.
_register_openapi_toolsnames an operationId inline withoperation_id.replace(" ", "_").lower(), which preserves/and.; the similarly namedsanitize_openapi_tool_namereplaces every character outside[a-zA-Z0-9_-]and belongs toregister_tools_from_openapi, which has no production caller. Replaying the second while gating onspec_path, which registers through the first, collapsedfoo/barandfoo.baronto one policy identitySo the map has one owner now. That inline expression is
openapi_tool_nameinutils.py, and registration and the matcher both call it, which turns the safety argument into a property rather than a claim: two operationIds that register as two tools normalize to two names here by construction, because this is the map that registered themtest_case_folding_applies_to_openapi_servers_and_not_to_native_onespins both halves,test_an_entry_does_not_decide_an_operation_id_registration_keeps_separatepins the collision, and two tests pin that a policy naming one tool leaves its case-variant sibling aloneSo the shipped
tools/listandtools/calldisagreement in the transcript at the top of this run is still closed, just from the other side: the typo'd entry now names nothing on either path instead of half-banning a toolType
🐛 Bug Fix
Changes
The name a client sees on the wire is
{server_prefix}{MCP_TOOL_PREFIX_SEPARATOR}{tool_name}, andget_server_prefixtakes that prefix fromshort_prefix, elsealias, elseserver_name, elseserver_id. Bothserver_nameandaliasare nullable inschema.prisma, so a server created with neither is prefixed by itsserver_id, and a UUID contains the default separator-. From there, any code that recovers the tool name by cutting at the first separator disagrees with any code that matches against the prefixes the server actually registered. That disagreement is the bug, and it is not limited to UUIDs: a hyphenated alias, an enabledshort_prefix, or a deployment that overrides the separator each hit it a different wayRecovering the boundary is now owned by one function.
match_known_server_prefix(name, known_prefixes)inutils.pyreturns(matched_prefix, bare_name), orNonewhen the name carries none of them. Candidates are normalized and tried longest first, so a prefix that itself contains the separator wins over a shorter prefix that is merely its leading segment.strip_known_server_prefixand the known-prefix branch ofis_tool_name_prefixeddelegate to it instead of each re-deriving the boundary, and_resolve_mcp_server_for_tool_callcalls it directly in place of the split-then-normalize-then-look-up sequence it hand-rolledsplit_server_prefix_from_namestays, and stays used for routing, because the two halves it returns reassemble into the input exactly; that property is what makes it safe there. Its docstring now says that reading one half on its own is a guess, and points at the ownerThe list path and the call path stopped disagreeing:
execute_mcp_tooltook the routing pair from the blunt split and repaired only the server half, sooriginal_tool_namestayed mangled for the whole rest of the request. It now recovers the tool name from the resolved server, on both the resolved-by-prefix and the routed-by-server_idbranch_tool_name_matches, used by both the MCP list filter and the REST list filter, took no server at all and so could only guess. It now takes the server as a required parameter, which is the structural half of the fix: a future caller cannot reintroduce the guess by omitting it. With the server in hand it reads the same spelling owner the permission checks read, so the two paths cannot answer for different sets of namesapply_tool_overridesand thetool_name_to_mcp_server_name_mappingbuild both keyed off the blunt splitThe three comparison sites needed the opposite correction, and this is the part the first review round got wrong. By the time
check_allowed_or_banned_tools,validate_allowed_params, and_call_openapi_tool_handlerrun, the tool name is already bare. Every caller resolves the boundary before dispatch:server.pypassesoriginal_tool_nameon both entry points, the Responses handler passes asanitized_tool_nameit produced withstrip_known_server_prefix, andcall_toolhands that same value to the upstream client verbatim, which only works because it carries no prefix. Stripping inside these three functions is therefore a second strip. On an ordinary name it is a no-op, which is why it looked harmless; on a native name that itself opens with the server prefix it cuts a boundary the caller already consumed, while a stored wire-form entry gets only one strip, so the two operands are no longer comparable. These sites now derive their comparison operands instead of cutting them back out of anythingWhich operands to derive is the part the second review round corrected, and it is the real invariant here.
get_server_prefixpublishes one prefix, but routing accepts several:iter_known_server_prefixesyieldsshort_prefix, the computed short prefix,alias,server_nameandserver_id, and an inbound name carrying any of them resolves to the same tool on the same server. Deriving only the published spelling therefore answers for fewer names than are reachable, and ondisallowed_toolsthat difference fails open. The new owner isiter_known_tool_name_spellings(tool_name, server)inutils.py, which yields the bare name and then its wire spelling under each accepted prefix.check_allowed_or_banned_tools,validate_allowed_params, thetool_name_to_mcp_server_name_mappingbuild and_tool_name_matchesall read it, so the routing map, both permission lists and the discovery filter agree on one set by construction. These are spellings of one tool on one server rather than candidate identities, so honoring all of them normalizes the entry rather than widening a grant, andtest_every_spelling_routing_registers_is_also_enforceddrives_create_prefixed_toolsand asserts every key routing registers is a key enforcement can refuseThat correction is also what closes the fail-open in run 2.
check_allowed_or_banned_toolspreviously built its second operand asf"{server.name}-{tool_name}", which hardcodes the separator and uses a field the prefix chain never reads. On a server with ashort_prefix, or under an overridden separator, that string can never equal the wire name the proxy published, so a wire-formdisallowed_toolsentry matched nothing._call_openapi_tool_handlerhad the same expression as its registry key while registration builds the key withadd_server_prefix_to_name(..., get_server_prefix(server)), so lookup and registration disagreed under exactly those conditionsEvery spelling routing accepts stays accepted, which is a deliberate call rather than the default. Rule of thumb would be to delete a tolerance for a form nothing writes, so I audited the writers.
allowed_toolsreaches the manager from config verbatim, from the create and update API bodies verbatim, and from the DB column verbatim;disallowed_toolshas no DB column and no UI writer at all, so its only real source is hand-written YAML. In every case the writer is or can be a human who is reading prefixed names out of their client, shipped code honors the prefixed form today, and dropping it fromdisallowed_toolswould make a currently-blocked tool callable, which is a fail-open introduced by a bug fix. Deleting the second spelling is a deprecation with its own migration note, not something to slip in hereFour sites elsewhere read one half of the blunt split and are deliberately left alone, because fixing them is a different change rather than a smaller one.
litellm_proxy_mcp_handler.py:327and:363have no server object in scope, since the Responses API path carries a flat set of names from the request body; threading one in is a signature change up that chain.mcp_end_user_permission.py:228mixes server IDs and server names in a single list, which is its own normalization problem.server.py:3110isprompts/get, which matches on.nameonly.user_api_key_auth_mcp.py:1155splits a header name, not a tool nameOne residual is worth stating plainly, and it is unchanged from shipped behavior rather than introduced here. Because more than one spelling is accepted, a single entry string can name two different tools on the same server: on a server prefixed
foo, the entryfoo-barmatches the native toolfoo-barby its bare name and the native toolbarby its wire name. No amount of prefix matching settles that from the string alone, and shipped code has the same property through itsf"{server.name}-{tool_name}"arm. What changes here is that every site resolves it the same way, instead of the list path and the call path resolving it differently, which is what produced a tool that lists and then refusesOn size, the four permission sites now share one matcher, so the diff deletes more than it adds where the duplication was. Counting executable lines only, by parsing each file and dropping docstrings, comments and blanks, the production tree goes from 8772 lines at the merge-base to 8776, a net of four, and all four are
match_known_tool_nameitself.mcp_server_manager.pydrops twelve lines,server.pygains one,rest_endpoints.pyis unchanged, andutils.pyabsorbs fifteen. The discovery filter alone goes from twenty-four lines to sevenTests are regression-shaped and mutation-checked. Eight mutants target the unified matcher and all eight are killed. On the matcher itself: narrowing it to the bare name fails twenty-two tests, making the blocklist arm always allow fails eleven, and reintroducing a truthiness test in the
allowed_paramslookup fails exactly one,test_an_explicitly_empty_allowed_params_list_refuses_every_parameter, which is the mutant run 4 reproduces live. On the case rule: dropping thespec_pathguard so the fold applies everywhere fails four, dropping the OpenAPI fold entirely fails three, and forcing the fold path by never matching exactly fails thirty-two. On the key/team predicate: restoring every-spelling matching on the listing side fails two, dropping the rule thatNonemeans no restriction fails one, and always granting fails four. That last group is whytest_key_team_listing_and_dispatch_agreeasserts the expected verdict and not only that the two paths agree; with both paths reading one predicate, equality alone is tautological, and the first version of that test let two of those three mutants live. Nine further mutants target the prefix design underneath and all nine are killed: narrowing the owner to the published prefix alone fails five tests; dropping the bare name from the owner fails three; registering only the bare name in the routing map fails three; comparing only the bare name in the blocklist fails eight; the same narrowing inallowed_paramsfails three; narrowing the discovery filter to the published prefix fails two; dropping the bare name from the filter fails seven; and restoring the truthiness test in theallowed_paramslookup failstest_an_explicitly_empty_allowed_params_list_refuses_every_parameter, which is the mutant run 4 reproduces live. Each mutation was undone with an edit rather thangit checkout --, so the fix under test was never at risk. Two mutants from the earlier round still apply and still die: restoring the double strip in the registry key failstest_dispatch_keeps_a_native_name_that_opens_with_the_prefix, and restoring the originalf"{server.name}-{tool_name}"fails the rows named for the blocklist bypass.TestMatchKnownServerPrefixpins the owner's contract, including that the longest candidate beats a leading segment, that the separator must follow the prefix, that candidates are normalized before matching, and that an empty candidate never matches a bare leading separator.TestServerToolListsHonorThePrefixBoundarydrives both spellings of both list arms throughpre_call_tool_check, under the default separator, under an overridden one, and under short-prefix mode.TestOpenAPIRegistryKeyMatchesRegistrationexists because a mutant on the registry key survived the first round: every pre-existing test on that path patches_call_openapi_tool_handlerout, so nothing pinned the agreement between lookup and registrationAlongside the live runs, two differential probes drive server shapes through the real permission function on both list arms and in both prefix modes. The first derives each entry spelling from
get_server_prefix, so it only ever covers the currently published name; this branch is 16 of 16 there in both modes, against 16 of 16 default and 8 of 16 short-prefix on the base, where four of the eight wrong rows are denials that returned allow. That probe was too narrow, which is what the second review round caught: a probe built from the published prefix cannot see an entry written with an accepted-but-unpublished one. The second probe enumerates entry spellings over every prefixiter_known_server_prefixesaccepts, 48 rows per mode, and that is the matrix that matches the invariant. This branch is 48 of 48 in default mode and 48 of 48 in short-prefix mode; the base is 24 of 48 in both, split evenly between grants that never matched and denials that returned allowTwo test-side notes for the reviewer. Several
MagicMockserver fixtures had drifted into shapes production never produces, where auto-created attributes stood in foralias,short_prefix, and the display-name maps, and a truthy auto-MagicMockfortool_name_to_display_namewas defeating a production early return; those are now pinned toNone. Andtest_execute_mcp_tool_rest_unresolved_prefixed_name_routes_to_requested_serverchanged on purpose: it asserted that a prefix belonging to a different server was stripped before dispatch to the routed server. It now asserts the name travels whole, because that prefix is not a boundary on the routed server, and stripping it is how the routed server's similarly named tool gets invoked instead, which is the confusion thetool_server_mismatch403 exists to prevent. That reading follows the routing principle in #30184, whose own commits include allowing hyphenated upstream tool names when the RESTserver_idis authoritativeOne red that is not mine, flagged rather than absorbed: two cases in
test_mcp_env_vars.pyfail when the MCP test directory runs in file order under-p no:randomly. They pass alone, they pass alongside the four files this PR touches, and they still fail with all four of those files ignored, so the order dependence predates the branch; none of the tests added here writeos.environdirectlyOne change deserves a reviewer's eye rather than a claim that it is safe.
validate_allowed_paramsused to fall back toserver.allowed_params.get(split_server_prefix_from_name(tool_name)[0]), and now falls back to the derived wire form. The only key that matched before and does not now is a malformed one equal to the post-first-separator suffix of a real tool name, such aswikiconfigured for a nativeread-wiki, and a miss there meansallowed_params_list is None, which allows all parameters. Nothing writes such a key and it is the blunt-split defect itself rather than a supported spelling, so removing it is the point; it is called out here because it can be misread as swapping which fallback is honored. The same lookup now tests key presence rather than value truthiness, so an explicitly empty allowlist denies every parameter instead of reading as nothing configured; an earlier commit on this branch got that wrong and run 4 is the differentialQA runbook
POST /v1/mcp/serverwithaliasandserver_nameboth omitted, pointing athttps://mcp.deepwiki.com/mcpwithtransport: http, and setallowed_toolsto["read_wiki_contents"]initializeandtools/listoverPOST /mcp/withx-litellm-api-key: Bearer <key>. Expect exactly one tool, named<server_id>-read_wiki_contentstools/calland{"repoName": "BerriAI/litellm"}. Expect wiki content, notTool ... not foundPOST /mcp-rest/tools/callwithserver_idin the body. Expect the same content<server_id>-ask_questionthe same way. Expect a refusal namingask_question, which confirms the fix narrowed correctly instead of just stopping refusalsallowed_toolsto the wire spelling["<server_id>-read_wiki_contents"]and repeat steps 2, 3 and 5. Expect identical results, since an admin copying the name out of their client writes this formdisallowed_toolsset to the wire name the proxy publishes for it, run the proxy withLITELLM_USE_SHORT_MCP_TOOL_PREFIX=true, and call the banned tool. Expect a refusal. Onlitellm_internal_stagingthe same call returns upstream contentFinal Attestation
Note
Medium Risk
Changes authorization and tool-routing behavior across MCP list/call and REST paths; mistakes could fail-open blocklists or break OpenAPI dispatch, though behavior is heavily regression-tested.
Overview
Fixes MCP proxy bugs where tool discovery and
tools/calldisagreed because the code split prefixed names at the first separator instead of using each server’s registered prefixes (notably when the prefix is a UUIDserver_idcontaining-).Prefix handling: Adds
match_known_server_prefix(longest-prefix match) and routesstrip_known_server_prefix, prefixed-tool detection, andexecute_mcp_toolthrough it so the bare tool name sent upstream matches what routing registered.One matcher for policy: Adds
iter_known_tool_name_spellingsandmatch_known_tool_namesoallowed_tools/disallowed_tools,allowed_params, OpenAPI registry lookup, and list filters honor every wire spelling routing accepts (alias, short prefix,server_id, etc.), not onlyf"{server.name}-…". OpenAPI servers normalize via sharedopenapi_tool_name; native tools stay case-exact.Permissions alignment: Introduces
MCPRequestHandler.tool_is_grantedfor bare key/team grants; REST listing usesfilter_tools_by_key_team_permissionslike the MCP path so prefixed grant strings cannot advertise tools that calls reject.Tests: Large regression coverage for UUID prefixes, short-prefix mode, OpenAPI keys, empty
allowed_params, and list vs dispatch parity.Reviewed by Cursor Bugbot for commit c4312fd. Bugbot is set up for automated code reviews on this repo. Configure here.