Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
19 changes: 15 additions & 4 deletions litellm/proxy/_experimental/mcp_server/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,17 @@ def _prepare_mcp_server_data(
# ``alias=None`` is a valid request to clear the stored alias.
if data_dict.get("alias") is None and "alias" not in fields_set:
data_dict.pop("alias", None)
# Prisma ``allowed_tools`` is a required String[]; ``null`` is invalid.
# The UI sends null to clear a whitelist — treat that as ``[]``.
if "allowed_tools" in data_dict and data_dict["allowed_tools"] is None:
data_dict["allowed_tools"] = []
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
# Json map fields use ``@default("{}")``; explicit null means clear overrides.
for json_map_field in (
"tool_name_to_display_name",
"tool_name_to_description",
):
if json_map_field in data_dict and data_dict[json_map_field] is None:
data_dict[json_map_field] = {}
else:
data_dict = data.model_dump(exclude_none=True)
# Ensure alias is always present in the dict (even if None)
Expand All @@ -93,13 +104,13 @@ def _prepare_mcp_server_data(
if data_dict.get("env") is not None:
data_dict["env"] = safe_dumps(data_dict["env"])

if data_dict.get("tool_name_to_display_name") is not None:
if "tool_name_to_display_name" in data_dict:
data_dict["tool_name_to_display_name"] = safe_dumps(
data_dict["tool_name_to_display_name"]
data_dict["tool_name_to_display_name"] or {}
)
if data_dict.get("tool_name_to_description") is not None:
if "tool_name_to_description" in data_dict:
data_dict["tool_name_to_description"] = safe_dumps(
data_dict["tool_name_to_description"]
data_dict["tool_name_to_description"] or {}
)

# mcp_access_groups is already List[str], no serialization needed
Expand Down
8 changes: 7 additions & 1 deletion litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2429,7 +2429,13 @@ def check_allowed_or_banned_tools(self, tool_name: str, server: MCPServer) -> bo
"""
Check if the tool is allowed or banned for the given server
"""
if server.allowed_tools:
from litellm.proxy._experimental.mcp_server.utils import (
server_applies_tool_allowlist,
)

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
Expand Down
7 changes: 5 additions & 2 deletions litellm/proxy/_experimental/mcp_server/rest_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,11 @@ async def _get_tools_for_single_server(
)

# Filter tools based on allowed_tools configuration
# Only filter if allowed_tools is explicitly configured (not None and not empty)
if server.allowed_tools is not None and len(server.allowed_tools) > 0:
from litellm.proxy._experimental.mcp_server.utils import (
server_applies_tool_allowlist,
)

if server_applies_tool_allowlist(server):
tools = filter_tools_by_allowed_tools(tools, server)

# Filter tools based on user_api_key_auth.object_permission.mcp_tool_permissions
Expand Down
8 changes: 7 additions & 1 deletion litellm/proxy/_experimental/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -945,10 +945,16 @@ def filter_tools_by_allowed_tools(
Returns:
Filtered list of tools
"""
from litellm.proxy._experimental.mcp_server.utils import (
server_applies_tool_allowlist,
)

tools_to_return = tools

# Filter by allowed_tools (whitelist)
if mcp_server.allowed_tools:
if server_applies_tool_allowlist(mcp_server):
if not mcp_server.allowed_tools:
return []
tools_to_return = [
tool
for tool in tools
Expand Down
31 changes: 31 additions & 0 deletions litellm/proxy/_experimental/mcp_server/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
MCP Server Utilities
"""

import json
import re
from typing import Any, Dict, Iterator, Mapping, Optional, Tuple, Union

Expand Down Expand Up @@ -162,6 +163,36 @@ def lookup_mcp_server_auth_in_headers(
return None


MCP_TOOL_ALLOWLIST_ENFORCED_KEY = "tool_allowlist_enforced"


def _parse_mcp_info_dict(mcp_info: Any) -> Optional[Dict[str, Any]]:
if mcp_info is None:
return None
if isinstance(mcp_info, dict):
return mcp_info
if isinstance(mcp_info, str):
try:
parsed = json.loads(mcp_info)
except (ValueError, TypeError):
return None
return parsed if isinstance(parsed, dict) else None
return None


def is_server_tool_allowlist_enforced(mcp_server: Any) -> bool:
mcp_info = _parse_mcp_info_dict(getattr(mcp_server, "mcp_info", None))
if not mcp_info:
return False
return bool(mcp_info.get(MCP_TOOL_ALLOWLIST_ENFORCED_KEY))


def server_applies_tool_allowlist(mcp_server: Any) -> bool:
"""Whether server-level allowed_tools whitelist filtering is active."""
allowed_tools = getattr(mcp_server, "allowed_tools", None) or []
return is_server_tool_allowlist_enforced(mcp_server) or bool(allowed_tools)


def validate_and_normalize_mcp_server_payload(payload: Any) -> None:
"""
Validate and normalize MCP server payload fields (server_name and alias).
Expand Down
4 changes: 3 additions & 1 deletion tests/mcp_tests/test_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1862,9 +1862,11 @@ async def test_get_tools_for_single_server():
)
from mcp.types import Tool as MCPTool

# Create a mock server
# Create a mock server (pin allowlist fields; MagicMock auto-attrs are truthy)
mock_server = MagicMock()
mock_server.mcp_info = {"server_name": "zapier"}
mock_server.allowed_tools = None
mock_server.disallowed_tools = None

# Create mock tools
mock_tools = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,34 @@ async def test_partial_update_omits_unset_defaultful_fields():
)


@pytest.mark.asyncio
async def test_partial_update_null_tool_name_maps_clear_to_empty_json():
"""Explicit null on Json map fields must clear overrides (UI legacy)."""
data = UpdateMCPServerRequest(
server_id="my-test-server",
tool_name_to_display_name=None,
tool_name_to_description=None,
)

data_dict = await _run_update(data)

assert data_dict["tool_name_to_display_name"] == "{}"
assert data_dict["tool_name_to_description"] == "{}"


@pytest.mark.asyncio
async def test_partial_update_null_allowed_tools_clears_whitelist():
"""Explicit null must clear the whitelist (UI legacy); Prisma requires []."""
data = UpdateMCPServerRequest(
server_id="my-test-server",
allowed_tools=None,
)

data_dict = await _run_update(data)

assert data_dict["allowed_tools"] == []


@pytest.mark.asyncio
async def test_partial_update_preserves_http_transport():
"""The reported prod incident: a PUT without transport must not flip http->sse."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4184,6 +4184,85 @@ def mock_handler(**kwargs):
assert len(filtered_tools) == 2


def test_filter_tools_enforced_empty_allowlist_blocks_all():
from mcp.types import Tool

from litellm.proxy._experimental.mcp_server.server import (
filter_tools_by_allowed_tools,
)
from litellm.types.mcp import MCPTransport
from litellm.types.mcp_server.mcp_server_manager import MCPServer

tools = [
Tool(
name="read_wiki_structure",
title=None,
description="",
inputSchema={"type": "object"},
outputSchema=None,
annotations=None,
),
]
server = MCPServer(
server_id="deepwiki",
name="deepwiki",
transport=MCPTransport.http,
allowed_tools=[],
mcp_info={"tool_allowlist_enforced": True},
)

assert filter_tools_by_allowed_tools(tools, server) == []


def test_filter_tools_legacy_empty_allowlist_allows_all():
from mcp.types import Tool

from litellm.proxy._experimental.mcp_server.server import (
filter_tools_by_allowed_tools,
)
from litellm.types.mcp import MCPTransport
from litellm.types.mcp_server.mcp_server_manager import MCPServer

tools = [
Tool(
name="read_wiki_structure",
title=None,
description="",
inputSchema={"type": "object"},
outputSchema=None,
annotations=None,
),
]
server = MCPServer(
server_id="legacy",
name="legacy",
transport=MCPTransport.http,
allowed_tools=[],
mcp_info=None,
)

assert len(filter_tools_by_allowed_tools(tools, server)) == 1


def test_check_allowed_or_banned_tools_enforced_empty_denies_calls():
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
MCPServerManager,
)
from litellm.types.mcp import MCPTransport
from litellm.types.mcp_server.mcp_server_manager import MCPServer

manager = MCPServerManager.__new__(MCPServerManager)
server = MCPServer(
server_id="deepwiki",
name="deepwiki",
transport=MCPTransport.http,
allowed_tools=[],
mcp_info={"tool_allowlist_enforced": True},
)

assert manager.check_allowed_or_banned_tools("read_wiki_structure", server) is False


@pytest.mark.asyncio
async def test_get_tools_from_mcp_servers_injects_stored_oauth2_token():
"""
Expand Down Expand Up @@ -4540,9 +4619,9 @@ async def test_cooldown_after_empty_upstream_response(self):
await global_mcp_server_manager._ensure_upstream_initialize_instructions_cached(
server
)
assert create.await_count == 1, (
"Second probe within cooldown must not reconnect to upstream"
)
assert (
create.await_count == 1
), "Second probe within cooldown must not reconnect to upstream"
assert (
"empty-server"
not in global_mcp_server_manager._upstream_initialize_instructions_by_server_id
Expand All @@ -4567,7 +4646,9 @@ async def test_cooldown_after_upstream_failure(self):

server = _make_instruction_server(server_id="boom-server", instructions=None)
fake_client = MagicMock()
fake_client.run_with_session = AsyncMock(side_effect=RuntimeError("upstream down"))
fake_client.run_with_session = AsyncMock(
side_effect=RuntimeError("upstream down")
)
fake_client._last_initialize_instructions = None

create = AsyncMock(return_value=fake_client)
Expand All @@ -4579,9 +4660,9 @@ async def test_cooldown_after_upstream_failure(self):
await global_mcp_server_manager._ensure_upstream_initialize_instructions_cached(
server
)
assert create.await_count == 1, (
"Second probe within cooldown must not reconnect after failure"
)
assert (
create.await_count == 1
), "Second probe within cooldown must not reconnect after failure"
assert (
"boom-server"
not in global_mcp_server_manager._upstream_initialize_instructions_by_server_id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,12 +384,13 @@ const CreateMCPServer: React.FC<CreateMCPServerProps> = ({
description: restValues.description,
logo_url: logoUrl || undefined,
mcp_server_cost_info: Object.keys(costConfig).length > 0 ? costConfig : null,
tool_allowlist_enforced: allowedTools.length > 0,

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.

Create flow omits enforcement flag when all tools deselected

Medium Severity

In the create flow, tool_allowlist_enforced is set to allowedTools.length > 0, which evaluates to false when a user explicitly deselects all tools. The backend's server_applies_tool_allowlist() then returns False (no enforcement, empty list), making all tools accessible despite the UI showing "0 tools enabled." The edit flow correctly handles this case using hasToolAllowlistInteraction tracking, but the create flow lacks this mechanism, creating a mismatch between displayed state and actual server behavior.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6290c4b. Configure here.

},
mcp_access_groups: accessGroups,
alias: restValues.alias,
allowed_tools: allowedTools.length > 0 ? allowedTools : null,
tool_name_to_display_name: Object.keys(toolNameToDisplayName).length > 0 ? toolNameToDisplayName : null,
tool_name_to_description: Object.keys(toolNameToDescription).length > 0 ? toolNameToDescription : null,
allowed_tools: allowedTools,
tool_name_to_display_name: toolNameToDisplayName,
tool_name_to_description: toolNameToDescription,
allow_all_keys: Boolean(allowAllKeysRaw),
available_on_public_internet: Boolean(availableOnPublicInternetRaw),
delegate_auth_to_upstream: Boolean(delegateAuthToUpstreamRaw),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ vi.mock("./MCPPermissionManagement", () => ({
}));

vi.mock("./mcp_tool_configuration", () => ({
default: () => <div data-testid="mcp-tool-config" />,
default: ({ existingAllowedTools }: { existingAllowedTools: string[] | null }) => (
<div data-testid="mcp-tool-config" data-existing-allowed-tools={JSON.stringify(existingAllowedTools)} />
),
}));

// ── fixtures ──────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -218,6 +220,48 @@ describe("MCPServerEdit (delegate auth)", () => {
});
});

describe("MCPServerEdit (tool allowlist)", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("treats legacy empty allowed_tools as unrestricted", () => {
render(
<MCPServerEdit
mcpServer={{
...interactiveOAuthServer,
allowed_tools: [],
mcp_info: { server_name: "OAuthServer" },
}}
accessToken={null}
onCancel={vi.fn()}
onSuccess={vi.fn()}
availableAccessGroups={[]}
/>,
);

expect(screen.getByTestId("mcp-tool-config")).toHaveAttribute("data-existing-allowed-tools", "null");
});

it("honors enforced empty allowed_tools", () => {
render(
<MCPServerEdit
mcpServer={{
...interactiveOAuthServer,
allowed_tools: [],
mcp_info: { server_name: "OAuthServer", tool_allowlist_enforced: true },
}}
accessToken={null}
onCancel={vi.fn()}
onSuccess={vi.fn()}
availableAccessGroups={[]}
/>,
);

expect(screen.getByTestId("mcp-tool-config")).toHaveAttribute("data-existing-allowed-tools", "[]");
});
});

describe("MCPServerEdit (interactive OAuth)", () => {
beforeEach(() => {
vi.clearAllMocks();
Expand Down
Loading
Loading