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): resolve toolset tools by the server's known prefix (#31254)
tin-berrif426912ba141
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 4e8e04245c2..8606a18cac1 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -82,6 +82,7 @@ from litellm.proxy._experimental.mcp_server.utils import (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 (@@ -1481,7 +1482,8 @@ class MCPServerManager:for toolset in toolsets:for tool in toolset.tools:raw_name = tool["tool_name"]- unprefixed, _ = split_server_prefix_from_name(raw_name)+ server = self.get_mcp_server_by_id(tool["server_id"])+ unprefixed = strip_known_server_prefix(raw_name, server)tool_permissions.setdefault(tool["server_id"], [])if unprefixed not in tool_permissions[tool["server_id"]]:tool_permissions[tool["server_id"]].append(unprefixed)diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex e891425274f..b48263703a0 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -300,6 +300,7 @@ if MCP_AVAILABLE:is_tool_name_prefixed,normalize_server_name,split_server_prefix_from_name,+ strip_known_server_prefix,)######################################################@@ -2109,20 +2110,18 @@ if MCP_AVAILABLE:server_id=server_id,user_api_key_auth=user_api_key_auth,)- if allowed_tool_names is not None:- # Strip prefix from tool names before comparing- # Tools are stored in DB without prefix, but come from MCP server with prefix- filtered_tools = []- for t in tools:- # Get tool name without server prefix- unprefixed_tool_name, _ = split_server_prefix_from_name(t.name)- if unprefixed_tool_name in allowed_tool_names:- filtered_tools.append(t)- else:- # No restrictions, return all tools- filtered_tools = tools+ if allowed_tool_names is None:+ return tools- return filtered_tools+ # Tools arrive prefixed with the server's own prefix; strip exactly that+ # prefix (resolved from the server) rather than the first separator, so a+ # prefix containing the separator still reduces to the stored bare name.+ server = global_mcp_server_manager.get_mcp_server_by_id(server_id)+ return [+ t+ for t in tools+ if strip_known_server_prefix(t.name, server) in allowed_tool_names+ ]async def _merge_toolset_permissions(user_api_key_auth: Optional[UserAPIKeyAuth],diff --git a/litellm/proxy/_experimental/mcp_server/utils.py b/litellm/proxy/_experimental/mcp_server/utils.pyindex b0141d3207c..3418417a8f8 100644--- a/litellm/proxy/_experimental/mcp_server/utils.py+++ b/litellm/proxy/_experimental/mcp_server/utils.py@@ -332,6 +332,30 @@ def split_server_prefix_from_name(prefixed_name: str) -> Tuple[str, str]:return prefixed_name, ""+def strip_known_server_prefix(name: str, server: Optional[Any]) -> str:+ """Strip ``server``'s registered prefix from a prefixed tool/resource name.++ Unlike :func:`split_server_prefix_from_name`, which guesses the boundary at+ the first separator, this removes exactly ``{known_prefix}{separator}`` for+ one of the server's actual registered prefixes. It therefore stays correct+ when a prefix itself contains the separator (e.g. the UUID ``server_id``+ used as the fallback prefix when a server has no alias, or a legacy+ hyphenated alias), where the first-separator split would cut inside the+ prefix and never match the stored bare tool name.++ Returns ``name`` unchanged when ``server`` is known but none of its prefixes+ match (the name is already unprefixed). Falls back to the legacy split only+ when ``server`` is ``None``.+ """+ 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++def is_tool_name_prefixed(tool_name: str,known_server_prefixes: Optional[set] = None,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 f44552c2943..ca326d197ae 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@@ -3313,6 +3313,7 @@ async def test_list_tools_filters_by_key_team_permissions():server.server_id = "server1"server.name = "Test Server"server.alias = "test"+ server.short_prefix = Noneserver.allowed_tools = Noneserver.disallowed_tools = Noneserver.server_name = "server1"@@ -3423,6 +3424,7 @@ async def test_list_tools_with_team_tool_permissions_inheritance():server.server_id = "server1"server.name = "Test Server"server.alias = "test"+ server.short_prefix = Noneserver.allowed_tools = Noneserver.disallowed_tools = Noneserver.server_name = "server1"@@ -3519,6 +3521,7 @@ async def test_list_tools_with_no_tool_permissions_shows_all():server.server_id = "server1"server.name = "Test Server"server.alias = "test"+ server.short_prefix = Noneserver.allowed_tools = Noneserver.disallowed_tools = Noneserver.server_name = "server1"@@ -3620,7 +3623,9 @@ async def test_list_tools_strips_prefix_when_matching_permissions():server = MagicMock()server.server_id = "gitmcp_server"server.name = "GITMCP"- server.alias = "gitmcp"+ server.alias = "GITMCP"+ server.short_prefix = None+ server.server_name = "GITMCP"server.allowed_tools = Noneserver.disallowed_tools = Nonediff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_toolset_scope.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_toolset_scope.pyindex b41cdfb1576..e7709165119 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_toolset_scope.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_toolset_scope.py@@ -235,6 +235,132 @@ class TestFetchMCPToolsetsAccess:mock_list.assert_called_once_with(mock_client, toolset_ids=["ts-1", "ts-2"])+class TestToolsetPrefixResolution:+ """Regression for LIT-3419.++ Toolsets store bare tool names; the live tools come back prefixed with the+ server's own prefix. Reconciling them must strip exactly that prefix, not+ chop at the first separator, otherwise tools on a server whose prefix+ contains the separator (a hyphenated alias, or the UUID server_id used when+ a server has no alias) are silently dropped from the toolset.+ """++ # alias, server_name, server_id; the clean-alias row worked before the fix,+ # the hyphenated-alias and no-alias (UUID prefix) rows did not.+ PREFIX_CASES = [+ ("deepwiki", None, "srv-clean"),+ ("deep-wiki", None, "srv-hyphen"),+ (None, None, "117c814c-1a2b-3c4d-9e8f"),+ ]++ @staticmethod+ def _server(alias, server_name, server_id):+ from types import SimpleNamespace++ return SimpleNamespace(+ alias=alias,+ server_name=server_name,+ server_id=server_id,+ short_prefix=None,+ )++ @pytest.mark.asyncio+ @pytest.mark.parametrize("alias, server_name, server_id", PREFIX_CASES)+ async def test_filter_keeps_tools_when_prefix_contains_separator(+ self, alias, server_name, server_id+ ):+ from mcp.types import Tool as MCPTool++ from litellm.proxy._experimental.mcp_server.server import (+ filter_tools_by_key_team_permissions,+ )+ from litellm.proxy._experimental.mcp_server.utils import (+ add_server_prefix_to_name,+ get_server_prefix,+ )++ server = self._server(alias, server_name, server_id)+ prefix = get_server_prefix(server)+ live_tools = [+ MCPTool(+ name=add_server_prefix_to_name(name, prefix),+ inputSchema={"type": "object"},+ )+ for name in ("read_wiki_contents", "read_wiki_structure", "not_granted")+ ]+ # Bare names as stored in the toolset / resolved into the permission dict.+ allowed = ["read_wiki_contents", "read_wiki_structure"]++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server."+ "MCPRequestHandler.get_allowed_tools_for_server",+ new=AsyncMock(return_value=allowed),+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server."+ "global_mcp_server_manager.get_mcp_server_by_id",+ return_value=server,+ ),+ ):+ result = await filter_tools_by_key_team_permissions(+ tools=live_tools,+ server_id=server_id,+ user_api_key_auth=_make_auth(),+ )++ assert sorted(t.name for t in result) == sorted(+ add_server_prefix_to_name(name, prefix)+ for name in ("read_wiki_contents", "read_wiki_structure")+ )++ @pytest.mark.asyncio+ @pytest.mark.parametrize("alias, server_name, server_id", PREFIX_CASES)+ async def test_resolve_unprefixes_stored_names_with_separator_prefix(+ self, alias, server_name, server_id+ ):+ from types import SimpleNamespace++ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )+ from litellm.proxy._experimental.mcp_server.utils import (+ add_server_prefix_to_name,+ get_server_prefix,+ )++ server = self._server(alias, server_name, server_id)+ # A caller (e.g. the management API) may persist already-prefixed names;+ # resolution must reduce them to the true bare name regardless of prefix.+ stored = add_server_prefix_to_name(+ "read_wiki_contents", get_server_prefix(server)+ )+ toolset = SimpleNamespace(tools=[{"server_id": server_id, "tool_name": stored}])+ cache = MagicMock(+ async_get_cache=AsyncMock(return_value=None),+ async_set_cache=AsyncMock(),+ )++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager."+ "global_mcp_server_manager.get_mcp_server_by_id",+ return_value=server,+ ),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.user_api_key_cache", cache),+ patch(+ "litellm.proxy._experimental.mcp_server.toolset_db.list_mcp_toolsets",+ new=AsyncMock(return_value=[toolset]),+ ),+ ):+ result = await global_mcp_server_manager.resolve_toolset_tool_permissions(+ toolset_ids=["ts-1"]+ )++ assert result == {server_id: ["read_wiki_contents"]}++class TestMCPActiveToolsetContextVar:"""Tests for _mcp_active_toolset_id ContextVar — clients cannot inject it."""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 bf90e9ebef6..662ef585c6b 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@@ -21,6 +21,7 @@ from litellm.proxy._experimental.mcp_server.utils import (get_server_prefix,is_short_mcp_tool_prefix_enabled,iter_known_server_prefixes,+ strip_known_server_prefix,)from litellm.types.mcp_server.mcp_server_manager import MCPServer@@ -143,6 +144,57 @@ class TestIterKnownServerPrefixes:assert compute_short_server_prefix(server.server_id) in prefixes+# ---------------------------------------------------------------------------+# strip_known_server_prefix — inverse of add_server_prefix_to_name (LIT-3419)+# ---------------------------------------------------------------------------+++class TestStripKnownServerPrefix:+ """Removes a server's exact known prefix, even when the prefix itself+ contains the separator (hyphenated alias or UUID server_id fallback) where+ a first-separator split would cut inside the prefix and mangle the name."""++ def test_clean_prefix_round_trips(self):+ server = _make_server(alias="deepwiki", server_name="deepwiki")+ live = add_server_prefix_to_name(+ "read_wiki_contents", get_server_prefix(server)+ )+ assert strip_known_server_prefix(live, server) == "read_wiki_contents"++ def test_hyphenated_alias_does_not_mangle(self):+ server = _make_server(alias="deep-wiki", server_name="deep-wiki")+ assert get_server_prefix(server) == "deep-wiki"+ # the first-separator split would yield "wiki-read_wiki_contents"+ assert (+ strip_known_server_prefix("deep-wiki-read_wiki_contents", server)+ == "read_wiki_contents"+ )++ def test_uuid_fallback_prefix_does_not_mangle(self):+ server = MCPServer(+ server_id="117c814c-1a2b-3c4d-9e8f",+ name="deepwiki",+ alias=None,+ server_name=None,+ transport="http",+ )+ live = add_server_prefix_to_name(+ "read_wiki_contents", get_server_prefix(server)+ )+ assert live.startswith("117c814c-1a2b-3c4d-9e8f-")+ assert strip_known_server_prefix(live, server) == "read_wiki_contents"++ def test_unprefixed_name_returned_unchanged(self):+ server = _make_server(alias="deep-wiki", server_name="deep-wiki")+ assert (+ strip_known_server_prefix("read_wiki_contents", server)+ == "read_wiki_contents"+ )++ def test_none_server_falls_back_to_first_separator_split(self):+ assert strip_known_server_prefix("svc-tool", None) == "tool"++# ---------------------------------------------------------------------------# Manager-level behaviour: list + reverse-lookup# ---------------------------------------------------------------------------diff --git a/ui/litellm-dashboard/src/components/mcp_tools/MCPToolsetsTab.tsx b/ui/litellm-dashboard/src/components/mcp_tools/MCPToolsetsTab.tsxindex 6d0ef76b11b..1a05edf7c2c 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/MCPToolsetsTab.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/MCPToolsetsTab.tsx@@ -12,6 +12,17 @@ import { MCPToolset, MCPToolsetTool } from "./types";const { Text: AntdText } = Typography;+// Display-only. Toolsets persist {server_id, bare tool_name}; the gateway serves+// each tool prefixed as "{server-prefix}-{tool}". Render that qualified form so+// the same tool name on different servers stays distinguishable. This mirrors the+// backend default MCP_TOOL_PREFIX_SEPARATOR; overriding that env var only changes+// this cosmetic label, never what is stored or how tools are matched.+const MCP_TOOL_PREFIX_SEPARATOR = "-";++function displayToolName(serverPrefix: string | undefined, toolName: string): string {+ return serverPrefix ? `${serverPrefix}${MCP_TOOL_PREFIX_SEPARATOR}${toolName}` : toolName;+}+interface MCPToolsetsTabProps {accessToken: string | null;userRole: string | null;@@ -138,6 +149,10 @@ function CreateToolsetModal({ open, onClose, onSave, accessToken, initialToolsetconst [saving, setSaving] = useState(false);const [serverSearch, setServerSearch] = useState("");const { data: mcpServers = [] } = useMCPServers();+ const serverPrefixById = React.useMemo(+ () => new Map(mcpServers.map((s) => [s.server_id, s.alias || s.server_name || s.server_id])),+ [mcpServers],+ );React.useEffect(() => {if (open) {@@ -254,7 +269,7 @@ function CreateToolsetModal({ open, onClose, onSave, accessToken, initialToolset><div className="min-w-0 text-left"><span className="text-xs font-medium text-purple-800 group-hover:text-red-600 truncate block">- {tool.tool_name}+ {displayToolName(serverPrefixById.get(tool.server_id), tool.tool_name)}</span><span className="text-[10px] text-purple-400 truncate block">{tool.server_id.slice(0, 8)}…</span></div>@@ -282,8 +297,9 @@ function toolsetColumns(isAdmin: boolean,onEdit: (t: MCPToolset) => void,onDelete: (id: string) => void,- proxyBaseUrl: string,+ serverPrefixById: Map<string, string>,): ColumnDef<MCPToolset>[] {+ const proxyBaseUrl = getProxyBaseUrl();return [{header: "Toolset ID",@@ -334,7 +350,7 @@ function toolsetColumns(key={i}className="inline-flex items-center px-1.5 py-0.5 rounded bg-purple-50 border border-purple-200 text-purple-700 text-xs">- {t.tool_name}+ {displayToolName(serverPrefixById.get(t.server_id), t.tool_name)}</span>))}{tools.length > 4 && <span className="text-xs text-gray-400 self-center">+{tools.length - 4} more</span>}@@ -431,6 +447,7 @@ function ToolsetUsageGuide() {export function MCPToolsetsTab({ accessToken, userRole }: MCPToolsetsTabProps) {const queryClient = useQueryClient();const { data: toolsets = [], isLoading } = useMCPToolsets();+ const { data: mcpServers = [] } = useMCPServers();const [createOpen, setCreateOpen] = useState(false);const [editToolset, setEditToolset] = useState<MCPToolset | null>(null);const [deleteId, setDeleteId] = useState<string | null>(null);@@ -466,8 +483,11 @@ export function MCPToolsetsTab({ accessToken, userRole }: MCPToolsetsTabProps) {}};- const proxyBaseUrl = getProxyBaseUrl();- const columns = toolsetColumns(isAdmin, setEditToolset, setDeleteId, proxyBaseUrl);+ const serverPrefixById = React.useMemo(+ () => new Map(mcpServers.map((s) => [s.server_id, s.alias || s.server_name || s.server_id])),+ [mcpServers],+ );+ const columns = toolsetColumns(isAdmin, setEditToolset, setDeleteId, serverPrefixById);return (<div className="mt-4">