Skip to content

fix(mcp): recover the tool-name prefix boundary from registered prefixes - #34673

Merged
tin-berri merged 6 commits into
litellm_internal_stagingfrom
litellm_mcp_prefix_boundary
Jul 31, 2026
Merged

tin-berri merged 6 commits into
litellm_internal_stagingfrom
litellm_mcp_prefix_boundary

Conversation

@tin-berri

@tin-berri tin-berri commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A tool that tools/list advertises gets refused on tools/call
  • Worse, on some servers a disallowed_tools entry hides the tool from discovery and still lets it execute
  • The call path recovered the tool-name prefix boundary by cutting at the first separator; the list path matched against the prefixes the server actually registered
  • A server with no alias is prefixed by its server_id, and a UUID contains that separator
  • OpenAPI dispatch built its registry key from a field the prefix chain never reads

How it solves it:

  • One owner recovers the boundary from the server's registered prefixes, longest candidate first
  • A second owner enumerates every spelling routing accepts for one tool, and the permission lists, allowed_params, the routing map and the discovery filter all read it, so enforcement honors exactly the names that are reachable
  • _tool_name_matches now requires the server, so the guess is structurally unavailable to a future caller, and discovery hides exactly what dispatch refuses

Relevant issues

  • Fixes a tool-permission defect on any MCP server whose published prefix contains the tool-name separator: a server-level allowed_tools entry matched nothing, so the tool neither listed nor called
  • Fixes a fail-open on the same class of server, where a disallowed_tools entry written in the wire form removed the tool from tools/list but left it fully callable; that one is live-reproduced below against shipped code
  • Follow-up to fix(mcp): use a toolset row's stored tool name as written #34559, which fixed the toolset side of the same boundary problem and left the server-level lists and the call path untouched

Linear 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_SEPARATOR is still unconfirmed, so a human should decide when the ticket closes

Pre-Submission checklist

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

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • 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)

CI is green. osv-scan was red on earlier pushes of this branch, and was red on litellm_internal_staging itself at 59f2bd7881, 2c6c8d8b30 and d19787e816; rebasing onto current staging picked up the upstream fix and it now passes, so the exception this section used to carry no longer applies

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

Live proxy on 127.0.0.1:4111 against a real Postgres and the real public DeepWiki MCP server at https://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 changed

Run 1: a tool that lists and then refuses

The server was created through the public API with server_name and alias both left null, which is what a config-driven or API-driven deployment produces and what makes the prefix fall back to the server_id. A virtual key scoped to that server does the probing

curl -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:

#!/bin/bash
# usage: capture.sh <label>
KEY="$MCP_PROBE_KEY"; SID=3c6f6617-d23c-4f48-bfb0-f205e3b27bab
B="http://127.0.0.1:4111"
echo "=============== $1 ==============="
S=$(curl -sS -D /tmp/h.txt -o /dev/null -X POST $B/mcp/ -H "x-litellm-api-key: Bearer $KEY" \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}' --max-time 60
  grep -i '^mcp-session-id' /tmp/h.txt | tr -d '\r' | awk '{print $2}')

echo "--- 1. MCP tools/list (what the client is told it may call)"
curl -sS -X POST $B/mcp/ -H "x-litellm-api-key: Bearer $KEY" -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' -H "mcp-session-id: $S" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' --max-time 90 \
  | tr -d '\r' | grep -o '"name":"[^"]*"'

echo "--- 2. MCP tools/call with that exact advertised name"
curl -sS -X POST $B/mcp/ -H "x-litellm-api-key: Bearer $KEY" -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' -H "mcp-session-id: $S" \
  -d "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"$SID-read_wiki_contents\",\"arguments\":{\"repoName\":\"BerriAI/litellm\"}}}" \
  --max-time 180 | tr -d '\r' | cut -c1-260

echo "--- 3. REST tools/call with server_id + advertised name"
curl -sS -X POST "$B/mcp-rest/tools/call" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d "{\"name\":\"$SID-read_wiki_contents\",\"arguments\":{\"repoName\":\"BerriAI/litellm\"},\"server_id\":\"$SID\"}" \
  --max-time 180 | cut -c1-260

echo "--- 4. negative control: ask_question is upstream and is NOT in allowed_tools"
curl -sS -X POST $B/mcp/ -H "x-litellm-api-key: Bearer $KEY" -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' -H "mcp-session-id: $S" \
  -d "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{\"name\":\"$SID-ask_question\",\"arguments\":{\"repoName\":\"BerriAI/litellm\",\"question\":\"hi\"}}}" \
  --max-time 180 | tr -d '\r' | cut -c1-320

Before, with the four production files at 215f05588d, this PR's base:

=============== BEFORE (unfixed, production files at 215f05588d) ===============
--- 1. MCP tools/list (what the client is told it may call)
--- 2. MCP tools/call with that exact advertised name
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Error: Tool d23c-4f48-bfb0-f205e3b27bab-read_wiki_contents not found"}],"isError":true}}

--- 3. REST tools/call with server_id + advertised name
{"detail":{"error":"Tool 3c6f6617-d23c-4f48-bfb0-f205e3b27bab-read_wiki_contents is not allowed for server 3c6f6617-d23c-4f48-bfb0-f205e3b27bab. Contact proxy admin to allow this tool."}}

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 name d23c-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 verbatim

After, at b818e95400:

=============== AFTER (fix applied, b818e95400) ===============
--- 1. MCP tools/list (what the client is told it may call)
"name":"3c6f6617-d23c-4f48-bfb0-f205e3b27bab-read_wiki_contents"
--- 2. MCP tools/call with that exact advertised name
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"# Page: Overview\n\n# Overview\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following files were used as context for generating this wiki page:\n\n- [README.md](README.m

--- 3. REST tools/call with server_id + advertised name
{"_meta":null,"content":[{"type":"text","text":"# Page: Overview\n\n# Overview\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following files were used as context for generating this wiki page:\n\n- [README.md](README.md)\n- [enterprise/pyprojec

--- 4. negative control: ask_question is upstream and is NOT in allowed_tools
event: message
data: {"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"Error: {'error': 'Tool ask_question is not allowed for server 3c6f6617-d23c-4f48-bfb0-f205e3b27bab. Contact proxy admin to allow this tool.'}"}],"isError":true}}

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_question rather than a mangled fragment, which is the same boundary resolving correctly on the denial path

Because an admin reading their client sees the prefixed name, the same run was repeated with allowed_tools set to the wire spelling instead of the bare one, changing nothing else:

curl -sS -X PUT http://127.0.0.1:4111/v1/mcp/server -H "Authorization: Bearer $MASTER_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"server_id":"3c6f6617-d23c-4f48-bfb0-f205e3b27bab","allowed_tools":["3c6f6617-d23c-4f48-bfb0-f205e3b27bab-read_wiki_contents"]}'
=============== AFTER, wire-form allowed_tools entry (b818e95400) ===============
--- 1. MCP tools/list (what the client is told it may call)
"name":"3c6f6617-d23c-4f48-bfb0-f205e3b27bab-read_wiki_contents"
--- 2. MCP tools/call with that exact advertised name
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"# Page: Overview\n\n# Overview\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following files were used as context for generating this wiki page:\n\n- [README.md](README.m

--- 4. negative control: ask_question is upstream and is NOT in allowed_tools
event: message
data: {"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"Error: {'error': 'Tool ask_question is not allowed for server 3c6f6617-d23c-4f48-bfb0-f205e3b27bab. Contact proxy admin to allow this tool."}],"isError":true}}

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_tools has no column in schema.prisma and no UI writer; its only sources are server_config.get("disallowed_tools") in the config loader and a carry-forward getattr. 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 under LITELLM_USE_SHORT_MCP_TOOL_PREFIX=true, where the published prefix is the computed short prefix and so can never equal server.name

mcp_servers:
  deepwiki_cfg:
    url: https://mcp.deepwiki.com/mcp
    transport: http
    disallowed_tools:
      - "eiG-read_wiki_contents"

eiG is the prefix the proxy itself published for that server, read out of a prior tools/list rather than guessed. The probe lists the server's tools and then calls the banned one:

echo "--- tools/list for the config server (eiG): is the banned tool hidden?"
curl -sS -X POST $B/mcp/ -H "x-litellm-api-key: Bearer $MASTER_KEY" -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' -H "mcp-session-id: $S" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' --max-time 90 \
  | tr -d '\r' | grep -o '"name":"eiG-[^"]*"' | sort -u

echo "--- tools/call the BANNED tool eiG-read_wiki_contents"
curl -sS -X POST $B/mcp/ -H "x-litellm-api-key: Bearer $MASTER_KEY" -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' -H "mcp-session-id: $S" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"eiG-read_wiki_contents","arguments":{"repoName":"BerriAI/litellm"}}}' \
  --max-time 180 | tr -d '\r' | cut -c1-300
=============== BASE 215f05588d (shipped), short-prefix mode, wire-form disallowed_tools ===============
--- tools/list for the config server (eiG): is the banned tool hidden?
"name":"eiG-ask_question"
"name":"eiG-read_wiki_structure"
--- tools/call the BANNED tool eiG-read_wiki_contents
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"# Page: Overview\n\n# Overview\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following files were used as context for generating this wiki page:\n\n- [README.md](README.md)\n- [enterprise/pyproject.toml](enterp

The blocklist works on the list path and does nothing on the call path. read_wiki_contents is 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:

=============== FIXED (b818e95400), short-prefix mode, wire-form disallowed_tools ===============
--- tools/list for the config server (eiG): is the banned tool hidden?
"name":"eiG-ask_question"
"name":"eiG-read_wiki_structure"
--- tools/call the BANNED tool eiG-read_wiki_contents
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Error: {'error': 'Tool read_wiki_contents is not allowed for server deepwiki_cfg. Contact proxy admin to allow this tool.'}"}],"isError":true}}

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:

mcp_servers:
  deepwiki_cfg:
    url: https://mcp.deepwiki.com/mcp
    transport: http
    disallowed_tools:
      - "deepwiki_cfg-read_wiki_contents"
=============== BASE 215f05588d (shipped), short-prefix mode, alias-form disallowed_tools ===============
config blocklist entry: deepwiki_cfg-read_wiki_contents   (alias form)
LITELLM_USE_SHORT_MCP_TOOL_PREFIX=1, so tools publish as eiG-*
--- tools/list: which eiG-* tools are advertised?
"name":"eiG-ask_question"
"name":"eiG-read_wiki_contents"
"name":"eiG-read_wiki_structure"
--- tools/call eiG-read_wiki_contents (the blocked tool, called by its published name)
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Error: {'error': 'Tool read_wiki_contents is not allowed for server deepwiki_cfg. Contact proxy admin to allow this tool.'}"}],"isError":true}}

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 discovers eiG-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:

=============== FIXED bb7eabde18 (this branch), short-prefix mode, alias-form disallowed_tools ===============
config blocklist entry: deepwiki_cfg-read_wiki_contents   (alias form)
LITELLM_USE_SHORT_MCP_TOOL_PREFIX=1, so tools publish as eiG-*
--- tools/list: which eiG-* tools are advertised?
"name":"eiG-ask_question"
"name":"eiG-read_wiki_structure"
--- tools/call eiG-read_wiki_contents (the blocked tool, called by its published name)
event: message
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Error: {'error': 'Tool read_wiki_contents is not allowed for server deepwiki_cfg. Contact proxy admin to allow this tool.'}"}],"isError":true}}

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_params has 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 parameters

mcp_servers:
  deepwiki_cfg:
    url: https://mcp.deepwiki.com/mcp
    transport: http
    allowed_params:
      read_wiki_structure: []
curl -sS -X POST http://127.0.0.1:4111/mcp/ -H "x-litellm-api-key: Bearer $MASTER_KEY" \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -H "mcp-session-id: $S" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"deepwiki_cfg-read_wiki_structure","arguments":{"repoName":"BerriAI/litellm"}}}'

Base 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:

data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Error: {'error': \"Parameters ['repoName'] are not allowed for tool read_wiki_structure. Allowed parameters: []. Contact proxy admin to allow these parameters.\"}"}],"isError":true}}

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:

data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Available pages for BerriAI/litellm:\n\n- 1 Overview\n  - 1.1 Getting Started and Repo Orientation\n  - 1.2 System Architecture at a Glance\n

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:

--- tools/call deepwiki_cfg-read_wiki_structure WITH a parameter (must be refused)
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Error: {'error': \"Parameters ['repoName'] are not allowed for tool read_wiki_structure. Allowed parameters: []. Contact proxy admin to allow these parameters.\"}"}],"isError":true}}

--- negative control: same tool, NO parameters (gate must let it through to upstream)
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Input validation error: 'repoName' is a required property"}],"isError":true}}

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/list and ignored by tools/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 both

mcp_servers:
  deepwiki_cfg:
    url: https://mcp.deepwiki.com/mcp
    transport: http
    disallowed_tools:
      - "DeepWiki_CFG-Read_Wiki_Contents"
=============== BEFORE 215f05588d (shipped) ===============
--- tools/list: is the blocked tool advertised?
"name":"deepwiki_cfg-ask_question"
"name":"deepwiki_cfg-read_wiki_structure"
--- tools/call deepwiki_cfg-read_wiki_contents (the tool the admin banned)
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"# Page: Overview\n\n# Overview\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following files were used as context for generating this wiki page:\n\n- [README.md](README.md)\n

The 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/list sees the ban working. Same config, this branch:

=============== AFTER (unified matcher) ===============
--- tools/list: is the blocked tool advertised?
"name":"deepwiki_cfg-ask_question"
"name":"deepwiki_cfg-read_wiki_structure"
--- tools/call deepwiki_cfg-read_wiki_contents (the tool the admin banned)
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"Error: {'error': 'Tool read_wiki_contents is not allowed for server deepwiki_cfg. Contact proxy admin to allow this tool.'}"}],"isError":true}}

The branch above folded case on every server, and that is the version this run was first written against. On a server exposing both getPet and getpet it granted getpet from an allowlist naming only getPet, and denied getpet from a blocklist naming only getPet; unauthorized execution on one arm, the wrong tool denied on the other. Driven through the real functions:

ROUTING keys registered:  getPet  getpet  petstore-getPet  petstore-getpet  ...   (8 distinct)
allowlist ["getPet"] ->  getPet allowed=True   getpet allowed=True    <- merged
blocklist ["getPet"] ->  getPet allowed=False  getpet allowed=False   <- merged

Matching is exact now, and the same probe reads getpet allowed=False under the allowlist and getpet allowed=True under the blocklist. Live, with a deny entry that names no tool that exists, the branch that folded case hid the real tool from tools/list and refused the call, while this one lists it and calls it:

=============== BEFORE (folded matcher), deny entry deepwiki_cfg-Read_Wiki_Contents ===============
--- tools/list
"name":"deepwiki_cfg-ask_question"
"name":"deepwiki_cfg-read_wiki_structure"
--- tools/call deepwiki_cfg-read_wiki_contents
data: ... "Error: {'error': 'Tool read_wiki_contents is not allowed for server deepwiki_cfg...'}" "isError":true

=============== AFTER (identity-exact matcher) ===============
--- tools/list
"name":"deepwiki_cfg-ask_question"
"name":"deepwiki_cfg-read_wiki_contents"
"name":"deepwiki_cfg-read_wiki_structure"
--- tools/call deepwiki_cfg-read_wiki_contents
data: ... "# Page: Overview\n\n# Overview\n\n<details>..."

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_tools names an operationId inline with operation_id.replace(" ", "_").lower(), which preserves / and .; the similarly named sanitize_openapi_tool_name replaces every character outside [a-zA-Z0-9_-] and belongs to register_tools_from_openapi, which has no production caller. Replaying the second while gating on spec_path, which registers through the first, collapsed foo/bar and foo.bar onto one policy identity

So the map has one owner now. That inline expression is openapi_tool_name in utils.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 them

REGISTRATION maps:   foo/bar -> foo/bar     foo.bar -> foo.bar     addPet -> addpet
policy entry ["foo/bar"]:   tool foo/bar -> matched 'foo/bar'   tool foo.bar -> matched None
spec-spelled entry:         tool 'addpet' vs ['addPet'] -> 'addPet'
same on a native server:    None

test_case_folding_applies_to_openapi_servers_and_not_to_native_ones pins both halves, test_an_entry_does_not_decide_an_operation_id_registration_keeps_separate pins the collision, and two tests pin that a policy naming one tool leaves its case-variant sibling alone

So the shipped tools/list and tools/call disagreement 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 tool

Type

🐛 Bug Fix

Changes

The name a client sees on the wire is {server_prefix}{MCP_TOOL_PREFIX_SEPARATOR}{tool_name}, and get_server_prefix takes that prefix from short_prefix, else alias, else server_name, else server_id. Both server_name and alias are nullable in schema.prisma, so a server created with neither is prefixed by its server_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 enabled short_prefix, or a deployment that overrides the separator each hit it a different way

Recovering the boundary is now owned by one function. match_known_server_prefix(name, known_prefixes) in utils.py returns (matched_prefix, bare_name), or None when 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_prefix and the known-prefix branch of is_tool_name_prefixed delegate to it instead of each re-deriving the boundary, and _resolve_mcp_server_for_tool_call calls it directly in place of the split-then-normalize-then-look-up sequence it hand-rolled

split_server_prefix_from_name stays, 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 owner

The list path and the call path stopped disagreeing:

  • execute_mcp_tool took the routing pair from the blunt split and repaired only the server half, so original_tool_name stayed 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_id branch
  • _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 names
  • apply_tool_overrides and the tool_name_to_mcp_server_name_mapping build both keyed off the blunt split

The 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_handler run, the tool name is already bare. Every caller resolves the boundary before dispatch: server.py passes original_tool_name on both entry points, the Responses handler passes a sanitized_tool_name it produced with strip_known_server_prefix, and call_tool hands 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 anything

Which operands to derive is the part the second review round corrected, and it is the real invariant here. get_server_prefix publishes one prefix, but routing accepts several: iter_known_server_prefixes yields short_prefix, the computed short prefix, alias, server_name and server_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 on disallowed_tools that difference fails open. The new owner is iter_known_tool_name_spellings(tool_name, server) in utils.py, which yields the bare name and then its wire spelling under each accepted prefix. check_allowed_or_banned_tools, validate_allowed_params, the tool_name_to_mcp_server_name_mapping build and _tool_name_matches all 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, and test_every_spelling_routing_registers_is_also_enforced drives _create_prefixed_tools and asserts every key routing registers is a key enforcement can refuse

That correction is also what closes the fail-open in run 2. check_allowed_or_banned_tools previously built its second operand as f"{server.name}-{tool_name}", which hardcodes the separator and uses a field the prefix chain never reads. On a server with a short_prefix, or under an overridden separator, that string can never equal the wire name the proxy published, so a wire-form disallowed_tools entry matched nothing. _call_openapi_tool_handler had the same expression as its registry key while registration builds the key with add_server_prefix_to_name(..., get_server_prefix(server)), so lookup and registration disagreed under exactly those conditions

Every 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_tools reaches the manager from config verbatim, from the create and update API bodies verbatim, and from the DB column verbatim; disallowed_tools has 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 from disallowed_tools would 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 here

Four 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:327 and :363 have 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:228 mixes server IDs and server names in a single list, which is its own normalization problem. server.py:3110 is prompts/get, which matches on .name only. user_api_key_auth_mcp.py:1155 splits a header name, not a tool name

One 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 entry foo-bar matches the native tool foo-bar by its bare name and the native tool bar by its wire name. No amount of prefix matching settles that from the string alone, and shipped code has the same property through its f"{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 refuses

On 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_name itself. mcp_server_manager.py drops twelve lines, server.py gains one, rest_endpoints.py is unchanged, and utils.py absorbs fifteen. The discovery filter alone goes from twenty-four lines to seven

Tests 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_params lookup 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 the spec_path guard 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 that None means no restriction fails one, and always granting fails four. That last group is why test_key_team_listing_and_dispatch_agree asserts 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 in allowed_params fails 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 the allowed_params lookup fails test_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 than git 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 fails test_dispatch_keeps_a_native_name_that_opens_with_the_prefix, and restoring the original f"{server.name}-{tool_name}" fails the rows named for the blocklist bypass. TestMatchKnownServerPrefix pins 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. TestServerToolListsHonorThePrefixBoundary drives both spellings of both list arms through pre_call_tool_check, under the default separator, under an overridden one, and under short-prefix mode. TestOpenAPIRegistryKeyMatchesRegistration exists because a mutant on the registry key survived the first round: every pre-existing test on that path patches _call_openapi_tool_handler out, so nothing pinned the agreement between lookup and registration

Alongside 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 prefix iter_known_server_prefixes accepts, 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 allow

Two test-side notes for the reviewer. Several MagicMock server fixtures had drifted into shapes production never produces, where auto-created attributes stood in for alias, short_prefix, and the display-name maps, and a truthy auto-MagicMock for tool_name_to_display_name was defeating a production early return; those are now pinned to None. And test_execute_mcp_tool_rest_unresolved_prefixed_name_routes_to_requested_server changed 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 the tool_server_mismatch 403 exists to prevent. That reading follows the routing principle in #30184, whose own commits include allowing hyphenated upstream tool names when the REST server_id is authoritative

One red that is not mine, flagged rather than absorbed: two cases in test_mcp_env_vars.py fail 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 write os.environ directly

One change deserves a reviewer's eye rather than a claim that it is safe. validate_allowed_params used to fall back to server.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 as wiki configured for a native read-wiki, and a miss there means allowed_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 differential

QA runbook

  1. Create an MCP server through POST /v1/mcp/server with alias and server_name both omitted, pointing at https://mcp.deepwiki.com/mcp with transport: http, and set allowed_tools to ["read_wiki_contents"]
  2. Mint a virtual key scoped to that server, then run initialize and tools/list over POST /mcp/ with x-litellm-api-key: Bearer <key>. Expect exactly one tool, named <server_id>-read_wiki_contents
  3. Call that exact advertised name with tools/call and {"repoName": "BerriAI/litellm"}. Expect wiki content, not Tool ... not found
  4. Repeat step 3 through POST /mcp-rest/tools/call with server_id in the body. Expect the same content
  5. Call <server_id>-ask_question the same way. Expect a refusal naming ask_question, which confirms the fix narrowed correctly instead of just stopping refusals
  6. Update allowed_tools to 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 form
  7. For the fail-open, define a server in config with disallowed_tools set to the wire name the proxy publishes for it, run the proxy with LITELLM_USE_SHORT_MCP_TOOL_PREFIX=true, and call the banned tool. Expect a refusal. On litellm_internal_staging the same call returns upstream content

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

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/call disagreed because the code split prefixed names at the first separator instead of using each server’s registered prefixes (notably when the prefix is a UUID server_id containing -).

Prefix handling: Adds match_known_server_prefix (longest-prefix match) and routes strip_known_server_prefix, prefixed-tool detection, and execute_mcp_tool through it so the bare tool name sent upstream matches what routing registered.

One matcher for policy: Adds iter_known_tool_name_spellings and match_known_tool_name so allowed_tools / disallowed_tools, allowed_params, OpenAPI registry lookup, and list filters honor every wire spelling routing accepts (alias, short prefix, server_id, etc.), not only f"{server.name}-…". OpenAPI servers normalize via shared openapi_tool_name; native tools stay case-exact.

Permissions alignment: Introduces MCPRequestHandler.tool_is_granted for bare key/team grants; REST listing uses filter_tools_by_key_team_permissions like 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.

@greptile-apps

greptile-apps Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR centralizes MCP tool-prefix recovery and policy identity matching.

  • Resolves tool names against registered server prefixes rather than the first separator.
  • Aligns discovery, dispatch, server policy lists, parameter restrictions, and routing-map spellings.
  • Preserves case-sensitive identities for native MCP tools while sharing OpenAPI registration normalization with policy matching.
  • Adds regression coverage for prefix boundaries, policy enforcement, OpenAPI identities, and empty parameter allowlists.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains in the fixes associated with the prior review threads.

Important Files Changed

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

codecov Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.11321% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...oxy/_experimental/mcp_server/mcp_server_manager.py 93.75% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_mcp_prefix_boundary (179ebdb) with litellm_internal_staging (d0fe305)1

Open in CodSpeed

Footnotes

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

@tin-berri
tin-berri force-pushed the litellm_mcp_prefix_boundary branch from 2806c76 to b818e95 Compare July 26, 2026 01:12
@veria-ai

veria-ai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 3 · PR risk: 0/10

@tin-berri
tin-berri force-pushed the litellm_mcp_prefix_boundary branch 3 times, most recently from 1f3c342 to bb7eabd Compare July 26, 2026 02:04
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

1 similar comment
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@tin-berri
tin-berri force-pushed the litellm_mcp_prefix_boundary branch from bb7eabd to 35006e5 Compare July 26, 2026 04:08
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@devin-ai-integration

Copy link
Copy Markdown
Contributor

QA of key/team tool grants (mcp_tool_permissions and toolsets) against a live proxy on 127.0.0.1:4111, real Postgres, and the public DeepWiki MCP server, on a server created through POST /v1/mcp/server with alias and server_name both null so the published prefix is the UUID server_id

Both grant shapes are stored as written and now work end to end on this branch, and both are broken on litellm_internal_staging at 10cd4288b6

Key with object_permission.mcp_tool_permissions = {"<server_id>": ["read_wiki_contents"]}, read back verbatim from GET /key/info:

=============== FIXED 35006e53ed ===============
--- 1. tools/list
"name":"48c8a868-5bb8-40d6-9688-8a337f585057-read_wiki_contents"
--- 2. tools/call the advertised name
data: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"# Page: Overview\n\n# Overview\n ...
--- 3. negative control: <server_id>-ask_question
data: {"...":"Error: {'error': \"Tool 'ask_question' is not allowed for your key/team on server '48c8a868-...'. Contact proxy admin for access.\"}"}

=============== BASE 10cd4288b6 ===============
--- 1. tools/list
"name":"48c8a868-5bb8-40d6-9688-8a337f585057-read_wiki_contents"
--- 2. tools/call the advertised name
data: {"...":"Error: Tool 5bb8-40d6-9688-8a337f585057-read_wiki_contents not found"}

A toolset created through POST /v1/mcp/toolset with {"server_id": "<server_id>", "tool_name": "read_wiki_structure"} and granted through object_permission.mcp_toolsets behaves the same way: the tool lists and calls on this branch, and dies on the base with the same mangled name. Editing the toolset through PUT /v1/mcp/toolset to add ask_question takes effect on the next request, so the permission cache invalidation holds. Calling a bare name the key was not granted is refused rather than dispatched, so the wider spelling set on the server-level lists did not leak into the key-level ones

One regression this branch introduced, now fixed in 46f37ff451. The REST listing filter compared key/team grants through _tool_name_matches, which this branch widened to every spelling routing accepts. Key-level entries are different from allowed_tools: mcp_tool_permissions and toolset rows name a tool on one server, every writer writes them bare (the dashboard picker stores the name mcp-rest/tools/list returns, and resolve_toolset_tool_permissions uses the stored name as written), and is_tool_allowed_for_server compares them bare. So a wire-form entry grants nothing, yet REST listing started advertising the tool:

# key whose only grant is "<server_id>-read_wiki_contents"
BASE 10cd4288b6      GET /mcp-rest/tools/list  ->  (empty)
35006e53ed           GET /mcp-rest/tools/list  ->  "name":"read_wiki_contents"     # advertised
                     POST /mcp/ tools/call     ->  refused, and MCP tools/list hides it
46f37ff451           GET /mcp-rest/tools/list  ->  (empty)

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 filter_tools_by_key_team_permissions, the same function the MCP list path uses, which also deletes the duplicated lookup. test_rest_listing_hides_key_grants_dispatch_would_refuse in tests/mcp_tests/test_mcp_server.py pins it and fails against the previous expression

tests/mcp_tests/test_mcp_server.py is 49 passed 1 skipped, and tests/test_litellm/proxy/_experimental/mcp_server/ is green apart from the test_mcp_env_vars.py order dependence already noted in the description and test_semantic_tool_filter.py, which needs the semantic_router package that is not installed on this box

@tin-berri

Copy link
Copy Markdown
Contributor Author

Pushed fe7aff81b0, which replaces the pointwise answers to both review findings with one owner

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, allowed_params, and the discovery filter. 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. Deriving the operands differently at one site is what produced the over-strip Greptile found; needing a value rather than a boolean at another is what produced the truthiness test Veria found

match_known_tool_name(tool_name, server, names) returns the matching entry or None, and all four sites read it. No site can test a container's values to decide membership any more, so the empty-allowed_params fail-open is not representable rather than fixed

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 disallowed_tools entry differing only in case therefore hides the tool from tools/list and lets tools/call execute it. On the base commit the banned tool is absent from the listing and returns the full wiki page when called. Unifying on case-insensitive closes it, and widens one thing in exchange: an allowed_tools entry differing only in case now grants the tool where it previously listed it and then refused it. Both directions are pinned, test_a_case_variant_allowlist_entry_grants_the_tool and test_a_case_variant_blocklist_entry_still_blocks

On size, executable lines over the merge-base go from +9 to +4, and all four are the new function. mcp_server_manager.py loses twelve lines and the discovery filter goes from twenty-four to seven. Five mutants against the matcher all die, including one that reintroduces the truthiness test and kills exactly the regression test for it

This sits on top of 46f37ff451 rather than replacing it, so the REST listing fix keeps its own commit and authorship

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri
tin-berri force-pushed the litellm_mcp_prefix_boundary branch 2 times, most recently from df4ed1b to e489574 Compare July 27, 2026 22:05
@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit c4312fd. Configure here.

@tin-berri
tin-berri enabled auto-merge July 29, 2026 07:55

@mateo-berri mateo-berri left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks!

tin-berri and others added 6 commits July 30, 2026 22:13
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.
@tin-berri
tin-berri force-pushed the litellm_mcp_prefix_boundary branch from c4312fd to 179ebdb Compare July 31, 2026 05:32
@tin-berri
tin-berri merged commit 05c9815 into litellm_internal_staging Jul 31, 2026
78 of 79 checks passed
@tin-berri
tin-berri deleted the litellm_mcp_prefix_boundary branch July 31, 2026 05:45
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