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): enforce tool entitlements on every MCP tool dispatch path (#35156)
Yassin Kortamf8375780fe9e
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex db80c0f76ee..e3f7352e8ca 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -4436,13 +4436,18 @@ class MCPServerManager:arguments: dict[str, Any],server_name: str,user_api_key_auth: Optional[UserAPIKeyAuth],- proxy_logging_obj: ProxyLogging,+ proxy_logging_obj: ProxyLogging | None,server: MCPServer,raw_headers: Optional[dict[str, str]] = None,) -> dict[str, Any]:"""Run pre-call checks and guardrail hooks for an MCP tool call.+ Authorization runs unconditionally; only the guardrail hooks, which are+ dispatched through ``proxy_logging_obj``, depend on a logger being+ present. An absent logger must never be able to turn an authorization+ decision into a no-op.+Returns a dict that may contain:- "arguments": hook-modified tool arguments (only if changed)- "extra_headers": headers injected by pre_mcp_call guardrail hooks@@ -4470,6 +4475,10 @@ class MCPServerManager:server=server,)+ hook_result: dict[str, Any] = {}+ if proxy_logging_obj is None:+ return hook_result+# Extract incoming Bearer token from raw request headers so# guardrails like MCPJWTSigner can verify + re-sign it (FR-5).normalized_raw = {k.lower(): v for k, v in (raw_headers or {}).items()}@@ -4499,7 +4508,6 @@ class MCPServerManager:# Convert to LLM format for existing guardrail compatibilitysynthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(mcp_request_obj, pre_hook_kwargs)- hook_result: dict[str, Any] = {}try:# Use standard pre_call_hookmodified_data = await proxy_logging_obj.pre_call_hook(@@ -5125,19 +5133,17 @@ class MCPServerManager:# Allow validation and modification of tool calls before execution# Using standard pre_call_hook#########################################################- hook_result: dict[str, Any] = {}- if proxy_logging_obj:- hook_result = await self.pre_call_tool_check(- name=name,- arguments=arguments,- server_name=server_name,- user_api_key_auth=user_api_key_auth,- proxy_logging_obj=proxy_logging_obj,- server=mcp_server,- raw_headers=raw_headers,- )- if "arguments" in hook_result:- arguments = hook_result["arguments"]+ hook_result: dict[str, Any] = await self.pre_call_tool_check(+ name=name,+ arguments=arguments,+ server_name=server_name,+ user_api_key_auth=user_api_key_auth,+ proxy_logging_obj=proxy_logging_obj,+ server=mcp_server,+ raw_headers=raw_headers,+ )+ if "arguments" in hook_result:+ arguments = hook_result["arguments"]# Prepare tasks for during hookstasks = []diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex 48effdb0f6e..d8431b9b3bb 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -2902,6 +2902,54 @@ if MCP_AVAILABLE:# Deprecated: Local MCP Server Tool#########################################################else:+ # Gate only what can actually dispatch. When the unprefixed name is+ # not in the registry either, `_handle_local_mcp_tool` below reports+ # 404 and nothing runs, so demanding a server here would turn every+ # unknown tool name into a misleading 503.+ if global_mcp_tool_registry.get_tool(original_tool_name) is not None:+ # `mcp_server` is None here because the tool name is not in the+ # tool -> server mapping, but the name still carries a prefix+ # that the server-level check above compared against the+ # caller's `allowed_mcp_servers` by exact `name`. So the named+ # server is in that list and can carry the tool-level checks,+ # even with the mapping cold. Resolve it from+ # `allowed_mcp_servers` rather than the registry: the registry+ # would happily return a server the caller holds no grant for,+ # and matching anything other than `name` would accept a server+ # the check never validated.+ prefix_server = next(+ (candidate for candidate in allowed_mcp_servers if candidate.name == server_name),+ None,+ )+ if prefix_server is None:+ # A non-empty prefix that passed the server-level check+ # always matches here, so this arm only fires when the+ # prefix was empty, which is exactly the case that check+ # skips. Fail closed rather than dispatch with no server to+ # evaluate a tool ceiling against.+ raise HTTPException(+ status_code=503,+ detail=(+ f"MCP server for tool '{original_tool_name}' is not available; "+ "refusing to dispatch without authorization checks. "+ "Retry once the server is registered."+ ),+ )++ from litellm.proxy.proxy_server import proxy_logging_obj++ hook_result = await global_mcp_server_manager.pre_call_tool_check(+ name=original_tool_name,+ arguments=arguments,+ server_name=server_name,+ user_api_key_auth=user_api_key_auth,+ proxy_logging_obj=proxy_logging_obj,+ server=prefix_server,+ raw_headers=raw_headers,+ )+ if "arguments" in hook_result:+ arguments = hook_result["arguments"] # pyright: ignore[reportAny] # hook returns untyped args+local_content = await _handle_local_mcp_tool(original_tool_name, arguments)response = CallToolResult(content=cast(Any, local_content), isError=False)diff --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 f6753e28a66..54fd5242d5f 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@@ -46,10 +46,13 @@ from litellm.proxy._experimental.mcp_server.mcp_server_manager import ()from litellm.proxy._types import (LiteLLM_MCPServerTable,+ LiteLLM_ObjectPermissionTable,+ LitellmUserRoles,MCPApprovalStatus,MCPEnvVar,MCPEnvVarScope,MCPTransport,+ UserAPIKeyAuth,)from litellm.types.mcp import MCPAuth, MCPAuthTypefrom litellm.types.mcp_server.mcp_server_manager import MCPOAuthMetadata, MCPServer@@ -9718,3 +9721,75 @@ class TestOpenAPIRegistryKeyMatchesRegistration:assert result.isError is Trueassert "not found in registry" in result.content[0].text+++class TestToolAuthorizationIsNotConditionalOnLogging:+ """`call_tool` used to run `pre_call_tool_check` — the only place tool-level+ MCP entitlements are enforced — inside `if proxy_logging_obj:`, so a caller+ reached with no logging object got no authorization decision at all. Both+ production call sites pass the module-level `ProxyLogging` singleton, which+ is never None, so this was not a live hole; the invariant being restored is+ that an authorization decision cannot be skipped by an absent logger.+ """++ @staticmethod+ def _manager_with_scoped_server() -> tuple[MCPServerManager, UserAPIKeyAuth]:+ manager = MCPServerManager()+ manager.registry["srv-gated"] = MCPServer(+ server_id="srv-gated",+ name="gated_server",+ server_name="gated_server",+ alias="gated_server",+ url="http://127.0.0.1:1/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.none,+ )+ for tool_name in ("read_only_tool", "delete_everything"):+ manager.tool_name_to_mcp_server_name_mapping[tool_name] = "gated_server"+ user = UserAPIKeyAuth(+ api_key="sk-caller",+ user_id="alice",+ user_role=LitellmUserRoles.INTERNAL_USER.value,+ object_permission=LiteLLM_ObjectPermissionTable(+ object_permission_id="op-gated",+ mcp_servers=["srv-gated"],+ mcp_tool_permissions={"srv-gated": ["read_only_tool"]},+ ),+ )+ return manager, user++ @pytest.mark.asyncio+ async def test_unentitled_tool_refused_without_proxy_logging_obj(self):+ manager, user = self._manager_with_scoped_server()+ upstream = AsyncMock(return_value=CallToolResult(content=[], isError=False))++ with patch.object(manager, "_call_regular_mcp_tool", new=upstream):+ with pytest.raises(HTTPException) as exc:+ await manager.call_tool(+ server_name="gated_server",+ name="delete_everything",+ arguments={},+ user_api_key_auth=user,+ proxy_logging_obj=None,+ )++ assert exc.value.status_code == 403+ upstream.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_entitled_tool_still_dispatches_without_proxy_logging_obj(self):+ """The gate must refuse only what the entitlement excludes; an allowed+ tool still reaches the upstream when there is no logging object."""+ manager, user = self._manager_with_scoped_server()+ upstream = AsyncMock(return_value=CallToolResult(content=[], isError=False))++ with patch.object(manager, "_call_regular_mcp_tool", new=upstream):+ await manager.call_tool(+ server_name="gated_server",+ name="read_only_tool",+ arguments={},+ user_api_key_auth=user,+ proxy_logging_obj=None,+ )++ upstream.assert_awaited_once()diff --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 c4b3c7f5f67..63473bf3cf5 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@@ -9,7 +9,13 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy._types import (+ LiteLLM_ObjectPermissionTable,+ LitellmUserRoles,+ UserAPIKeyAuth,+)+from litellm.types.mcp import MCPAuth, MCPTransport+from litellm.types.mcp_server.mcp_server_manager import MCPServer@pytest.mark.asyncio@@ -305,3 +311,241 @@ async def test_openapi_local_tool_injects_resolved_oauth_token():assert captured["resolved"] == {"Authorization": "Bearer stored-user-token"}assert _request_resolved_auth_headers.get() is None++++LEGACY_SERVER_ID = "srv-legacy-petstore"+LEGACY_SERVER_NAME = "legacy_petstore"+LEGACY_TOOL = "dump_secrets"+++def legacy_local_tool():+ """A bare `mcp_tools`-style handler plus a registered server whose tools were+ never listed, which is what leaves `tool_name_to_mcp_server_name_mapping`+ cold and routes `{server}-{tool}` into `execute_mcp_tool`'s legacy fallback.++ Yields the server and the list the handler appends to, so a test can tell+ "refused" from "dispatched" by whether the handler actually ran.+ """+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )+ from litellm.proxy._experimental.mcp_server.tool_registry import (+ global_mcp_tool_registry,+ )++ executed: list[dict] = []+ server = MCPServer(+ server_id=LEGACY_SERVER_ID,+ name=LEGACY_SERVER_NAME,+ server_name=LEGACY_SERVER_NAME,+ alias=LEGACY_SERVER_NAME,+ url="http://127.0.0.1:1/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.none,+ )+ global_mcp_tool_registry.register_tool(+ name=LEGACY_TOOL,+ description="bare tool registered from the mcp_tools config block",+ input_schema={"type": "object", "properties": {}},+ handler=lambda **kwargs: executed.append(kwargs) or "legacy local tool ran",+ )+ global_mcp_server_manager.registry[LEGACY_SERVER_ID] = server+ assert (+ global_mcp_server_manager._get_mcp_server_from_tool_name(+ f"{LEGACY_SERVER_NAME}-{LEGACY_TOOL}"+ )+ is None+ ), "fixture precondition: the prefixed name must resolve to no server"+ try:+ yield server, executed+ finally:+ global_mcp_tool_registry.tools.pop(LEGACY_TOOL, None)+ global_mcp_server_manager.registry.pop(LEGACY_SERVER_ID, None)+++def _caller_entitled_to(tools: list[str]) -> UserAPIKeyAuth:+ return UserAPIKeyAuth(+ api_key="sk-caller",+ user_id="alice",+ user_role=LitellmUserRoles.INTERNAL_USER.value,+ object_permission=LiteLLM_ObjectPermissionTable(+ object_permission_id="op-legacy-fallback",+ mcp_servers=[LEGACY_SERVER_ID],+ mcp_tool_permissions={LEGACY_SERVER_ID: tools},+ ),+ )+++async def test_legacy_local_tool_fallback_refuses_unentitled_caller(legacy_local_tool):+ """The legacy fallback dispatched into the local tool registry with no+ tool-level authorization at all: no allowed/banned check, no key/team/org+ tool permissions, no parameter validation. It must now run the same gate,+ so a caller whose entitlement excludes the tool is refused and the handler+ never runs.++ Nothing is mocked: the real registries and the real entitlement gate decide.+ """+ from fastapi import HTTPException++ from litellm.proxy._experimental.mcp_server import server as mcp_module+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (+ MCPRequestHandler,+ )++ server, executed = legacy_local_tool+ user = _caller_entitled_to(["list_pets"])++ # The gate answers "no" for this caller/tool pair, so a dispatch below would+ # be an entitlement bypass rather than a routing quirk.+ assert (+ await MCPRequestHandler.is_tool_allowed_for_server(+ tool_name=LEGACY_TOOL,+ server_id=LEGACY_SERVER_ID,+ user_api_key_auth=user,+ )+ is False+ )++ with pytest.raises(HTTPException) as exc:+ await mcp_module.execute_mcp_tool(+ name=f"{LEGACY_SERVER_NAME}-{LEGACY_TOOL}",+ arguments={},+ allowed_mcp_servers=[server],+ start_time=datetime.now(timezone.utc),+ user_api_key_auth=user,+ )++ assert exc.value.status_code == 403+ # Pin the refusal to the ENTITLEMENT gate. The server-level check earlier in+ # execute_mcp_tool also raises 403 (with a plain-string detail), and the+ # allowed/banned-tools check raises a dict naming the server rather than the+ # key/team, so asserting on the status alone would pass for the wrong reason.+ detail = exc.value.detail+ assert isinstance(detail, dict), detail+ assert "not allowed for your key/team" in detail["error"], detail+ assert executed == []+++async def test_legacy_local_tool_fallback_still_dispatches_entitled_caller(+ legacy_local_tool,+):+ """The gate must do per-tool work rather than disabling the fallback: the+ same shape of call, from a caller entitled to the tool, still dispatches.++ This is the backwards-compatibility half. Refusing this call would trade an+ authorization hole for an outage on a configuration that worked before.+ """+ from litellm.proxy._experimental.mcp_server import server as mcp_module++ server, executed = legacy_local_tool+ user = _caller_entitled_to([LEGACY_TOOL])++ result = await mcp_module.execute_mcp_tool(+ name=f"{LEGACY_SERVER_NAME}-{LEGACY_TOOL}",+ arguments={},+ allowed_mcp_servers=[server],+ start_time=datetime.now(timezone.utc),+ user_api_key_auth=user,+ )++ assert result.isError is False+ assert executed == [{}]+ assert "legacy local tool ran" in result.content[0].text+++async def test_legacy_local_tool_fallback_fails_closed_on_empty_prefix(+ legacy_local_tool,+):+ """An empty prefix segment skips the server-level check outright:+ `split_server_prefix_from_name` yields an empty `server_name`, and `execute_mcp_tool`+ only runs `is_tool_allowed` `if server_name`. The legacy fallback then dispatched for a+ caller holding no server grant at all, so this arm of the guard is reachable rather than+ defensive. Nothing is patched here; the empty prefix segment is the whole of it.+ """+ from fastapi import HTTPException++ from litellm.proxy._experimental.mcp_server import server as mcp_module++ _server, executed = legacy_local_tool++ with pytest.raises(HTTPException) as exc:+ await mcp_module.execute_mcp_tool(+ name=f"-{LEGACY_TOOL}",+ arguments={},+ allowed_mcp_servers=[],+ start_time=datetime.now(timezone.utc),+ user_api_key_auth=_caller_entitled_to([LEGACY_TOOL]),+ )++ assert exc.value.status_code == 503+ assert executed == []+++async def test_legacy_local_tool_fallback_fails_closed_when_prefix_names_no_server(+ legacy_local_tool,+):+ """Second arm of the same guard: a non-empty prefix that named a server the caller does+ hold, but which is absent from `allowed_mcp_servers` by the time dispatch runs. Patching+ the server-level check (which would otherwise refuse first) is what makes the arm+ observable, so a later refactor cannot make the branch dispatch with no server to+ evaluate a tool ceiling against.+ """+ from fastapi import HTTPException++ from litellm.proxy._experimental.mcp_server import server as mcp_module++ _server, executed = legacy_local_tool+ other_server = MCPServer(+ server_id="srv-unrelated",+ name="unrelated_server",+ server_name="unrelated_server",+ alias="unrelated_server",+ url="http://127.0.0.1:1/mcp",+ transport=MCPTransport.http,+ auth_type=MCPAuth.none,+ )++ with patch(+ "litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",+ return_value=True,+ ):+ with pytest.raises(HTTPException) as exc:+ await mcp_module.execute_mcp_tool(+ name=f"{LEGACY_SERVER_NAME}-{LEGACY_TOOL}",+ arguments={},+ allowed_mcp_servers=[other_server],+ start_time=datetime.now(timezone.utc),+ user_api_key_auth=_caller_entitled_to([LEGACY_TOOL]),+ )++ assert exc.value.status_code == 503+ assert executed == []+++async def test_unknown_tool_name_still_reports_not_found():+ """The guard must gate dispatch, not existence. An unprefixed name that no registry+ knows cannot dispatch anything, so it has to keep reporting 404 rather than collapsing+ into the guard's 503; every typo'd tool name takes this branch.+ """+ from fastapi import HTTPException++ from litellm.proxy._experimental.mcp_server import server as mcp_module++ with pytest.raises(HTTPException) as exc:+ await mcp_module.execute_mcp_tool(+ name="tool_no_registry_knows",+ arguments={},+ allowed_mcp_servers=[],+ start_time=datetime.now(timezone.utc),+ user_api_key_auth=_caller_entitled_to([LEGACY_TOOL]),+ )++ assert exc.value.status_code == 404+ assert "not found" in str(exc.value.detail)