The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(mcp): recover the tool-name prefix boundary from registered prefixes
Tin7be3ddd0ffbd
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex ae1095da336..285e7b26104 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -116,12 +116,13 @@ from litellm.proxy._experimental.mcp_server.utils import (get_server_prefix,interpolate_headers,is_short_mcp_tool_prefix_enabled,- is_tool_name_prefixed,iter_known_server_prefixes,+ iter_known_tool_name_spellings,+ match_known_server_prefix,merge_mcp_headers,normalize_server_name,parse_admin_env_vars,- split_server_prefix_from_name,+ strip_known_server_prefix,validate_mcp_server_name,)from litellm.proxy._types import (@@ -4185,10 +4186,8 @@ class MCPServerManager:# Register every known prefix form (alias, server_name, server_id,# short ID) so call_tool can resolve regardless of which form a# caller / cached client is using.- self.tool_name_to_mcp_server_name_mapping[original_name] = prefix- for known_prefix in iter_known_server_prefixes(server):- qualified = add_server_prefix_to_name(original_name, known_prefix)- self.tool_name_to_mcp_server_name_mapping[qualified] = prefix+ for spelling in iter_known_tool_name_spellings(original_name, server):+ self.tool_name_to_mcp_server_name_mapping[spelling] = prefixverbose_logger.info(f"Successfully fetched {len(prefixed_tools)} tools from server {server.name}")return prefixed_tools@@ -4261,20 +4260,27 @@ class MCPServerManager:def check_allowed_or_banned_tools(self, tool_name: str, server: MCPServer) -> bool:"""- Check if the tool is allowed or banned for the given server+ Check if the tool is allowed or banned for the given server.++ ``tool_name`` is bare: every caller resolves the boundary against the+ server's registered prefixes before dispatch (``server.py``'s+ ``original_tool_name``, the Responses handler's ``sanitized_tool_name``).+ Stored entries are matched by deriving the spellings routing accepts+ rather than by stripping the entries, which would cut a second boundary+ out of a native name that itself opens with the server prefix."""from litellm.proxy._experimental.mcp_server.utils import (server_applies_tool_allowlist,)+ spellings = tuple(iter_known_tool_name_spellings(tool_name, server))+if server_applies_tool_allowlist(server):if not server.allowed_tools:return False- return tool_name in server.allowed_tools or f"{server.name}-{tool_name}" in server.allowed_tools+ return any(spelling in server.allowed_tools for spelling in spellings)if server.disallowed_tools:- return (- tool_name not in server.disallowed_tools and f"{server.name}-{tool_name}" not in server.disallowed_tools- )+ return all(spelling not in server.disallowed_tools for spelling in spellings)return Truedef validate_allowed_params(self, tool_name: str, arguments: dict[str, Any], server: MCPServer) -> None:@@ -4282,7 +4288,8 @@ class MCPServerManager:Filter arguments to only include allowed parameters for the given tool.Args:- tool_name: Name of the tool (with or without prefix)+ tool_name: Bare tool name, already resolved against the server's+ registered prefixes by the callerarguments: Dictionary of arguments to filterserver: MCPServer configuration@@ -4292,19 +4299,14 @@ class MCPServerManager:Raises:HTTPException: If allowed_params is configured for this tool but arguments contain disallowed params"""- from litellm.proxy._experimental.mcp_server.utils import (- split_server_prefix_from_name,- )-# If no allowed_params configured, return all argumentsif not server.allowed_params:return- # Get the unprefixed tool name to match against config- unprefixed_tool_name, _ = split_server_prefix_from_name(tool_name)-- # Check both prefixed and unprefixed tool names- allowed_params_list = server.allowed_params.get(tool_name) or server.allowed_params.get(unprefixed_tool_name)+ spellings = iter_known_tool_name_spellings(tool_name, server)+ allowed_params_list = next(+ (server.allowed_params[name] for name in spellings if name in server.allowed_params), None+ )# If this tool doesn't have allowed_params specified, allow all paramsif allowed_params_list is None:@@ -4390,8 +4392,11 @@ class MCPServerManager:global_mcp_tool_registry,)- # Get the tool from the registry- tool = global_mcp_tool_registry.get_tool(f"{server.name}-{tool_name}")+ # Registration used add_server_prefix_to_name(base, get_server_prefix(server)),+ # and tool_name is the bare base name by the time call_tool reaches here, so+ # rebuilding the key the same way reproduces it exactly+ registry_key = add_server_prefix_to_name(tool_name, get_server_prefix(server))+ tool = global_mcp_tool_registry.get_tool(registry_key)if tool is None:# Tool not found in registryerror_msg = f"OpenAPI tool {tool_name} not found in registry"@@ -5251,7 +5256,7 @@ class MCPServerManager:for tool in tools:# The tool.name here is already prefixed from _get_tools_from_server# Extract original name for mapping- original_name, _ = split_server_prefix_from_name(tool.name)+ original_name = strip_known_server_prefix(tool.name, server)self.tool_name_to_mcp_server_name_mapping[original_name] = server.nameself.tool_name_to_mcp_server_name_mapping[tool.name] = server.name@@ -5288,13 +5293,10 @@ class MCPServerManager:# If not found and tool name is prefixed, extract the prefix and# match against any known form.- if is_tool_name_prefixed(tool_name, known_server_prefixes=set(prefix_to_server.keys())):- (- original_tool_name,- server_name_from_prefix,- ) = split_server_prefix_from_name(tool_name)- normalised_prefix = normalize_server_name(server_name_from_prefix)- matched_server = prefix_to_server.get(normalised_prefix)+ matched = match_known_server_prefix(tool_name, prefix_to_server.keys())+ if matched is not None:+ matched_prefix, original_tool_name = matched+ matched_server = prefix_to_server.get(matched_prefix)if matched_server is not None and (original_tool_name in self.tool_name_to_mcp_server_name_mappingor tool_name in self.tool_name_to_mcp_server_name_mappingdiff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.pyindex 9b51513f4ac..1736e34d70c 100644--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py@@ -542,7 +542,7 @@ if MCP_AVAILABLE:user_api_key_auth=user_api_key_auth,)if allowed_tools_for_server is not None:- tools = [tool for tool in tools if _tool_name_matches(tool.name, allowed_tools_for_server)]+ tools = [tool for tool in tools if _tool_name_matches(tool.name, allowed_tools_for_server, server)]return _create_tool_response_objects(tools, server)diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex ec07d33f24d..5181f3a2676 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -65,6 +65,7 @@ from litellm.proxy._experimental.mcp_server.utils import (extract_mcp_tool_result_error_message,get_server_prefix,iter_known_server_prefixes,+ iter_known_tool_name_spellings,)from litellm.proxy._types import (ProxyException,@@ -1416,34 +1417,32 @@ if MCP_AVAILABLE:return allowed_mcp_servers- def _tool_name_matches(tool_name: str, filter_list: list[str]) -> bool:+ def _tool_name_matches(tool_name: str, filter_list: list[str], mcp_server: MCPServer) -> bool:"""Check if a tool name matches any name in the filter list.- Checks both the full tool name and unprefixed version (without server prefix).- This allows users to configure simple tool names regardless of prefixing.- Comparison is case-insensitive to handle OpenAPI operationIds that may be in camelCase.+ Matches via the same ``iter_known_tool_name_spellings`` the server-level+ permission checks use, so discovery hides exactly what dispatch refuses;+ covering fewer spellings here leaves a blocked tool advertised in+ ``tools/list``. Comparison is case-insensitive to handle OpenAPI+ operationIds that may be in camelCase.Args:tool_name: The tool name to check (may be prefixed like "server-tool_name")filter_list: List of tool names to match against+ mcp_server: The server the tool belongs to, whose registered prefixes+ locate the boundary exactly. Required: guessing the boundary at+ the first separator silently mismatches every tool on a server+ whose prefix contains the separator.Returns:- True if the tool name (prefixed or unprefixed) is in the filter list+ True if any spelling of the tool name is in the filter list"""- from litellm.proxy._experimental.mcp_server.utils import (- split_server_prefix_from_name,- )-- # Normalize filter list to lowercase for case-insensitive comparison- filter_list_lower = [f.lower() for f in filter_list]-- if tool_name.lower() in filter_list_lower:- return True+ filter_list_lower = {f.lower() for f in filter_list}+ bare_name = strip_known_server_prefix(tool_name, mcp_server)+ spellings = (tool_name, *iter_known_tool_name_spellings(bare_name, mcp_server))- # Check if the unprefixed name is in the list (case-insensitive)- unprefixed_name, _ = split_server_prefix_from_name(tool_name)- return unprefixed_name.lower() in filter_list_lower+ return any(spelling.lower() in filter_list_lower for spelling in spellings)def filter_tools_by_allowed_tools(tools: list[MCPTool],@@ -1473,12 +1472,16 @@ if MCP_AVAILABLE:if server_applies_tool_allowlist(mcp_server):if not mcp_server.allowed_tools:return []- tools_to_return = [tool for tool in tools if _tool_name_matches(tool.name, mcp_server.allowed_tools)]+ tools_to_return = [+ tool for tool in tools if _tool_name_matches(tool.name, mcp_server.allowed_tools, mcp_server)+ ]# Filter by disallowed_tools (blacklist)if mcp_server.disallowed_tools:tools_to_return = [- tool for tool in tools_to_return if not _tool_name_matches(tool.name, mcp_server.disallowed_tools)+ tool+ for tool in tools_to_return+ if not _tool_name_matches(tool.name, mcp_server.disallowed_tools, mcp_server)]return tools_to_return@@ -1498,7 +1501,7 @@ if MCP_AVAILABLE:return toolsfor tool in tools:- unprefixed, _ = split_server_prefix_from_name(tool.name)+ unprefixed = strip_known_server_prefix(tool.name, mcp_server)lookup_key = unprefixed or tool.nameif lookup_key in display_name_map:tool.name = display_name_map[lookup_key]@@ -2699,6 +2702,7 @@ if MCP_AVAILABLE:breakif mcp_server is not None:server_name = mcp_server.name+ original_tool_name = strip_known_server_prefix(name, mcp_server)if requested_server is not None:if mcp_server is not None and mcp_server.server_id != requested_server.server_id:@@ -2716,6 +2720,7 @@ if MCP_AVAILABLE:if mcp_server is None:mcp_server = requested_serverserver_name = requested_server.name+ original_tool_name = strip_known_server_prefix(name, requested_server)# Only enforce server-level permissions when we can resolve a serverif server_name:@@ -2887,13 +2892,14 @@ if MCP_AVAILABLE:_request_resolved_auth_headers.reset(_resolved_token)response = CallToolResult(content=cast(Any, local_content), isError=False)- # Try managed MCP server tool (pass the full prefixed name)+ # Try managed MCP server tool (the name is bare; the prefix boundary was+ # already resolved above against this server's registered prefixes)# Primary and recommended way to use external MCP servers#########################################################elif mcp_server:response = await _handle_managed_mcp_tool(server_name=server_name,- name=original_tool_name, # Pass the full name (potentially prefixed)+ name=original_tool_name,arguments=arguments,user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,diff --git a/litellm/proxy/_experimental/mcp_server/utils.py b/litellm/proxy/_experimental/mcp_server/utils.pyindex afd396adc4c..e8f8c08188e 100644--- a/litellm/proxy/_experimental/mcp_server/utils.py+++ b/litellm/proxy/_experimental/mcp_server/utils.py@@ -326,8 +326,34 @@ def iter_known_server_prefixes(server: Any) -> Iterator[str]:yield from _emit(server_id)+def iter_known_tool_name_spellings(tool_name: str, server: Any) -> Iterator[str]:+ """Yield every name that denotes the bare ``tool_name`` on ``server``.++ The bare name, then its wire spelling under each prefix from+ ``iter_known_server_prefixes``. Routing resolves an inbound name against that+ whole set, so anything keyed by tool name (the routing map, the allow/deny+ lists, ``allowed_params``) must cover it too or it answers for fewer names+ than are reachable, which fails open on ``disallowed_tools``.+ ``get_server_prefix`` alone covers only the published spelling, and that moves+ with the alias and with ``LITELLM_USE_SHORT_MCP_TOOL_PREFIX``. These are+ spellings of one tool on one server, so honoring all of them normalizes the+ entry rather than widening a grant.+ """+ yield tool_name+ for prefix in iter_known_server_prefixes(server):+ yield add_server_prefix_to_name(tool_name, prefix)++def split_server_prefix_from_name(prefixed_name: str) -> Tuple[str, str]:- """Return the unprefixed name plus the server name used as prefix."""+ """Return the unprefixed name plus the server name used as prefix.++ Cuts at the FIRST separator, so the two halves are only trustworthy as a+ pair: they reassemble into ``prefixed_name`` exactly, which is what makes+ this safe for routing. Reading one half on its own is a guess about where the+ boundary fell, and that guess is wrong whenever the prefix itself contains+ the separator. Callers that compare a half against configuration must use+ :func:`match_known_server_prefix` or :func:`strip_known_server_prefix`.+ """if MCP_TOOL_PREFIX_SEPARATOR in prefixed_name:parts = prefixed_name.split(MCP_TOOL_PREFIX_SEPARATOR, 1)if len(parts) == 2:@@ -335,6 +361,27 @@ def split_server_prefix_from_name(prefixed_name: str) -> Tuple[str, str]:return prefixed_name, ""+def match_known_server_prefix(name: str, known_prefixes: Iterable[str]) -> tuple[str, str] | None:+ """Return ``(matched_prefix, bare_name)`` when ``name`` carries a known prefix.++ Candidates are normalized and tried LONGEST first, so a prefix that itself+ contains :data:`MCP_TOOL_PREFIX_SEPARATOR` (the UUID ``server_id`` used when+ a server has no alias, or a legacy hyphenated alias) wins over a shorter+ prefix that is merely its leading segment. Returns ``None`` when no candidate+ matches, i.e. ``name`` carries none of these prefixes.+ """+ candidates = sorted(+ {normalize_server_name(prefix) for prefix in known_prefixes if prefix},+ key=len,+ reverse=True,+ )+ for prefix in candidates:+ separator_suffixed = prefix + MCP_TOOL_PREFIX_SEPARATOR+ if name.startswith(separator_suffixed):+ return prefix, name[len(separator_suffixed) :]+ return None++def strip_known_server_prefix(name: str, server: Optional[Any]) -> str:"""Strip ``server``'s registered prefix from a prefixed tool/resource name.@@ -352,11 +399,8 @@ def strip_known_server_prefix(name: str, server: Optional[Any]) -> str:"""if server is None:return split_server_prefix_from_name(name)[0]- for prefix in iter_known_server_prefixes(server):- candidate = normalize_server_name(prefix) + MCP_TOOL_PREFIX_SEPARATOR- if name.startswith(candidate):- return name[len(candidate) :]- return name+ matched = match_known_server_prefix(name, iter_known_server_prefixes(server))+ return name if matched is None else matched[1]def is_tool_name_prefixed(@@ -367,15 +411,16 @@ def is_tool_name_prefixed(Check if tool name has a known MCP server prefix.When ``known_server_prefixes`` is provided the function verifies that the- substring before the first separator is an actual registered server- prefix. Without it the check falls back to the legacy heuristic+ name actually starts with one of those prefixes followed by the separator,+ matching the longest candidate first so a prefix containing the separator+ still resolves. Without it the check falls back to the legacy heuristic(separator present anywhere in the name), which can produce falsepositives for non-MCP tools whose names contain hyphens(e.g. ``text-to-speech``, ``code-review``).Args:tool_name: Tool name to check.- known_server_prefixes: Optional set of normalised server prefixes+ known_server_prefixes: Optional set of normalized server prefixescurrently registered in the MCP manager. Pass this wheneverthe caller has access to the server registry so that the checkis accurate.@@ -387,8 +432,7 @@ def is_tool_name_prefixed(return Falseif known_server_prefixes is not None:- candidate_prefix = tool_name.split(MCP_TOOL_PREFIX_SEPARATOR, 1)[0]- return normalize_server_name(candidate_prefix) in known_server_prefixes+ return match_known_server_prefix(tool_name, known_server_prefixes) is not None# Legacy fallback – separator present somewhere in the name.return Truediff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.pyindex f1e6539439a..390f6917573 100644--- a/tests/mcp_tests/test_mcp_server.py+++ b/tests/mcp_tests/test_mcp_server.py@@ -2010,6 +2010,9 @@ async def test_get_tools_for_single_server_applies_disallowed_tools_without_allomock_server.mcp_info = {"server_name": "zapier"}mock_server.name = "zapier"mock_server.server_id = "zapier"+ mock_server.server_name = "zapier"+ mock_server.alias = None+ mock_server.short_prefix = Nonemock_server.allowed_tools = Nonemock_server.disallowed_tools = ["send_email"]diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.pyindex c0affdf46b3..a3577c85621 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py@@ -1029,6 +1029,9 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():working_server.server_name = "working_server"working_server.auth_type = Noneworking_server.extra_headers = None+ working_server.short_prefix = None+ working_server.tool_name_to_display_name = None+ working_server.tool_name_to_description = Nonefailing_server = MagicMock()failing_server.name = "failing_server"@@ -1039,6 +1042,9 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():failing_server.server_name = "failing_server"failing_server.auth_type = Nonefailing_server.extra_headers = None+ failing_server.short_prefix = None+ failing_server.tool_name_to_display_name = None+ failing_server.tool_name_to_description = None# Mock global_mcp_server_managermock_manager = MagicMock()@@ -4507,28 +4513,36 @@ def test_tool_name_matches_case_insensitive():except ImportError:pytest.skip("MCP server not available")+ server = MCPServer(+ server_id="srv-per-store",+ name="per_store",+ server_name="per_store",+ url="http://127.0.0.1:5115/mcp",+ transport=MCPTransport.http,+ )+# Test case 1: Unprefixed tool name with camelCase in filter list- assert _tool_name_matches("addpet", ["addPet", "updatePet"]) is True- assert _tool_name_matches("updatepet", ["addPet", "updatePet"]) is True- assert _tool_name_matches("deletepet", ["addPet", "updatePet"]) is False+ assert _tool_name_matches("addpet", ["addPet", "updatePet"], server) is True+ assert _tool_name_matches("updatepet", ["addPet", "updatePet"], server) is True+ assert _tool_name_matches("deletepet", ["addPet", "updatePet"], server) is False# Test case 2: Prefixed tool name with camelCase in filter list- assert _tool_name_matches("per_store-addpet", ["addPet", "updatePet"]) is True- assert _tool_name_matches("per_store-updatepet", ["addPet", "updatePet"]) is True- assert _tool_name_matches("per_store-deletepet", ["addPet", "updatePet"]) is False+ assert _tool_name_matches("per_store-addpet", ["addPet", "updatePet"], server) is True+ assert _tool_name_matches("per_store-updatepet", ["addPet", "updatePet"], server) is True+ assert _tool_name_matches("per_store-deletepet", ["addPet", "updatePet"], server) is False# Test case 3: Mixed case variations- assert _tool_name_matches("findPetsByStatus", ["findpetsbystatus"]) is True- assert _tool_name_matches("findpetsbystatus", ["findPetsByStatus"]) is True- assert _tool_name_matches("FINDPETSBYSTATUS", ["findPetsByStatus"]) is True+ assert _tool_name_matches("findPetsByStatus", ["findpetsbystatus"], server) is True+ assert _tool_name_matches("findpetsbystatus", ["findPetsByStatus"], server) is True+ assert _tool_name_matches("FINDPETSBYSTATUS", ["findPetsByStatus"], server) is True# Test case 4: Full prefixed name in filter list (case-insensitive)- assert _tool_name_matches("server-addPet", ["server-addpet"]) is True- assert _tool_name_matches("server-addpet", ["server-addPet"]) is True+ assert _tool_name_matches("server-addPet", ["server-addpet"], server) is True+ assert _tool_name_matches("server-addpet", ["server-addPet"], server) is True# Test case 5: Ensure non-matching names still don't match- assert _tool_name_matches("addpet", ["deletePet", "updatePet"]) is False- assert _tool_name_matches("server-addpet", ["deletePet", "updatePet"]) is False+ assert _tool_name_matches("addpet", ["deletePet", "updatePet"], server) is False+ assert _tool_name_matches("server-addpet", ["deletePet", "updatePet"], server) is Falsedef test_filter_tools_by_allowed_tools_case_insensitive():@@ -4581,6 +4595,7 @@ def test_filter_tools_by_allowed_tools_case_insensitive():server = MCPServer(server_id="test-server",name="per_store",+ server_name="per_store",transport=MCPTransport.http,allowed_tools=["addPet", "updatePet", "findPetsByStatus"],)@@ -6121,6 +6136,70 @@ async def test_execute_mcp_tool_rest_server_id_authoritative_for_unprefixed_toolassert captured["name"] == "echo"+async def test_execute_mcp_tool_strips_a_prefix_that_contains_the_separator():+ """A server with no alias publishes its UUID server_id as the tool prefix.++ Splitting that wire name at the first separator leaves a truncated UUID tail+ glued to the tool name, which then travels to the upstream server as the tool+ to call, into the spend log, and into the server-level allowed_tools check.+ """+ from mcp.types import TextContent++ from litellm.proxy._experimental.mcp_server import server as mcp_module++ server_id = "117c814c-1a2b-4c4d-8e8f-0a1b2c3d4e5f"+ alias_less_server = MCPServer(+ server_id=server_id,+ name=server_id,+ url="http://127.0.0.1:5115/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.api_key,+ authentication_token="abc123",+ )++ captured: dict = {}++ async def fake_handle_managed_mcp_tool(**kwargs):+ captured.update(kwargs)+ return mcp_module.CallToolResult(+ content=[TextContent(type="text", text="ok")],+ isError=False,+ )++ with (+ patch.object(+ mcp_module.global_mcp_server_manager,+ "_get_mcp_server_from_tool_name",+ return_value=alias_less_server,+ ),+ patch.object(+ mcp_module,+ "_handle_managed_mcp_tool",+ new=fake_handle_managed_mcp_tool,+ ),+ patch.object(+ mcp_module.MCPRequestHandler,+ "is_tool_allowed",+ return_value=True,+ ),+ patch.object(+ mcp_module.global_mcp_tool_registry,+ "get_tool",+ return_value=None,+ ),+ ):+ await mcp_module.execute_mcp_tool(+ name=f"{server_id}-read_wiki_contents",+ arguments={"repoName": "acme/wiki"},+ allowed_mcp_servers=[alias_less_server],+ start_time=datetime.now(),+ )++ assert captured["server_name"] == server_id+ assert captured["name"] == "read_wiki_contents"++@pytest.mark.asyncioasync def test_execute_mcp_tool_rest_server_id_injects_requested_server_credentials():"""REST server_id must inject the requested server's auth, not a URL-collision peer's."""@@ -6426,6 +6505,8 @@ async def test_execute_mcp_tool_sets_model_in_model_call_details():fake_server.mcp_info = Nonefake_server.server_id = "srv-1"fake_server.server_name = "openapi-petstore"+ fake_server.alias = None+ fake_server.short_prefix = Nonefake_tool = MagicMock()fake_tool.name = "list_pets"@@ -6481,7 +6562,13 @@ async def test_execute_mcp_tool_sets_model_in_model_call_details():@pytest.mark.asyncioasync def test_execute_mcp_tool_rest_unresolved_prefixed_name_routes_to_requested_server():- """A prefixed REST name that resolves to no tool must still dispatch to the server_id."""+ """A prefixed REST name that resolves to no tool must still dispatch to the server_id.++ The prefix here belongs to a different server, so it is not a prefix boundary on the+ routed server and the name travels upstream whole. Stripping it would invoke the routed+ server's similarly named tool instead, which is what the tool_server_mismatch 403 exists+ to prevent when the prefix does resolve.+ """from mcp.types import TextContentfrom litellm.proxy._experimental.mcp_server import server as mcp_module@@ -6553,7 +6640,7 @@ async def test_execute_mcp_tool_rest_unresolved_prefixed_name_routes_to_requeste)assert captured["server_name"] == "rest_target"- assert captured["name"] == "list_things"+ assert captured["name"] == "known_prefix-list_things"routed_server = {requested_server.name: requested_server,@@ -7587,22 +7674,28 @@ async def test_aggregate_listing_reports_per_server_outcomes():working_server = MagicMock()working_server.name = "working_server"working_server.alias = "working"+ working_server.short_prefix = Noneworking_server.allowed_tools = Noneworking_server.disallowed_tools = Noneworking_server.server_id = "working_server"working_server.server_name = "working_server"working_server.auth_type = Noneworking_server.extra_headers = None+ working_server.tool_name_to_display_name = None+ working_server.tool_name_to_description = Nonebroken_server = MagicMock()broken_server.name = "broken_server"broken_server.alias = "broken"+ broken_server.short_prefix = Nonebroken_server.allowed_tools = Nonebroken_server.disallowed_tools = Nonebroken_server.server_id = "broken_server"broken_server.server_name = "broken_server"broken_server.auth_type = Nonebroken_server.extra_headers = None+ broken_server.tool_name_to_display_name = None+ broken_server.tool_name_to_description = Nonemock_manager = MagicMock()mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["working_server", "broken_server"])@@ -7924,3 +8017,139 @@ async def test_post_mcp_call_guardrails_propagate_a_block():user_api_key_auth=None,request_data={},)+++class TestListFiltersHonorThePrefixBoundary:+ """The listing filters compare a published (prefixed) tool name against+ configured entries, so they have to locate the boundary with the server's+ registered prefixes. An alias-less server publishes its UUID server_id as+ the prefix, and that prefix contains the separator, so cutting at the first+ separator drops every tool on the server from the listing.+ """++ SERVER_ID = "117c814c-1a2b-4c4d-8e8f-0a1b2c3d4e5f"++ @staticmethod+ def _alias_less_server(**overrides):+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import MCPServer++ return MCPServer(+ server_id=TestListFiltersHonorThePrefixBoundary.SERVER_ID,+ name=TestListFiltersHonorThePrefixBoundary.SERVER_ID,+ url="http://127.0.0.1:5115/mcp",+ transport=MCPTransport.http,+ **overrides,+ )++ def _published_tools(self, *bare_names: str):+ from mcp.types import Tool as MCPTool++ return [+ MCPTool(name=f"{self.SERVER_ID}-{bare}", description=bare, inputSchema={"type": "object"})+ for bare in bare_names+ ]++ def test_bare_allowlist_entry_keeps_the_published_tool(self):+ from litellm.proxy._experimental.mcp_server.server import (+ filter_tools_by_allowed_tools,+ )++ server = self._alias_less_server(allowed_tools=["read_wiki_contents"])+ tools = self._published_tools("read_wiki_contents", "read_wiki_structure")++ kept = filter_tools_by_allowed_tools(tools, server)++ assert [tool.name for tool in kept] == [f"{self.SERVER_ID}-read_wiki_contents"]++ def test_bare_blocklist_entry_excludes_the_published_tool(self):+ from litellm.proxy._experimental.mcp_server.server import (+ filter_tools_by_allowed_tools,+ )++ server = self._alias_less_server(disallowed_tools=["read_wiki_structure"])+ tools = self._published_tools("read_wiki_contents", "read_wiki_structure")++ kept = filter_tools_by_allowed_tools(tools, server)++ assert [tool.name for tool in kept] == [f"{self.SERVER_ID}-read_wiki_contents"]++ def test_unrelated_entry_does_not_match(self):+ from litellm.proxy._experimental.mcp_server.server import _tool_name_matches++ server = self._alias_less_server()++ assert not _tool_name_matches(f"{self.SERVER_ID}-read_wiki_contents", ["read_wiki_structure"], server)++ def test_match_is_still_case_insensitive(self):+ from litellm.proxy._experimental.mcp_server.server import _tool_name_matches++ server = self._alias_less_server()++ assert _tool_name_matches(f"{self.SERVER_ID}-findPetsByStatus", ["findpetsbystatus"], server)++ def test_alias_form_entry_matches_a_tool_published_under_the_short_prefix(self, monkeypatch):+ # Routing accepts the alias form, so an entry stored before short+ # prefixes were turned on still governs the tool. Matching only the+ # published spelling left it advertised while dispatch refused it.+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import MCPServer+ from litellm.proxy._experimental.mcp_server.server import _tool_name_matches++ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = MCPServer(+ server_id=self.SERVER_ID,+ name="deepwiki_cfg",+ alias="deepwiki_cfg",+ short_prefix="eiG",+ url="http://127.0.0.1:5115/mcp",+ transport=MCPTransport.http,+ )++ assert _tool_name_matches("eiG-read_wiki_contents", ["deepwiki_cfg-read_wiki_contents"], server)++ def test_discovery_hides_exactly_what_dispatch_refuses(self, monkeypatch):+ """Both halves of one decision, driven through both production paths.++ A spelling the blocklist enforces but the filter misses leaves a blocked+ tool advertised; the reverse hides a tool that would have been callable.+ """+ from mcp.types import Tool as MCPTool++ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ MCPServer,+ MCPServerManager,+ )+ from litellm.proxy._experimental.mcp_server.server import (+ filter_tools_by_allowed_tools,+ )++ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")++ def _server(**overrides):+ return MCPServer(+ server_id=self.SERVER_ID,+ name="deepwiki_prod",+ alias="deepwiki",+ server_name="deepwiki_prod",+ short_prefix="eiG",+ url="http://127.0.0.1:5115/mcp",+ transport=MCPTransport.http,+ **overrides,+ )++ manager = MCPServerManager()+ manager._create_prefixed_tools(+ [MCPTool(name="read_wiki_contents", description="", inputSchema={"type": "object"})],+ _server(),+ )+ registered = sorted(manager.tool_name_to_mcp_server_name_mapping)+ assert len(registered) > 1++ published = MCPTool(name="eiG-read_wiki_contents", description="", inputSchema={"type": "object"})+ for spelling in registered:+ server = _server(disallowed_tools=[spelling])++ refused = not manager.check_allowed_or_banned_tools("read_wiki_contents", server)+ hidden = filter_tools_by_allowed_tools([published], server) == []++ assert refused, spelling+ assert hidden, spellingdiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.pyindex 8a8dea0ba28..2977f13caf1 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py@@ -9189,3 +9189,471 @@ class TestDiscoveryFailureLogging:assert "typo_row" in caplog.textassert "authorization_url, token_url" in caplog.textassert "unresolved" in caplog.text+++def _unrestricted_auth() -> MagicMock:+ """A caller with no object_permission, so only server-level checks apply."""+ user_api_key_auth = MagicMock()+ user_api_key_auth.object_permission = None+ user_api_key_auth.object_permission_id = None+ return user_api_key_auth+++def _permissive_proxy_logging() -> MagicMock:+ proxy_logging_obj = MagicMock()+ proxy_logging_obj._create_mcp_request_object_from_kwargs = MagicMock(return_value={})+ proxy_logging_obj._convert_mcp_to_llm_format = MagicMock(return_value={})+ proxy_logging_obj.pre_call_hook = AsyncMock(return_value={})+ return proxy_logging_obj+++ALIAS_LESS_SERVER_ID = "117c814c-1a2b-4c4d-8e8f-0a1b2c3d4e5f"+++class TestServerToolListsHonorThePrefixBoundary:+ """The server-level allowed_tools / disallowed_tools / allowed_params checks+ receive a BARE tool name. Every caller resolves the prefix boundary before+ dispatch (``server.py``'s ``original_tool_name``, the Responses handler's+ ``sanitized_tool_name``), and ``call_tool`` hands that same value to the+ upstream client verbatim, which only works because it carries no prefix.++ Stored entries may also carry a prefix, and routing accepts *every* prefix+ from ``iter_known_server_prefixes`` (short ID, alias, server_name,+ server_id), so enforcement derives that whole set via+ ``iter_known_tool_name_spellings``. Rebuilding a single comparand as+ ``f"{server.name}-{tool_name}"`` used a field the prefix chain never reads+ (``get_server_prefix`` is short_prefix, then alias, then server_name, then+ server_id) and hardcoded the separator; deriving only ``get_server_prefix``+ covers just the currently published spelling. Either way the check answers+ for fewer spellings than are reachable, and on the blocklist arm that is a+ fail-open.+ """++ async def _run_check(self, server: MCPServer, name: str, arguments: dict[str, Any] | None = None) -> None:+ await MCPServerManager().pre_call_tool_check(+ name=name,+ arguments=arguments if arguments is not None else {},+ server_name=server.name,+ user_api_key_auth=_unrestricted_auth(),+ proxy_logging_obj=_permissive_proxy_logging(),+ server=server,+ )++ @staticmethod+ def _aliased_server(**overrides: Any) -> MCPServer:+ return MCPServer(+ server_id="dd7f2b9e-2c4a-4f1b-9e0a-8d3c6b5a4f21",+ name="petstore_prod",+ alias="petstore",+ server_name="petstore_prod",+ url="https://petstore.example.com/mcp",+ transport=MCPTransport.http,+ **overrides,+ )++ @staticmethod+ def _alias_less_server(**overrides: Any) -> MCPServer:+ # No alias and no server_name, so the published prefix is the UUID+ # server_id, which itself contains the prefix separator.+ return MCPServer(+ server_id=ALIAS_LESS_SERVER_ID,+ name=ALIAS_LESS_SERVER_ID,+ url="https://wiki.example.com/mcp",+ transport=MCPTransport.http,+ **overrides,+ )++ @pytest.mark.asyncio+ async def test_allowlist_entry_prefixed_with_the_alias_matches_a_bare_call(self):+ # The dashboard shows tools under the published prefix, so admins store+ # "petstore-getpetbyid"; the display name "petstore_prod" is not it.+ server = self._aliased_server(allowed_tools=["petstore-getpetbyid"])++ await self._run_check(server, "getpetbyid")++ @pytest.mark.asyncio+ async def test_bare_allowlist_entry_matches_on_an_alias_less_server(self):+ server = self._alias_less_server(allowed_tools=["read_wiki_contents"])++ await self._run_check(server, "read_wiki_contents")++ @pytest.mark.asyncio+ async def test_wire_form_allowlist_entry_matches_on_an_alias_less_server(self):+ # The published prefix is the UUID server_id, so it contains the+ # separator; the derived wire form has to reproduce it whole.+ server = self._alias_less_server(allowed_tools=[f"{ALIAS_LESS_SERVER_ID}-read_wiki_contents"])++ await self._run_check(server, "read_wiki_contents")++ @pytest.mark.asyncio+ async def test_wire_form_entry_matches_a_native_name_that_opens_with_the_prefix(self):+ # "petstore-getpetbyid" is a real upstream tool name here, so its wire+ # form is "petstore-petstore-getpetbyid". Stripping the stored entry+ # instead of deriving the wire form cut a boundary the caller had already+ # consumed, leaving asymmetric operands that denied a permitted call.+ server = self._aliased_server(allowed_tools=["petstore-petstore-getpetbyid"])++ await self._run_check(server, "petstore-getpetbyid")++ @pytest.mark.asyncio+ async def test_wire_form_blocklist_entry_blocks_a_native_name_that_opens_with_the_prefix(self):+ server = self._aliased_server(disallowed_tools=["petstore-petstore-getpetbyid"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "petstore-getpetbyid")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_wire_form_blocklist_entry_blocks_under_the_short_prefix_mode(self, monkeypatch):+ # short_prefix wins in get_server_prefix but is never server.name, so the+ # hand-built comparand could not match a stored wire-form entry and the+ # blocklisted tool stayed callable.+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._aliased_server(short_prefix="F3X", disallowed_tools=["F3X-deletepet"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "deletepet")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_alias_form_blocklist_entry_still_blocks_under_the_short_prefix_mode(self, monkeypatch):+ # Turning short prefixes on republishes every tool under the short ID,+ # but routing still resolves the alias form, so an entry an admin stored+ # before the flip stays reachable and has to stay enforced. Deriving only+ # the published spelling silently stops honoring it: a fail-open on a+ # config nobody edited.+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._aliased_server(short_prefix="F3X", disallowed_tools=["petstore-deletepet"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "deletepet")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_alias_form_allowlist_entry_still_matches_under_the_short_prefix_mode(self, monkeypatch):+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._aliased_server(short_prefix="F3X", allowed_tools=["petstore-getpetbyid"])++ await self._run_check(server, "getpetbyid")++ @pytest.mark.asyncio+ async def test_server_name_form_blocklist_entry_still_blocks_under_the_short_prefix_mode(self, monkeypatch):+ # server_name sits third in the prefix chain, so it is published only+ # when alias and short_prefix are both absent, yet routing accepts it+ # regardless.+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._aliased_server(short_prefix="F3X", disallowed_tools=["petstore_prod-deletepet"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "deletepet")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_raw_server_id_form_blocklist_entry_still_blocks_under_the_short_prefix_mode(self, monkeypatch):+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._alias_less_server(disallowed_tools=[f"{ALIAS_LESS_SERVER_ID}-read_wiki_contents"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "read_wiki_contents")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_allowed_params_keyed_by_the_alias_form_are_enforced_under_the_short_prefix_mode(self, monkeypatch):+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._aliased_server(short_prefix="F3X", allowed_params={"petstore-getpetbyid": ["petid"]})++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(+ server,+ "getpetbyid",+ arguments={"petid": "7", "include_internal": "true"},+ )++ assert exc_info.value.status_code == 403+ assert "include_internal" in exc_info.value.detail["error"]++ @pytest.mark.asyncio+ async def test_foreign_prefix_entry_does_not_match_under_the_short_prefix_mode(self, monkeypatch):+ # Honoring every known prefix must not become "honor any prefix": the+ # widened set is this server's spellings only.+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true")+ server = self._aliased_server(short_prefix="F3X", allowed_tools=["other_server-getpetbyid"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "getpetbyid")++ assert exc_info.value.status_code == 403++ @pytest.mark.parametrize("short_prefix_mode", [False, True])+ @pytest.mark.asyncio+ async def test_every_spelling_routing_registers_is_also_enforced(self, monkeypatch, short_prefix_mode):+ """The invariant, driven through production code on both sides.++ ``_create_prefixed_tools`` decides which spellings reach dispatch, so+ every key it registers has to be a spelling the blocklist can refuse.+ Any key routing accepts but enforcement misses is a callable blocked+ tool.+ """+ monkeypatch.setenv("LITELLM_USE_SHORT_MCP_TOOL_PREFIX", "true" if short_prefix_mode else "false")+ shape = self._aliased_server(short_prefix="F3X")++ manager = MCPServerManager()+ manager._create_prefixed_tools([MCPTool(name="deletepet", description="", inputSchema={})], shape)+ registered = sorted(manager.tool_name_to_mcp_server_name_mapping)+ assert len(registered) > 1++ for spelling in registered:+ server = self._aliased_server(short_prefix="F3X", disallowed_tools=[spelling])+ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "deletepet")+ assert exc_info.value.status_code == 403, spelling++ @pytest.mark.asyncio+ async def test_wire_form_allowlist_entry_follows_a_non_default_separator(self):+ from litellm.proxy._experimental.mcp_server import utils as mcp_utils++ server = self._aliased_server(allowed_tools=["petstore__getpetbyid"])++ with patch.object(mcp_utils, "MCP_TOOL_PREFIX_SEPARATOR", "__"):+ await self._run_check(server, "getpetbyid")++ @pytest.mark.asyncio+ async def test_tool_outside_the_allowlist_is_still_denied(self):+ server = self._aliased_server(allowed_tools=["petstore-getpetbyid"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "deletepet")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_allowlist_entry_prefixed_for_another_server_does_not_match(self):+ # Reducing both sides must not widen the allowlist across servers: a+ # foreign prefix is not one of this server's known prefixes, so the+ # entry keeps it and never collapses onto a bare name.+ server = self._aliased_server(allowed_tools=["other_server-getpetbyid"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "getpetbyid")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_prefixed_disallowed_entry_blocks_a_bare_call(self):+ # Fail-open regression: the blocklist arm answered "not banned" whenever+ # the stored entry carried a prefix it failed to reconstruct.+ server = self._aliased_server(disallowed_tools=["petstore-deletepet"])++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "deletepet")++ assert exc_info.value.status_code == 403++ @pytest.mark.asyncio+ async def test_tool_outside_the_blocklist_is_still_allowed(self):+ server = self._aliased_server(disallowed_tools=["petstore-deletepet"])++ await self._run_check(server, "getpetbyid")++ @pytest.mark.asyncio+ async def test_allowed_params_are_enforced_for_a_bare_key(self):+ server = self._alias_less_server(allowed_params={"read_wiki_contents": ["repo"]})++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(+ server,+ "read_wiki_contents",+ arguments={"repo": "acme/wiki", "internal_only": "true"},+ )++ assert exc_info.value.status_code == 403+ assert "internal_only" in exc_info.value.detail["error"]++ @pytest.mark.asyncio+ async def test_allowed_params_are_enforced_for_a_wire_form_key(self):+ # A key stored under the published prefix matched nothing, so the lookup+ # returned None and the check silently allowed every parameter instead of+ # enforcing the configured list.+ server = self._alias_less_server(allowed_params={f"{ALIAS_LESS_SERVER_ID}-read_wiki_contents": ["repo"]})++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(+ server,+ "read_wiki_contents",+ arguments={"repo": "acme/wiki", "internal_only": "true"},+ )++ assert exc_info.value.status_code == 403+ assert "internal_only" in exc_info.value.detail["error"]++ @pytest.mark.asyncio+ async def test_allowed_params_still_accept_the_configured_parameters(self):+ server = self._alias_less_server(allowed_params={f"{ALIAS_LESS_SERVER_ID}-read_wiki_contents": ["repo"]})++ await self._run_check(server, "read_wiki_contents", arguments={"repo": "acme/wiki"})++ @pytest.mark.asyncio+ async def test_allowed_params_are_enforced_for_a_native_name_that_opens_with_the_prefix(self):+ server = self._aliased_server(allowed_params={"petstore-petstore-getpetbyid": ["petid"]})++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(+ server,+ "petstore-getpetbyid",+ arguments={"petid": "7", "include_internal": "true"},+ )++ assert exc_info.value.status_code == 403+ assert "include_internal" in exc_info.value.detail["error"]++ @pytest.mark.asyncio+ async def test_an_explicitly_empty_allowed_params_list_refuses_every_parameter(self):+ server = self._alias_less_server(allowed_params={"read_wiki_contents": []})++ with pytest.raises(HTTPException) as exc_info:+ await self._run_check(server, "read_wiki_contents", arguments={"repo": "acme/wiki"})++ assert exc_info.value.status_code == 403+ assert "repo" in exc_info.value.detail["error"]++ @pytest.mark.asyncio+ async def test_an_explicitly_empty_allowed_params_list_still_permits_an_argument_free_call(self):+ server = self._alias_less_server(allowed_params={"read_wiki_contents": []})++ await self._run_check(server, "read_wiki_contents", arguments={})+++class TestOpenAPIRegistryKeyMatchesRegistration:+ """OpenAPI tools are registered under ``add_server_prefix_to_name(base, get_server_prefix(server))``,+ so the dispatch lookup has to build its key the same way from the bare name ``call_tool``+ hands it. Rebuilding it as ``f"{server.name}-{bare_name}"`` used a field the prefix chain+ never reads and hardcoded the separator, so every call on a server whose published prefix+ differs from its display name failed with "not found in registry" instead of dispatching.+ """++ @staticmethod+ def _register(server: MCPServer, base_tool_name: str) -> str:+ from litellm.proxy._experimental.mcp_server.utils import (+ add_server_prefix_to_name,+ get_server_prefix,+ )++ return add_server_prefix_to_name(base_tool_name, get_server_prefix(server))++ async def _call(self, server: MCPServer, registered_key: str, bare_tool_name: str) -> CallToolResult:+ from litellm.proxy._experimental.mcp_server.tool_registry import (+ global_mcp_tool_registry,+ )++ async def handler(**kwargs: Any) -> str:+ return "dispatched"++ tool = MagicMock()+ tool.handler = handler++ with patch.dict(global_mcp_tool_registry.tools, {registered_key: tool}, clear=True):+ return await MCPServerManager()._call_openapi_tool_handler(server, bare_tool_name, {})++ @pytest.mark.asyncio+ async def test_aliased_server_dispatches_when_name_differs_from_published_prefix(self):+ server = MCPServer(+ server_id="dd7f2b9e-2c4a-4f1b-9e0a-8d3c6b5a4f21",+ name="petstore_prod",+ alias="petstore",+ server_name="petstore_prod",+ url=None,+ transport=MCPTransport.http,+ spec_path="https://example.com/petstore.yaml",+ )+ registered_key = self._register(server, "list_pets")+ assert registered_key == "petstore-list_pets"++ result = await self._call(server, registered_key, "list_pets")++ assert result.isError is False+ assert result.content[0].text == "dispatched"++ @pytest.mark.asyncio+ async def test_alias_less_server_dispatches_when_the_prefix_contains_the_separator(self):+ server = MCPServer(+ server_id=ALIAS_LESS_SERVER_ID,+ name=ALIAS_LESS_SERVER_ID,+ url=None,+ transport=MCPTransport.http,+ spec_path="https://example.com/wiki.yaml",+ )+ registered_key = self._register(server, "read_wiki_contents")+ assert registered_key == f"{ALIAS_LESS_SERVER_ID}-read_wiki_contents"++ result = await self._call(server, registered_key, "read_wiki_contents")++ assert result.isError is False+ assert result.content[0].text == "dispatched"++ @pytest.mark.asyncio+ async def test_dispatch_keeps_a_native_name_that_opens_with_the_prefix(self):+ # Registration prefixes the upstream name whatever it looks like, so+ # "petstore-list_pets" is registered as "petstore-petstore-list_pets".+ # Stripping the bare name again before rebuilding the key cut that+ # leading segment back off and the lookup missed.+ server = MCPServer(+ server_id="dd7f2b9e-2c4a-4f1b-9e0a-8d3c6b5a4f21",+ name="petstore_prod",+ alias="petstore",+ server_name="petstore_prod",+ url=None,+ transport=MCPTransport.http,+ spec_path="https://example.com/petstore.yaml",+ )+ registered_key = self._register(server, "petstore-list_pets")+ assert registered_key == "petstore-petstore-list_pets"++ result = await self._call(server, registered_key, "petstore-list_pets")++ assert result.isError is False+ assert result.content[0].text == "dispatched"++ @pytest.mark.asyncio+ async def test_dispatch_follows_a_non_default_prefix_separator(self):+ from litellm.proxy._experimental.mcp_server import utils as mcp_utils++ server = MCPServer(+ server_id="dd7f2b9e-2c4a-4f1b-9e0a-8d3c6b5a4f21",+ name="petstore_prod",+ alias="petstore",+ server_name="petstore_prod",+ url=None,+ transport=MCPTransport.http,+ spec_path="https://example.com/petstore.yaml",+ )++ with patch.object(mcp_utils, "MCP_TOOL_PREFIX_SEPARATOR", "__"):+ registered_key = self._register(server, "list_pets")+ assert registered_key == "petstore__list_pets"++ result = await self._call(server, registered_key, "list_pets")++ assert result.isError is False+ assert result.content[0].text == "dispatched"++ @pytest.mark.asyncio+ async def test_unregistered_tool_is_still_reported_missing(self):+ server = MCPServer(+ server_id="dd7f2b9e-2c4a-4f1b-9e0a-8d3c6b5a4f21",+ name="petstore_prod",+ alias="petstore",+ server_name="petstore_prod",+ url=None,+ transport=MCPTransport.http,+ spec_path="https://example.com/petstore.yaml",+ )++ result = await self._call(server, "petstore-list_pets", "delete_pet")++ assert result.isError is True+ assert "not found in registry" in result.content[0].textdiff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.pyindex 1e4349c3143..c4b3c7f5f67 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_tool_auth.py@@ -32,6 +32,8 @@ async def test_openapi_local_tool_runs_pre_call_tool_check():fake_server.mcp_info = Nonefake_server.server_id = "srv-1"fake_server.server_name = "openapi-petstore"+ fake_server.alias = None+ fake_server.short_prefix = Nonefake_tool = MagicMock()fake_tool.name = "list_pets"@@ -111,6 +113,8 @@ async def test_openapi_local_tool_blocked_when_pre_call_check_raises():fake_server.mcp_info = Nonefake_server.server_id = "srv-1"fake_server.server_name = "openapi-petstore"+ fake_server.alias = None+ fake_server.short_prefix = Nonefake_tool = MagicMock()fake_tool.name = "delete_pet"diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_short_mcp_tool_prefix.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_short_mcp_tool_prefix.pyindex 662ef585c6b..6e3ac014840 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_short_mcp_tool_prefix.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_short_mcp_tool_prefix.py@@ -20,7 +20,9 @@ from litellm.proxy._experimental.mcp_server.utils import (compute_short_server_prefix,get_server_prefix,is_short_mcp_tool_prefix_enabled,+ is_tool_name_prefixed,iter_known_server_prefixes,+ match_known_server_prefix,strip_known_server_prefix,)from litellm.types.mcp_server.mcp_server_manager import MCPServer@@ -195,6 +197,70 @@ class TestStripKnownServerPrefix:assert strip_known_server_prefix("svc-tool", None) == "tool"+# ---------------------------------------------------------------------------+# match_known_server_prefix — the shared boundary primitive+# ---------------------------------------------------------------------------+++class TestMatchKnownServerPrefix:+ """Locates the boundary by matching registered prefixes instead of cutting+ at the first separator, preferring the longest candidate so a prefix that+ itself contains the separator still wins."""++ def test_returns_matched_prefix_and_bare_name(self):+ assert match_known_server_prefix("deepwiki-contents", ["deepwiki"]) == (+ "deepwiki",+ "contents",+ )++ def test_returns_none_when_no_candidate_matches(self):+ assert match_known_server_prefix("contents", ["deepwiki"]) is None++ def test_separator_must_follow_the_prefix(self):+ assert match_known_server_prefix("deepwikicontents", ["deepwiki"]) is None++ def test_uuid_prefix_survives_its_own_separators(self):+ server_id = "117c814c-1a2b-3c4d-9e8f"+ assert match_known_server_prefix(f"{server_id}-contents", [server_id]) == (+ server_id,+ "contents",+ )++ def test_longest_candidate_wins_over_leading_segment(self):+ # "svc" is a registered prefix in its own right and also the leading+ # segment of "svc-prod". A first-separator split hands the tool to+ # "svc" with a bare name of "prod-run", attributing it to the wrong+ # server; longest-match keeps it on "svc-prod".+ assert match_known_server_prefix("svc-prod-run", ["svc", "svc-prod"]) == (+ "svc-prod",+ "run",+ )++ def test_candidates_are_normalised_before_matching(self):+ assert match_known_server_prefix("my_server-run", ["my server"]) == (+ "my_server",+ "run",+ )++ def test_empty_candidate_never_matches_a_leading_separator(self):+ assert match_known_server_prefix("-run", [""]) is None+++class TestIsToolNamePrefixedBoundary:+ """The known-prefix gate decides which branch the call path takes, so it has+ to agree with the prefix the list path actually emitted."""++ def test_uuid_prefix_is_recognised(self):+ server_id = "117c814c-1a2b-3c4d-9e8f"+ assert is_tool_name_prefixed(f"{server_id}-contents", known_server_prefixes={server_id})++ def test_unrelated_hyphenated_tool_is_still_not_prefixed(self):+ # Negative control: an upstream tool whose own name contains the+ # separator must not start reading as prefixed just because the gate+ # got more permissive about where the boundary can fall.+ assert not is_tool_name_prefixed("text-to-speech", known_server_prefixes={"deepwiki"})++# ---------------------------------------------------------------------------# Manager-level behaviour: list + reverse-lookup# ---------------------------------------------------------------------------