Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
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: true,
},
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 @@ -208,7 +208,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({

// Initialize allowed tools and tool overrides from existing server data
useEffect(() => {
if (mcpServer.allowed_tools) {
if (mcpServer.allowed_tools != null) {
setAllowedTools(mcpServer.allowed_tools);
}
setToolNameToDisplayName(mcpServer.tool_name_to_display_name ?? {});
Expand Down Expand Up @@ -537,18 +537,20 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({
env_json: undefined,
server_id: mcpServer.server_id,
mcp_info: {
...(mcpServer.mcp_info && typeof mcpServer.mcp_info === "object" ? mcpServer.mcp_info : {}),
server_name: mcpInfoServerName,
description: restValues.description,
logo_url: logoUrl || undefined,
mcp_server_cost_info: Object.keys(costConfig).length > 0 ? costConfig : null,
tool_allowlist_enforced: true,
},
mcp_access_groups: accessGroups,
alias: restValues.alias,
// Include permission management fields
extra_headers: restValues.extra_headers || [],
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,
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
tool_name_to_description: toolNameToDescription,
disallowed_tools: restValues.disallowed_tools || [],
static_headers: staticHeaders,
allow_all_keys: Boolean(allowAllKeysRaw ?? mcpServer.allow_all_keys),
Expand Down Expand Up @@ -1106,7 +1108,7 @@ const MCPServerEdit: React.FC<MCPServerEditProps> = ({
registration_url: currentRegistrationUrl ?? mcpServer.registration_url,
}}
allowedTools={allowedTools}
existingAllowedTools={mcpServer.allowed_tools || null}
existingAllowedTools={mcpServer.allowed_tools ?? null}
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
onAllowedToolsChange={setAllowedTools}
toolNameToDisplayName={toolNameToDisplayName}
toolNameToDescription={toolNameToDescription}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,8 @@ const MCPToolConfiguration: React.FC<MCPToolConfigurationProps> = ({
if (!hasInitializedRef.current) {
hasInitializedRef.current = true;

if (existingAllowedTools && existingAllowedTools.length > 0) {
// Edit mode: pre-select tools that match existing allowed tools
if (existingAllowedTools !== null) {
// Edit mode: honor stored allowlist, including [] (user cleared all tools).
const validExistingTools = existingAllowedTools.filter((toolName) =>
availableToolNames.includes(toolName)
);
Expand Down Expand Up @@ -467,7 +467,11 @@ const MCPToolConfiguration: React.FC<MCPToolConfigurationProps> = ({
<McpCrudPermissionPanel
tools={tools}
searchFilter={toolSearchTerm}
value={allowedTools.length === 0 ? undefined : allowedTools}
value={
existingAllowedTools === null && allowedTools.length === 0
? undefined
: allowedTools
}
onChange={(allowed) => onAllowedToolsChange(allowed)}
/>
)}
Expand Down
Loading