Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2057,7 +2057,7 @@ def _get_key_object_permission(
@staticmethod
async def _get_team_object_permission(
user_api_key_auth: UserAPIKeyAuth | None = None,
):
) -> LiteLLM_ObjectPermissionTable | None:
"""
Get team object_permission - automatically loaded by get_team_object() in main auth flow.
Expand Down Expand Up @@ -2289,6 +2289,10 @@ async def get_allowed_tools_for_server(
)
)

allowed_tools = _as_list(

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.

P2 Critical-path database lookups

This caller ceiling adds team and user permission lookups to each applicable MCP tool authorization. The repository forbids new database requests in the critical request path, so this requirement must be satisfied before merging

Rule Used: What: Avoid creating new database requests or Router objects in the critical request path. Why: Creating these objects on every request causes performance degradation and unnecessary resource consumption. (source)

Knowledge Base Used: Proxy authentication and authorization

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

Both loaders go through user_api_key_cache and the shared object_permission_id cache, and the server-level caller ceiling already warms them for these same principals earlier in the request, so a warm request reads no rows

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.

That’s a valid clarification. Because the caller team/user resolvers use user_api_key_cache and the shared object-permission cache, and the existing server-level caller ceiling resolves the same principals earlier in the request, this addition does not introduce additional database queries on the normal warm path. The cold-cache lookup is already part of the existing caller-ceiling flow, so my critical-path database finding does not apply here; I’m withdrawing it.

await MCPRequestHandler._apply_agent_caller_tool_ceiling(allowed_tools, server_id, user_api_key_auth)
)

return await MCPRequestHandler._apply_agent_and_org_tool_ceilings(
allowed_tools, server_id, user_api_key_auth, keyless_source=keyless_source
)
Expand Down Expand Up @@ -3170,6 +3174,48 @@ async def _apply_user_tool_ceiling(
return list(user_tools)
return list(set(allowed_tools) & set(user_tools))

@staticmethod
async def _apply_agent_caller_tool_ceiling(
allowed_tools: Sequence[str] | None,
server_id: str,
user_api_key_auth: UserAPIKeyAuth | None = None,
) -> Sequence[str] | None:
"""Narrow an agent key's tools on ``server_id`` to those the invoking user and team (echoed back
by the agent as ``x-litellm-user-id`` / ``x-litellm-team-id``) may call: the echoed team's tool
grants when it names any on this server, then the echoed user's own tool entitlement. The tools
axis twin of ``_apply_agent_caller_ceiling``, so the headers only ever narrow. Denies every tool
on the server when the caller's team cannot be loaded, since a caller we cannot resolve must not
read as unrestricted."""
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)

caller_auth: Final = agent_caller_auth(user_api_key_auth) if user_api_key_auth else None
if caller_auth is None:
return allowed_tools
try:
team_obj_perm: Final = await MCPRequestHandler._get_team_object_permission(caller_auth)
team_toolset_tools: Final = await MCPRequestHandler._toolset_tools_for_server(team_obj_perm, server_id)
except Exception as e: # noqa: BLE001 # an unresolved caller team must deny, not widen
verbose_logger.warning(
"MCP agent caller team tool ceiling unresolvable, denying tools on %r: %s", server_id, e
)
return ()
team_direct_tools: Final = (
global_mcp_server_manager.expand_tool_permissions(team_obj_perm.mcp_tool_permissions).get(server_id)
if team_obj_perm
else None
)
team_tools: Final = MCPRequestHandler._union_tool_grants(team_direct_tools, team_toolset_tools)
team_capped: Final = (
allowed_tools
if team_tools is None
else tuple(team_tools)
if allowed_tools is None
else tuple(frozenset(allowed_tools) & frozenset(team_tools))
)
return await MCPRequestHandler._apply_user_tool_ceiling(team_capped, server_id, caller_auth)

@staticmethod
async def _apply_end_user_tool_ceiling(
allowed_tools: Sequence[str] | None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import os
from datetime import datetime, timedelta, timezone
from typing import Literal
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
Expand Down Expand Up @@ -4284,6 +4285,105 @@ async def test_agent_key_acting_for_a_caller_whose_entitlement_is_unreadable_rea
):
assert await MCPRequestHandler.get_allowed_mcp_servers(user_api_key_auth=agent_key) == []

@staticmethod
def _tool_grants(grants: dict[str, dict[str, list[str]]], keyed_by: Literal["team_id", "user_id"]) -> AsyncMock:
"""Object permissions keyed by the ``team_id`` or ``user_id`` being asked about; anyone else has none."""

async def by_principal(user_api_key_auth: UserAPIKeyAuth | None = None) -> LiteLLM_ObjectPermissionTable | None:
assert user_api_key_auth is not None
principal = (user_api_key_auth.team_id if keyed_by == "team_id" else user_api_key_auth.user_id) or ""
tools = grants.get(principal)
if tools is None:
return None
return LiteLLM_ObjectPermissionTable(object_permission_id=f"perm-{principal}", mcp_tool_permissions=tools)

return AsyncMock(side_effect=by_principal)

@contextlib.contextmanager
def _caller_tool_levels(
self, team_grants: dict[str, dict[str, list[str]]], user_grants: dict[str, dict[str, list[str]]]
):
with (
patch.object( # test-quality-ok: the level loaders read proxy_server globals with no injection seam
MCPRequestHandler, "_get_key_object_permission", return_value=None
),
patch.object( # test-quality-ok: same seam, keyed by which team is being asked about
MCPRequestHandler, "_get_team_object_permission", self._tool_grants(team_grants, keyed_by="team_id")
),
patch.object( # test-quality-ok: same seam, keyed by which user is being asked about
MCPRequestHandler, "_get_user_object_permission", self._tool_grants(user_grants, keyed_by="user_id")
),
patch.object( # test-quality-ok: agent object_permission lookup hits the DB, not under test here
MCPRequestHandler, "_get_agent_object_permission", AsyncMock(return_value=None)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
),
):
yield

async def test_agent_key_acting_for_a_user_only_sees_the_tools_that_user_may_call(self):
"""The agent's key may call every tool on server-a, the invoking team grants two of them and the
invoking user only one, so on that user's behalf the agent sees exactly that one tool."""
agent_key = self._agent_key_acting_for(user_id="alice", team_id="callers")

with self._caller_tool_levels(
team_grants={"callers": {"server-a": ["read_wiki_structure", "ask_wiki_question"]}},
user_grants={"alice": {"server-a": ["read_wiki_structure", "read_wiki_contents"]}},
):
assert await MCPRequestHandler.get_allowed_tools_for_server("server-a", agent_key) == [
"read_wiki_structure"
]

async def test_agent_key_acting_for_a_user_without_tool_grants_keeps_its_own_tools(self):
agent_key = self._agent_key_acting_for(user_id="alice", team_id="callers")

with self._caller_tool_levels(team_grants={}, user_grants={}):
assert await MCPRequestHandler.get_allowed_tools_for_server("server-a", agent_key) is None

async def test_agent_key_acting_for_a_team_is_capped_at_that_teams_tools_on_the_server(self):
agent_key = self._agent_key_acting_for(user_id="alice", team_id="callers")

with self._caller_tool_levels(
team_grants={"callers": {"server-a": ["ask_wiki_question"], "server-b": ["other"]}}, user_grants={}
):
assert await MCPRequestHandler.get_allowed_tools_for_server("server-a", agent_key) == ["ask_wiki_question"]
assert await MCPRequestHandler.get_allowed_tools_for_server("server-c", agent_key) is None

async def test_agent_key_not_acting_for_anyone_ignores_the_caller_tool_ceiling(self):
agent_key = UserAPIKeyAuth(api_key="agent-key", user_id="agent-owner", team_id="agent-team", agent_id="agent-1")

with self._caller_tool_levels(
team_grants={"callers": {"server-a": ["ask_wiki_question"]}},
user_grants={"alice": {"server-a": ["read_wiki_structure"]}},
):
assert await MCPRequestHandler.get_allowed_tools_for_server("server-a", agent_key) is None

async def test_agent_key_acting_for_a_caller_whose_team_is_unreadable_gets_no_tools(self):
agent_key = self._agent_key_acting_for(user_id="alice", team_id="callers")

async def only_the_callers_team_is_unreadable(
user_api_key_auth: UserAPIKeyAuth | None = None,
) -> LiteLLM_ObjectPermissionTable | None:
if user_api_key_auth is not None and user_api_key_auth.team_id == "callers":
raise RuntimeError("db down")
return None

with (
patch.object( # test-quality-ok: the level loaders read proxy_server globals with no injection seam
MCPRequestHandler, "_get_key_object_permission", return_value=None
),
patch.object( # test-quality-ok: same seam; the agent's own team resolves, the caller's team does not
MCPRequestHandler,
"_get_team_object_permission",
AsyncMock(side_effect=only_the_callers_team_is_unreadable),
),
patch.object( # test-quality-ok: same seam
MCPRequestHandler, "_get_user_object_permission", AsyncMock(return_value=None)
),
patch.object( # test-quality-ok: agent object_permission lookup hits the DB, not under test here
MCPRequestHandler, "_get_agent_object_permission", AsyncMock(return_value=None)
),
):
assert await MCPRequestHandler.get_allowed_tools_for_server("server-a", agent_key) == []

async def test_get_allowed_mcp_servers_agent_intersection(self):
"""Key/team allow [server_1, server_2]; agent allows [server_1]. Result = [server_1]."""
user_api_key_auth = UserAPIKeyAuth(
Expand Down Expand Up @@ -4354,8 +4454,7 @@ async def resolve(agent_id: str) -> AgentAccessGroupCeiling | None:
assert result == frozenset({"ag-server-id"})
assert asked == ["agent-ag"]
assert (
await MCPRequestHandler._get_agent_access_group_server_ceiling(UserAPIKeyAuth(api_key="k"), resolve)
is None
await MCPRequestHandler._get_agent_access_group_server_ceiling(UserAPIKeyAuth(api_key="k"), resolve) is None
)
assert asked == ["agent-ag"]

Expand Down Expand Up @@ -4492,7 +4591,9 @@ async def test_get_allowed_mcp_servers_toolset_only_agent_caps_key_servers(self)
stack.enter_context(patcher)
stack.enter_context(
patch.object( # test-quality-ok: key resolution has its own tests; pin its grants here
MCPRequestHandler, "_get_allowed_mcp_servers_for_key", AsyncMock(return_value=["server-a", "server-b"])
MCPRequestHandler,
"_get_allowed_mcp_servers_for_key",
AsyncMock(return_value=["server-a", "server-b"]),
)
)
stack.enter_context(
Expand All @@ -4518,7 +4619,9 @@ async def test_get_allowed_mcp_servers_agent_dangling_toolset_denies(self):
await MCPRequestHandler._get_allowed_mcp_servers_for_agent(user_api_key_auth)
stack.enter_context(
patch.object( # test-quality-ok: key resolution has its own tests; pin its grants here
MCPRequestHandler, "_get_allowed_mcp_servers_for_key", AsyncMock(return_value=["server-a", "server-b"])
MCPRequestHandler,
"_get_allowed_mcp_servers_for_key",
AsyncMock(return_value=["server-a", "server-b"]),
)
)
stack.enter_context(
Expand All @@ -4542,9 +4645,15 @@ async def test_get_agent_tool_permissions_for_server_unions_direct_and_toolset_t
with contextlib.ExitStack() as stack:
for patcher in self._agent_toolset_patches(agent_object_permission, mock_manager):
stack.enter_context(patcher)
server_a_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server("server-a", user_api_key_auth)
server_b_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server("server-b", user_api_key_auth)
server_c_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server("server-c", user_api_key_auth)
server_a_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server(
"server-a", user_api_key_auth
)
server_b_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server(
"server-b", user_api_key_auth
)
server_c_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server(
"server-c", user_api_key_auth
)

assert sorted(server_a_tools) == ["tool_direct", "tool_via_toolset"]
assert server_b_tools == ["tool_b"]
Expand Down
Loading