diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py index 593115ca254..cc2192bd4e8 100644 --- a/litellm/proxy/auth/auth_checks.py +++ b/litellm/proxy/auth/auth_checks.py @@ -173,7 +173,7 @@ class _PrismaVectorStoreRow(Protocol): def __iter__(self) -> Iterator[tuple[str, object]]: ... -class _PrismaUserRow(Protocol): +class _PrismaUserRow(_PrismaModelDumpRow, Protocol): user_id: str @property @@ -2486,7 +2486,7 @@ async def _get_fuzzy_user_object( if sso_user_id is not None: response = await _user_table(UserRepository(prisma_client)).find_unique( where={"sso_user_id": sso_user_id}, - include={"organization_memberships": True}, + include={"organization_memberships": True, "object_permission": True}, ) if response is None and user_email is not None: @@ -2494,7 +2494,7 @@ async def _get_fuzzy_user_object( # This matches the pattern used in _check_duplicate_user_email response = await _user_table(UserRepository(prisma_client)).find_first( where={"user_email": {"equals": user_email, "mode": "insensitive"}}, - include={"organization_memberships": True}, + include={"organization_memberships": True, "object_permission": True}, ) if response is not None and sso_user_id is not None: # update sso_user_id @@ -2652,8 +2652,7 @@ async def get_user_object( ] response.organization_memberships = _dumped_memberships - _response = LiteLLM_UserTable.model_validate(dict(response)) - + _response = LiteLLM_UserTable.model_validate(response.model_dump()) _response = await _backfill_null_user_email( prisma_client=prisma_client, user_api_key_cache=user_api_key_cache, diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py index 343cbfa20d7..b54474bfda6 100644 --- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py +++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py @@ -416,6 +416,44 @@ class TestListToolRestApiWithToolSearch: SKILL_SEARCH_TOOL_NAME, } + @pytest.mark.asyncio + async def test_returns_only_virtual_tools_when_team_flag_enabled(self) -> None: + from litellm.proxy._experimental.mcp_server.rest_endpoints import router + + user_api_key_dict = UserAPIKeyAuth( + api_key="test_key", + object_permission=None, + team_object_permission=LiteLLM_ObjectPermissionTable( + object_permission_id="team-perm", + mcp_tool_search_enabled=True, + ), + ) + + mock_request = MagicMock() + mock_request.headers = {} + + list_fn = next( + r.endpoint + for r in router.routes + if hasattr(r, "path") and r.path.endswith("/tools/list") and hasattr(r, "methods") and "GET" in r.methods + ) + + result = await list_fn( + request=mock_request, + server_id=None, + include_disabled_tools=False, + user_api_key_dict=user_api_key_dict, + ) + + assert result["error"] is None + tool_names = [t["name"] for t in result["tools"]] + assert set(tool_names) == { + MCP_TOOL_SEARCH_TOOL_NAME, + MCP_TOOL_CALL_TOOL_NAME, + AGENT_SEARCH_TOOL_NAME, + SKILL_SEARCH_TOOL_NAME, + } + @pytest.mark.asyncio async def test_returns_full_catalog_when_flag_disabled(self) -> None: from litellm.proxy._experimental.mcp_server.rest_endpoints import router @@ -622,6 +660,38 @@ class TestCallToolRestApiVirtualTools: assert isinstance(returned_tools, list) assert any(t["name"] == "github-create_issue" for t in returned_tools) + @pytest.mark.asyncio + async def test_mcp_tool_search_call_allowed_by_user_flag_only(self) -> None: + user_api_key_dict = UserAPIKeyAuth( + api_key="test_key", + object_permission=None, + team_object_permission=None, + user_object_permission=_make_perm(mcp_tool_search_enabled=True), + ) + + request = self._make_request({"name": MCP_TOOL_SEARCH_TOOL_NAME, "arguments": {"query": "create issue"}}) + + mock_tool = MagicMock() + mock_tool.name = "github-create_issue" + mock_tool.description = "Create a GitHub issue" + mock_tool.inputSchema = {"type": "object", "properties": {}} + + with patch( # test-quality-ok: the REST handler resolves the internal catalog helper directly; no injection seam + "litellm.proxy._experimental.mcp_server.server._list_mcp_tools", + new_callable=AsyncMock, + return_value=AggregateToolListing(tools=[mock_tool], outcomes={}), + ): + result = await self._get_call_fn()( + request=request, + user_api_key_dict=user_api_key_dict, + ) + + assert result.content + assert result.content[0].type == "text" + returned_tools = json.loads(result.content[0].text) + assert isinstance(returned_tools, list) + assert any(t["name"] == "github-create_issue" for t in returned_tools) + @pytest.mark.asyncio async def test_mcp_tool_call_executes_discovered_tool(self) -> None: from mcp.types import CallToolResult, TextContent @@ -930,6 +1000,27 @@ class TestCallToolRestApiVirtualTools: assert exc_info.value.status_code in (400, 403, 404) + @pytest.mark.asyncio + async def test_mcp_tool_search_call_rejected_when_team_disables_and_user_enables(self) -> None: + from fastapi import HTTPException + + user_api_key_dict = UserAPIKeyAuth( + api_key="test_key", + object_permission=None, + team_object_permission=_make_perm(mcp_tool_search_enabled=False), + user_object_permission=_make_perm(mcp_tool_search_enabled=True), + ) + + request = self._make_request({"name": MCP_TOOL_SEARCH_TOOL_NAME, "arguments": {"query": "create issue"}}) + + with pytest.raises(HTTPException) as exc_info: + await self._get_call_fn()( + request=request, + user_api_key_dict=user_api_key_dict, + ) + + assert exc_info.value.status_code in (400, 403, 404) + class TestDispatchVirtualMcpTool: """Covers the SSE/protocol-path interception helper in server.py.""" diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.py index 79acf37eeff..78666e2bc4a 100644 --- a/tests/test_litellm/proxy/auth/test_auth_checks.py +++ b/tests/test_litellm/proxy/auth/test_auth_checks.py @@ -3533,7 +3533,7 @@ async def test_get_fuzzy_user_object_case_insensitive_email(): call_args = mock_prisma.db.litellm_usertable.find_first.call_args assert call_args.kwargs["where"]["user_email"]["equals"] == "test@example.com" assert call_args.kwargs["where"]["user_email"]["mode"] == "insensitive" - assert call_args.kwargs["include"] == {"organization_memberships": True} + assert call_args.kwargs["include"] == {"organization_memberships": True, "object_permission": True} @pytest.mark.asyncio diff --git a/tests/test_litellm/proxy/auth/test_object_permission_loading.py b/tests/test_litellm/proxy/auth/test_object_permission_loading.py index 7df537d284f..3194984577c 100644 --- a/tests/test_litellm/proxy/auth/test_object_permission_loading.py +++ b/tests/test_litellm/proxy/auth/test_object_permission_loading.py @@ -5,6 +5,7 @@ Test that object_permission is automatically loaded when fetching keys and teams from unittest.mock import AsyncMock, MagicMock, patch import pytest +from pydantic import BaseModel from litellm.proxy._types import ( @@ -15,6 +16,11 @@ from litellm.proxy._types import ( from litellm.proxy.auth.auth_checks import get_key_object, get_team_object +class _PrismaObjectPermissionStub(BaseModel): + object_permission_id: str + mcp_tool_search_enabled: bool + + @pytest.mark.asyncio async def test_get_key_object_loads_object_permission(): """ @@ -182,11 +188,12 @@ async def test_get_user_object_loads_object_permission(): user_id="test_user", user_email="test@example.com", object_permission_id="test_perm_id", - object_permission=LiteLLM_ObjectPermissionTable( - object_permission_id="test_perm_id", - mcp_servers=["user_server1"], - mcp_tool_search_enabled=True, - ), + object_permission=None, + ) + setattr( + mock_user, + "object_permission", + _PrismaObjectPermissionStub(object_permission_id="test_perm_id", mcp_tool_search_enabled=True), ) mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user) diff --git a/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx b/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx index ac4a2307de1..6794613ab12 100644 --- a/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx +++ b/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx @@ -2212,6 +2212,28 @@ describe("TeamInfoView - the exact bytes the update call sends", () => { }); }); + it("sends an enabled MCP Tool Search setting when selected during team edit", async () => { + const user = userEvent.setup({ delay: null }); + await openEditor(user); + + await chooseSelectOption(user, screen.getByRole("combobox", { name: "MCP Tool Search" }), "Enabled"); + const payload = await save(user); + + const objectPermission = wireBody(payload).object_permission as Record; + expect(objectPermission.mcp_tool_search_enabled).toBe(true); + }); + + it("sends a disabled MCP Tool Search setting when selected during team edit", async () => { + const user = userEvent.setup({ delay: null }); + await openEditor(user); + + await chooseSelectOption(user, screen.getByRole("combobox", { name: "MCP Tool Search" }), "Disabled"); + const payload = await save(user); + + const objectPermission = wireBody(payload).object_permission as Record; + expect(objectPermission.mcp_tool_search_enabled).toBe(false); + }); + const openEditorWithAgents = async (user: ReturnType) => { vi.mocked(networking.teamInfoCall).mockResolvedValue( createMockTeamData({