Skip to content

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]

fix: remove adding Mcp-Protocol-Version header (#14069)

Yuta Saito6c291093e9fd
diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py
index c97da6624ac..71ad721f423 100644
--- a/litellm/experimental_mcp_client/client.py
+++ b/litellm/experimental_mcp_client/client.py
@@ -19,8 +19,6 @@ from litellm._logging import verbose_logger
from litellm.types.mcp import (
MCPAuth,
MCPAuthType,
- MCPSpecVersion,
- MCPSpecVersionType,
MCPStdioConfig,
MCPTransport,
MCPTransportType,
@@ -48,7 +46,6 @@ class MCPClient:
auth_value: Optional[str] = None,
timeout: float = 60.0,
stdio_config: Optional[MCPStdioConfig] = None,
- protocol_version: MCPSpecVersionType = MCPSpecVersion.jun_2025,
):
self.server_url: str = server_url
self.transport_type: MCPTransport = transport_type
@@ -62,7 +59,6 @@ class MCPClient:
self._session_ctx = None
self._task: Optional[asyncio.Task] = None
self.stdio_config: Optional[MCPStdioConfig] = stdio_config
- self.protocol_version: MCPSpecVersionType = protocol_version
# handle the basic auth value if provided
if auth_value:
@@ -84,22 +80,24 @@ class MCPClient:
"""Initialize the transport and session."""
if self._session:
return # Already connected
-
+
try:
if self.transport_type == MCPTransport.stdio:
# For stdio transport, use stdio_client with command-line parameters
if not self.stdio_config:
raise ValueError("stdio_config is required for stdio transport")
-
+
server_params = StdioServerParameters(
command=self.stdio_config.get("command", ""),
args=self.stdio_config.get("args", []),
- env=self.stdio_config.get("env", {})
+ env=self.stdio_config.get("env", {}),
)
-
+
self._transport_ctx = stdio_client(server_params)
self._transport = await self._transport_ctx.__aenter__()
- self._session_ctx = ClientSession(self._transport[0], self._transport[1])
+ self._session_ctx = ClientSession(
+ self._transport[0], self._transport[1]
+ )
self._session = await self._session_ctx.__aenter__()
await self._session.initialize()
elif self.transport_type == MCPTransport.sse:
@@ -110,7 +108,9 @@ class MCPClient:
headers=headers,
)
self._transport = await self._transport_ctx.__aenter__()
- self._session_ctx = ClientSession(self._transport[0], self._transport[1])
+ self._session_ctx = ClientSession(
+ self._transport[0], self._transport[1]
+ )
self._session = await self._session_ctx.__aenter__()
await self._session.initialize()
else: # http
@@ -121,7 +121,9 @@ class MCPClient:
headers=headers,
)
self._transport = await self._transport_ctx.__aenter__()
- self._session_ctx = ClientSession(self._transport[0], self._transport[1])
+ self._session_ctx = ClientSession(
+ self._transport[0], self._transport[1]
+ )
self._session = await self._session_ctx.__aenter__()
await self._session.initialize()
except ValueError as e:
@@ -185,7 +187,7 @@ class MCPClient:
def _get_auth_headers(self) -> dict:
"""Generate authentication headers based on auth type."""
headers = {}
-
+
if self._mcp_auth_value:
if self.auth_type == MCPAuth.bearer_token:
headers["Authorization"] = f"Bearer {self._mcp_auth_value}"
@@ -196,18 +198,8 @@ class MCPClient:
elif self.auth_type == MCPAuth.authorization:
headers["Authorization"] = self._mcp_auth_value
- # Handle protocol version - it might be a string or enum
- if hasattr(self.protocol_version, 'value'):
- # It's an enum
- protocol_version_str = self.protocol_version.value
- else:
- # It's a string
- protocol_version_str = str(self.protocol_version)
-
- headers["MCP-Protocol-Version"] = protocol_version_str
return headers
-
async def list_tools(self) -> List[MCPTool]:
"""List available tools from the server."""
if not self._session:
@@ -216,7 +208,7 @@ class MCPClient:
except Exception as e:
verbose_logger.warning(f"MCP client connection failed: {str(e)}")
return []
-
+
if self._session is None:
verbose_logger.warning("MCP client session is not initialized")
return []
@@ -245,17 +237,20 @@ class MCPClient:
except Exception as e:
verbose_logger.warning(f"MCP client connection failed: {str(e)}")
return MCPCallToolResult(
- content=[TextContent(type="text", text=f"{str(e)}")],
- isError=True
+ content=[TextContent(type="text", text=f"{str(e)}")], isError=True
)
if self._session is None:
verbose_logger.warning("MCP client session is not initialized")
return MCPCallToolResult(
- content=[TextContent(type="text", text="MCP client session is not initialized")],
+ content=[
+ TextContent(
+ type="text", text="MCP client session is not initialized"
+ )
+ ],
isError=True,
)
-
+
try:
tool_result = await self._session.call_tool(
name=call_tool_request_params.name,
@@ -270,8 +265,8 @@ class MCPClient:
await self.disconnect()
# Return a default error result instead of raising
return MCPCallToolResult(
- content=[TextContent(type="text", text=f"{str(e)}")], # Empty content for error case
+ content=[
+ TextContent(type="text", text=f"{str(e)}")
+ ], # Empty content for error case
isError=True,
)
-
-
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
index a075de13fb1..6afed97fe93 100644
--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
@@ -28,12 +28,16 @@ class MCPRequestHandler:
LITELLM_MCP_SERVERS_HEADER_NAME = SpecialHeaders.mcp_servers.value
LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME = SpecialHeaders.mcp_access_groups.value
-
+
# MCP Protocol Version header
MCP_PROTOCOL_VERSION_HEADER_NAME = "MCP-Protocol-Version"
@staticmethod
- async def process_mcp_request(scope: Scope) -> Tuple[UserAPIKeyAuth, Optional[str], Optional[List[str]], Optional[Dict[str, str]], Optional[str]]:
+ async def process_mcp_request(
+ scope: Scope,
+ ) -> Tuple[
+ UserAPIKeyAuth, Optional[str], Optional[List[str]], Optional[Dict[str, str]]
+ ]:
"""
Process and validate MCP request headers from the ASGI scope.
This includes:
@@ -49,7 +53,6 @@ class MCPRequestHandler:
mcp_auth_header: Optional[str] MCP auth header to be passed to the MCP server (deprecated)
mcp_servers: Optional[List[str]] List of MCP servers and access groups to use
mcp_server_auth_headers: Optional[Dict[str, str]] Server-specific auth headers in format {server_alias: auth_value}
- mcp_protocol_version: Optional[str] MCP protocol version from request header
Raises:
HTTPException: If headers are invalid or missing required headers
@@ -58,39 +61,50 @@ class MCPRequestHandler:
litellm_api_key = (
MCPRequestHandler.get_litellm_api_key_from_headers(headers) or ""
)
-
+
# Get the old mcp_auth_header for backward compatibility
mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(headers)
-
- # Get the new server-specific auth headers
- mcp_server_auth_headers = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
- # Get MCP protocol version from header
- mcp_protocol_version = headers.get(MCPRequestHandler.MCP_PROTOCOL_VERSION_HEADER_NAME)
+ # Get the new server-specific auth headers
+ mcp_server_auth_headers = (
+ MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ )
# Parse MCP servers from header
- mcp_servers_header = headers.get(MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME)
+ mcp_servers_header = headers.get(
+ MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME
+ )
verbose_logger.debug(f"Raw MCP servers header: {mcp_servers_header}")
mcp_servers = None
if mcp_servers_header is not None:
try:
- mcp_servers = [s.strip() for s in mcp_servers_header.split(",") if s.strip()]
+ mcp_servers = [
+ s.strip() for s in mcp_servers_header.split(",") if s.strip()
+ ]
verbose_logger.debug(f"Parsed MCP servers: {mcp_servers}")
except Exception as e:
verbose_logger.debug(f"Error parsing mcp_servers header: {e}")
mcp_servers = None
- if mcp_servers_header == "" or (mcp_servers is not None and len(mcp_servers) == 0):
+ if mcp_servers_header == "" or (
+ mcp_servers is not None and len(mcp_servers) == 0
+ ):
mcp_servers = []
# Create a proper Request object with mock body method to avoid ASGI receive channel issues
request = Request(scope=scope)
+
async def mock_body():
return b"{}"
+
request.body = mock_body # type: ignore
validated_user_api_key_auth = await user_api_key_auth(
api_key=litellm_api_key, request=request
)
- return validated_user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version
-
+ return (
+ validated_user_api_key_auth,
+ mcp_auth_header,
+ mcp_servers,
+ mcp_server_auth_headers,
+ )
@staticmethod
def _get_mcp_auth_header_from_headers(headers: Headers) -> Optional[str]:
@@ -104,10 +118,12 @@ class MCPRequestHandler:
Support this auth: https://docs.litellm.ai/docs/mcp#using-your-mcp-with-client-side-credentials
If you want to use a different header name, you can set the `LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME` in the secret manager or `mcp_client_side_auth_header_name` in the general settings.
-
+
DEPRECATED: This method is deprecated in favor of server-specific auth headers using the format x-mcp-{{server_alias}}-{{header_name}} instead.
"""
- mcp_client_side_auth_header_name: str = MCPRequestHandler._get_mcp_client_side_auth_header_name()
+ mcp_client_side_auth_header_name: str = (
+ MCPRequestHandler._get_mcp_client_side_auth_header_name()
+ )
auth_header = headers.get(mcp_client_side_auth_header_name)
if auth_header:
verbose_logger.warning(
@@ -115,42 +131,49 @@ class MCPRequestHandler:
f"Please use server-specific auth headers in the format 'x-mcp-{{server_alias}}-{{header_name}}' instead."
)
return auth_header
-
+
@staticmethod
def _get_mcp_server_auth_headers_from_headers(headers: Headers) -> Dict[str, str]:
"""
Parse server-specific MCP auth headers from the request headers.
-
+
Looks for headers in the format: x-mcp-{server_alias}-{header_name}
Examples:
- x-mcp-github-authorization: Bearer token123
- x-mcp-zapier-x-api-key: api_key_456
- x-mcp-deepwiki-authorization: Basic base64_encoded_creds
-
+
Returns:
Dict[str, str]: Mapping of server alias to auth value
"""
server_auth_headers = {}
prefix = "x-mcp-"
-
+
for header_name, header_value in headers.items():
if header_name.lower().startswith(prefix):
# Skip the access groups header as it's not a server auth header
- if header_name.lower() == MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME.lower() or header_name.lower() == MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME.lower():
+ if (
+ header_name.lower()
+ == MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME.lower()
+ or header_name.lower()
+ == MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME.lower()
+ ):
continue
-
+
# Extract server_alias and header_name from x-mcp-{server_alias}-{header_name}
- remaining = header_name[len(prefix):].lower()
- if '-' in remaining:
+ remaining = header_name[len(prefix) :].lower()
+ if "-" in remaining:
# Split on the last dash to separate server_alias from header_name
- parts = remaining.rsplit('-', 1)
+ parts = remaining.rsplit("-", 1)
if len(parts) == 2:
server_alias, auth_header_name = parts
server_auth_headers[server_alias] = header_value
- verbose_logger.debug(f"Found server auth header: {server_alias} -> {auth_header_name}: {header_value[:10]}...")
-
+ verbose_logger.debug(
+ f"Found server auth header: {server_alias} -> {auth_header_name}: {header_value[:10]}..."
+ )
+
return server_auth_headers
-
+
@staticmethod
def _get_mcp_client_side_auth_header_name() -> str:
"""
@@ -162,14 +185,22 @@ class MCPRequestHandler:
"""
from litellm.proxy.proxy_server import general_settings
from litellm.secret_managers.main import get_secret_str
- MCP_CLIENT_SIDE_AUTH_HEADER_NAME: str = MCPRequestHandler.LITELLM_MCP_AUTH_HEADER_NAME
+
+ MCP_CLIENT_SIDE_AUTH_HEADER_NAME: str = (
+ MCPRequestHandler.LITELLM_MCP_AUTH_HEADER_NAME
+ )
if get_secret_str("LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME") is not None:
- MCP_CLIENT_SIDE_AUTH_HEADER_NAME = get_secret_str("LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME") or MCP_CLIENT_SIDE_AUTH_HEADER_NAME
+ MCP_CLIENT_SIDE_AUTH_HEADER_NAME = (
+ get_secret_str("LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME")
+ or MCP_CLIENT_SIDE_AUTH_HEADER_NAME
+ )
elif general_settings.get("mcp_client_side_auth_header_name") is not None:
- MCP_CLIENT_SIDE_AUTH_HEADER_NAME = general_settings.get("mcp_client_side_auth_header_name") or MCP_CLIENT_SIDE_AUTH_HEADER_NAME
+ MCP_CLIENT_SIDE_AUTH_HEADER_NAME = (
+ general_settings.get("mcp_client_side_auth_header_name")
+ or MCP_CLIENT_SIDE_AUTH_HEADER_NAME
+ )
return MCP_CLIENT_SIDE_AUTH_HEADER_NAME
-
@staticmethod
def get_litellm_api_key_from_headers(headers: Headers) -> Optional[str]:
"""
@@ -229,10 +260,14 @@ class MCPRequestHandler:
try:
allowed_mcp_servers: List[str] = []
allowed_mcp_servers_for_key = (
- await MCPRequestHandler._get_allowed_mcp_servers_for_key(user_api_key_auth)
+ await MCPRequestHandler._get_allowed_mcp_servers_for_key(
+ user_api_key_auth
+ )
)
allowed_mcp_servers_for_team = (
- await MCPRequestHandler._get_allowed_mcp_servers_for_team(user_api_key_auth)
+ await MCPRequestHandler._get_allowed_mcp_servers_for_team(
+ user_api_key_auth
+ )
)
#########################################################
@@ -274,7 +309,9 @@ class MCPRequestHandler:
try:
key_object_permission = (
await prisma_client.db.litellm_objectpermissiontable.find_unique(
- where={"object_permission_id": user_api_key_auth.object_permission_id},
+ where={
+ "object_permission_id": user_api_key_auth.object_permission_id
+ },
)
)
if key_object_permission is None:
@@ -282,17 +319,21 @@ class MCPRequestHandler:
# Get direct MCP servers
direct_mcp_servers = key_object_permission.mcp_servers or []
-
+
# Get MCP servers from access groups
- access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups(
- key_object_permission.mcp_access_groups or []
+ access_group_servers = (
+ await MCPRequestHandler._get_mcp_servers_from_access_groups(
+ key_object_permission.mcp_access_groups or []
+ )
)
-
+
# Combine both lists
all_servers = direct_mcp_servers + access_group_servers
return list(set(all_servers))
except Exception as e:
- verbose_logger.warning(f"Failed to get allowed MCP servers for key: {str(e)}")
+ verbose_logger.warning(
+ f"Failed to get allowed MCP servers for key: {str(e)}"
+ )
return []
@staticmethod
@@ -318,10 +359,10 @@ class MCPRequestHandler:
return []
try:
- team_obj: Optional[LiteLLM_TeamTable] = (
- await prisma_client.db.litellm_teamtable.find_unique(
- where={"team_id": user_api_key_auth.team_id},
- )
+ team_obj: Optional[
+ LiteLLM_TeamTable
+ ] = await prisma_client.db.litellm_teamtable.find_unique(
+ where={"team_id": user_api_key_auth.team_id},
)
if team_obj is None:
verbose_logger.debug("team_obj is None")
@@ -333,21 +374,27 @@ class MCPRequestHandler:
# Get direct MCP servers
direct_mcp_servers = object_permissions.mcp_servers or []
-
+
# Get MCP servers from access groups
- access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups(
- object_permissions.mcp_access_groups or []
+ access_group_servers = (
+ await MCPRequestHandler._get_mcp_servers_from_access_groups(
+ object_permissions.mcp_access_groups or []
+ )
)
-
+
# Combine both lists
all_servers = direct_mcp_servers + access_group_servers
return list(set(all_servers))
except Exception as e:
- verbose_logger.warning(f"Failed to get allowed MCP servers for team: {str(e)}")
+ verbose_logger.warning(
+ f"Failed to get allowed MCP servers for team: {str(e)}"
+ )
return []
@staticmethod
- def _get_config_server_ids_for_access_groups(config_mcp_servers, access_groups: List[str]) -> Set[str]:
+ def _get_config_server_ids_for_access_groups(
+ config_mcp_servers, access_groups: List[str]
+ ) -> Set[str]:
"""
Helper to get server_ids from config-loaded servers that match any of the given access groups.
"""
@@ -359,7 +406,9 @@ class MCPRequestHandler:
return server_ids
@staticmethod
- async def _get_db_server_ids_for_access_groups(prisma_client, access_groups: List[str]) -> Set[str]:
+ async def _get_db_server_ids_for_access_groups(
+ prisma_client, access_groups: List[str]
+ ) -> Set[str]:
"""
Helper to get server_ids from DB servers that match any of the given access groups.
"""
@@ -367,21 +416,19 @@ class MCPRequestHandler:
if access_groups and prisma_client is not None:
try:
mcp_servers = await prisma_client.db.litellm_mcpservertable.find_many(
- where={
- "mcp_access_groups": {
- "hasSome": access_groups
- }
- }
+ where={"mcp_access_groups": {"hasSome": access_groups}}
)
for server in mcp_servers:
server_ids.add(server.server_id)
except Exception as e:
- verbose_logger.debug(f"Error getting MCP servers from access groups: {e}")
+ verbose_logger.debug(
+ f"Error getting MCP servers from access groups: {e}"
+ )
return server_ids
@staticmethod
async def _get_mcp_servers_from_access_groups(
- access_groups: List[str]
+ access_groups: List[str],
) -> List[str]:
"""
Resolve MCP access groups to server IDs by querying BOTH the MCP server table (DB) AND config-loaded servers
@@ -390,22 +437,28 @@ class MCPRequestHandler:
try:
# Import here to avoid circular import
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager
-
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ global_mcp_server_manager,
+ )
+
# Use the new helper for config-loaded servers
server_ids = MCPRequestHandler._get_config_server_ids_for_access_groups(
global_mcp_server_manager.config_mcp_servers, access_groups
)
# Use the new helper for DB servers
- db_server_ids = await MCPRequestHandler._get_db_server_ids_for_access_groups(
- prisma_client, access_groups
+ db_server_ids = (
+ await MCPRequestHandler._get_db_server_ids_for_access_groups(
+ prisma_client, access_groups
+ )
)
server_ids.update(db_server_ids)
return list(server_ids)
except Exception as e:
- verbose_logger.warning(f"Failed to get MCP servers from access groups: {str(e)}")
+ verbose_logger.warning(
+ f"Failed to get MCP servers from access groups: {str(e)}"
+ )
return []
@staticmethod
@@ -418,8 +471,8 @@ class MCPRequestHandler:
from typing import List
access_groups: List[str] = []
- access_groups_for_key = (
- await MCPRequestHandler._get_mcp_access_groups_for_key(user_api_key_auth)
+ access_groups_for_key = await MCPRequestHandler._get_mcp_access_groups_for_key(
+ user_api_key_auth
)
access_groups_for_team = (
await MCPRequestHandler._get_mcp_access_groups_for_team(user_api_key_auth)
@@ -482,10 +535,10 @@ class MCPRequestHandler:
verbose_logger.debug("prisma_client is None")
return []
- team_obj: Optional[LiteLLM_TeamTable] = (
- await prisma_client.db.litellm_teamtable.find_unique(
- where={"team_id": user_api_key_auth.team_id},
- )
+ team_obj: Optional[
+ LiteLLM_TeamTable
+ ] = await prisma_client.db.litellm_teamtable.find_unique(
+ where={"team_id": user_api_key_auth.team_id},
)
if team_obj is None:
verbose_logger.debug("team_obj is None")
@@ -502,10 +555,14 @@ class MCPRequestHandler:
"""
Extract and parse the x-mcp-access-groups header as a list of strings.
"""
- mcp_access_groups_header = headers.get(MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME)
+ mcp_access_groups_header = headers.get(
+ MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME
+ )
if mcp_access_groups_header is not None:
try:
- return [s.strip() for s in mcp_access_groups_header.split(",") if s.strip()]
+ return [
+ s.strip() for s in mcp_access_groups_header.split(",") if s.strip()
+ ]
except Exception:
return None
return None
@@ -516,4 +573,4 @@ class MCPRequestHandler:
Extract and parse the x-mcp-access-groups header from an ASGI scope.
"""
headers = MCPRequestHandler._safe_get_headers_from_scope(scope)
- return MCPRequestHandler.get_mcp_access_groups_from_headers(headers)
\ No newline at end of file
+ return MCPRequestHandler.get_mcp_access_groups_from_headers(headers)
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index b35b3ad93d5..79b309d6a30 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -239,7 +239,6 @@ class MCPServerManager:
env=server_config.get("env", None) or {},
# TODO: utility fn the default values
transport=server_config.get("transport", MCPTransport.http),
- spec_version=server_config.get("spec_version", MCPSpecVersion.jun_2025),
auth_type=server_config.get("auth_type", None),
authentication_token=server_config.get(
"authentication_token", server_config.get("auth_value", None)
@@ -287,7 +286,6 @@ class MCPServerManager:
server_name=getattr(mcp_server, "server_name", None),
url=mcp_server.url,
transport=cast(MCPTransportType, mcp_server.transport),
- spec_version=_convert_protocol_version_to_enum(mcp_server.spec_version),
auth_type=cast(MCPAuthType, mcp_server.auth_type),
mcp_info=MCPInfo(
server_name=mcp_server.server_name or mcp_server.server_id,
@@ -350,7 +348,6 @@ class MCPServerManager:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
) -> List[MCPTool]:
"""
List all tools available across all MCP Servers.
@@ -390,7 +387,6 @@ class MCPServerManager:
tools = await self._get_tools_from_server(
server=server,
mcp_auth_header=server_auth_header,
- mcp_protocol_version=mcp_protocol_version,
)
list_tools_result.extend(tools)
verbose_logger.info(
@@ -414,7 +410,6 @@ class MCPServerManager:
self,
server: MCPServer,
mcp_auth_header: Optional[str] = None,
- protocol_version: Optional[str] = None,
) -> MCPClient:
"""
Create an MCPClient instance for the given server.
@@ -422,18 +417,12 @@ class MCPServerManager:
Args:
server (MCPServer): The server configuration
mcp_auth_header: MCP auth header to be passed to the MCP server. This is optional and will be used if provided.
- protocol_version: Optional MCP protocol version to use. If not provided, uses server's default.
Returns:
MCPClient: Configured MCP client instance
"""
transport = server.transport or MCPTransport.sse
- # Convert protocol version string to enum
- protocol_version_enum = _convert_protocol_version_to_enum(
- protocol_version or server.spec_version
- )
-
# Handle stdio transport
if transport == MCPTransport.stdio:
# For stdio, we need to get the stdio config from the server
@@ -450,7 +439,6 @@ class MCPServerManager:
auth_value=mcp_auth_header or server.authentication_token,
timeout=60.0,
stdio_config=stdio_config,
- protocol_version=protocol_version_enum,
)
else:
# For HTTP/SSE transports
@@ -461,14 +449,12 @@ class MCPServerManager:
auth_type=server.auth_type,
auth_value=mcp_auth_header or server.authentication_token,
timeout=60.0,
- protocol_version=protocol_version_enum,
)
async def _get_tools_from_server(
self,
server: MCPServer,
mcp_auth_header: Optional[str] = None,
- mcp_protocol_version: Optional[str] = None,
) -> List[MCPTool]:
"""
Helper method to get tools from a single MCP server with prefixed names.
@@ -483,22 +469,18 @@ class MCPServerManager:
verbose_logger.debug(f"Connecting to url: {server.url}")
verbose_logger.info(f"_get_tools_from_server for {server.name}...")
- protocol_version = (
- mcp_protocol_version if mcp_protocol_version else server.spec_version
- )
client = None
try:
client = self._create_mcp_client(
server=server,
mcp_auth_header=mcp_auth_header,
- protocol_version=protocol_version,
)
tools = await self._fetch_tools_with_timeout(client, server.name)
-
+
prefixed_tools = self._create_prefixed_tools(tools, server)
-
+
return prefixed_tools
except Exception as e:
@@ -530,7 +512,7 @@ class MCPServerManager:
async def _list_tools_task():
try:
await client.connect()
-
+
tools = await client.list_tools()
verbose_logger.debug(f"Tools from {server_name}: {tools}")
return tools
@@ -609,7 +591,6 @@ class MCPServerManager:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> CallToolResult:
"""
@@ -660,32 +641,54 @@ class MCPServerManager:
"arguments": arguments,
"server_name": server_name_from_prefix,
"user_api_key_auth": user_api_key_auth,
- "user_api_key_user_id": getattr(user_api_key_auth, 'user_id', None) if user_api_key_auth else None,
- "user_api_key_team_id": getattr(user_api_key_auth, 'team_id', None) if user_api_key_auth else None,
- "user_api_key_end_user_id": getattr(user_api_key_auth, 'end_user_id', None) if user_api_key_auth else None,
- "user_api_key_hash": getattr(user_api_key_auth, 'api_key_hash', None) if user_api_key_auth else None,
+ "user_api_key_user_id": getattr(user_api_key_auth, "user_id", None)
+ if user_api_key_auth
+ else None,
+ "user_api_key_team_id": getattr(user_api_key_auth, "team_id", None)
+ if user_api_key_auth
+ else None,
+ "user_api_key_end_user_id": getattr(
+ user_api_key_auth, "end_user_id", None
+ )
+ if user_api_key_auth
+ else None,
+ "user_api_key_hash": getattr(user_api_key_auth, "api_key_hash", None)
+ if user_api_key_auth
+ else None,
}
-
+
# Create MCP request object for processing
- mcp_request_obj = proxy_logging_obj._create_mcp_request_object_from_kwargs(pre_hook_kwargs)
-
+ mcp_request_obj = proxy_logging_obj._create_mcp_request_object_from_kwargs(
+ pre_hook_kwargs
+ )
+
# Convert to LLM format for existing guardrail compatibility
- synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(mcp_request_obj, pre_hook_kwargs)
-
+ synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(
+ mcp_request_obj, pre_hook_kwargs
+ )
+
try:
# Use standard pre_call_hook with call_type="mcp_call"
modified_data = await proxy_logging_obj.pre_call_hook(
- user_api_key_dict=user_api_key_auth, #type: ignore
+ user_api_key_dict=user_api_key_auth, # type: ignore
data=synthetic_llm_data,
- call_type="mcp_call" #type: ignore
+ call_type="mcp_call", # type: ignore
)
if modified_data:
# Convert response back to MCP format and apply modifications
- modified_kwargs = proxy_logging_obj._convert_mcp_hook_response_to_kwargs(modified_data, pre_hook_kwargs)
+ modified_kwargs = (
+ proxy_logging_obj._convert_mcp_hook_response_to_kwargs(
+ modified_data, pre_hook_kwargs
+ )
+ )
if modified_kwargs.get("arguments") != arguments:
arguments = modified_kwargs["arguments"]
-
- except (BlockedPiiEntityError, GuardrailRaisedException, HTTPException) as e:
+
+ except (
+ BlockedPiiEntityError,
+ GuardrailRaisedException,
+ HTTPException,
+ ) as e:
# Re-raise guardrail exceptions to properly fail the MCP call
verbose_logger.error(
f"Guardrail blocked MCP tool call pre call: {str(e)}"
@@ -706,11 +709,9 @@ class MCPServerManager:
client = self._create_mcp_client(
server=mcp_server,
mcp_auth_header=server_auth_header,
- protocol_version=mcp_protocol_version,
)
async with client:
-
# Use the original tool name (without prefix) for the actual call
call_tool_params = MCPCallToolRequestParams(
name=original_tool_name,
@@ -721,7 +722,7 @@ class MCPServerManager:
# Create synthetic LLM data for during hook processing
from litellm.types.llms.base import HiddenParams
from litellm.types.mcp import MCPDuringCallRequestObject
-
+
request_obj = MCPDuringCallRequestObject(
tool_name=name,
arguments=arguments,
@@ -729,28 +730,29 @@ class MCPServerManager:
start_time=start_time.timestamp() if start_time else None,
hidden_params=HiddenParams(),
)
-
+
during_hook_kwargs = {
"name": name,
"arguments": arguments,
"server_name": server_name_from_prefix,
"user_api_key_auth": user_api_key_auth,
}
-
- synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(request_obj, during_hook_kwargs)
-
+
+ synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(
+ request_obj, during_hook_kwargs
+ )
+
during_hook_task = asyncio.create_task(
proxy_logging_obj.during_call_hook(
user_api_key_dict=user_api_key_auth,
data=synthetic_llm_data,
- call_type="mcp_call" #type: ignore
+ call_type="mcp_call", # type: ignore
)
)
tasks.append(during_hook_task)
tasks.append(asyncio.create_task(client.call_tool(call_tool_params)))
try:
-
mcp_responses = await asyncio.gather(*tasks)
# If proxy_logging_obj is None, the tool call result is at index 0
@@ -839,19 +841,21 @@ class MCPServerManager:
)
verbose_logger.info("Loading MCP servers from database into registry...")
-
+
# perform authz check to filter the mcp servers user has access to
prisma_client = get_prisma_client_or_throw(
"Database not connected. Connect a database to your proxy"
)
db_mcp_servers = await get_all_mcp_servers(prisma_client)
verbose_logger.info(f"Found {len(db_mcp_servers)} MCP servers in database")
-
+
# ensure the global_mcp_server_manager is up to date with the db
for server in db_mcp_servers:
- verbose_logger.debug(f"Adding server to registry: {server.server_id} ({server.server_name})")
+ verbose_logger.debug(
+ f"Adding server to registry: {server.server_id} ({server.server_name})"
+ )
self.add_update_server(server)
-
+
verbose_logger.info(f"Registry now contains {len(self.get_registry())} servers")
def get_mcp_server_by_id(self, server_id: str) -> Optional[MCPServer]:
@@ -1054,7 +1058,9 @@ class MCPServerManager:
auth_type=_server_config.auth_type,
created_at=datetime.datetime.now(),
updated_at=datetime.datetime.now(),
- description=_server_config.mcp_info.get("description") if _server_config.mcp_info else None,
+ description=_server_config.mcp_info.get("description")
+ if _server_config.mcp_info
+ else None,
mcp_info=_server_config.mcp_info,
mcp_access_groups=_server_config.access_groups or [],
# Stdio-specific fields
diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
index 048b25fa35a..9d88b979b62 100644
--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
@@ -34,18 +34,24 @@ if MCP_AVAILABLE:
########################################################
############ MCP Server REST API Routes #################
def _get_server_auth_header(
- server, mcp_server_auth_headers: Optional[Dict[str, str]], mcp_auth_header: Optional[str]
+ server,
+ mcp_server_auth_headers: Optional[Dict[str, str]],
+ mcp_auth_header: Optional[str],
) -> Optional[str]:
"""Helper function to get server-specific auth header with case-insensitive matching."""
if mcp_server_auth_headers and server.alias:
normalized_server_alias = server.alias.lower()
- normalized_headers = {k.lower(): v for k, v in mcp_server_auth_headers.items()}
+ normalized_headers = {
+ k.lower(): v for k, v in mcp_server_auth_headers.items()
+ }
server_auth = normalized_headers.get(normalized_server_alias)
if server_auth is not None:
return server_auth
elif mcp_server_auth_headers and server.server_name:
normalized_server_name = server.server_name.lower()
- normalized_headers = {k.lower(): v for k, v in mcp_server_auth_headers.items()}
+ normalized_headers = {
+ k.lower(): v for k, v in mcp_server_auth_headers.items()
+ }
server_auth = normalized_headers.get(normalized_server_name)
if server_auth is not None:
return server_auth
@@ -63,12 +69,11 @@ if MCP_AVAILABLE:
for tool in tools
]
- async def _get_tools_for_single_server(server, server_auth_header, mcp_protocol_version):
+ async def _get_tools_for_single_server(server, server_auth_header):
"""Helper function to get tools for a single server."""
tools = await global_mcp_server_manager._get_tools_from_server(
server=server,
mcp_auth_header=server_auth_header,
- mcp_protocol_version=mcp_protocol_version,
)
return _create_tool_response_objects(tools, server.mcp_info)
@@ -104,17 +109,20 @@ if MCP_AVAILABLE:
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
MCPRequestHandler,
)
-
+
try:
# Extract auth headers from request
headers = request.headers
- mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(headers)
- mcp_server_auth_headers = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
- mcp_protocol_version = headers.get(MCPRequestHandler.MCP_PROTOCOL_VERSION_HEADER_NAME)
-
+ mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(
+ headers
+ )
+ mcp_server_auth_headers = (
+ MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ )
+
list_tools_result = []
error_message = None
-
+
# If server_id is specified, only query that specific server
if server_id:
server = global_mcp_server_manager.get_mcp_server_by_id(server_id)
@@ -122,49 +130,67 @@ if MCP_AVAILABLE:
return {
"tools": [],
"error": "server_not_found",
- "message": f"Server with id {server_id} not found"
+ "message": f"Server with id {server_id} not found",
}
-
- server_auth_header = _get_server_auth_header(server, mcp_server_auth_headers, mcp_auth_header)
-
+
+ server_auth_header = _get_server_auth_header(
+ server, mcp_server_auth_headers, mcp_auth_header
+ )
+
try:
- list_tools_result = await _get_tools_for_single_server(server, server_auth_header, mcp_protocol_version)
+ list_tools_result = await _get_tools_for_single_server(
+ server, server_auth_header
+ )
except Exception as e:
- verbose_logger.exception(f"Error getting tools from {server.name}: {e}")
+ verbose_logger.exception(
+ f"Error getting tools from {server.name}: {e}"
+ )
return {
"tools": [],
"error": "server_error",
- "message": f"Failed to get tools from server {server.name}: {str(e)}"
+ "message": f"Failed to get tools from server {server.name}: {str(e)}",
}
else:
# Query all servers
errors = []
for server in global_mcp_server_manager.get_registry().values():
- server_auth_header = _get_server_auth_header(server, mcp_server_auth_headers, mcp_auth_header)
-
+ server_auth_header = _get_server_auth_header(
+ server, mcp_server_auth_headers, mcp_auth_header
+ )
+
try:
- tools_result = await _get_tools_for_single_server(server, server_auth_header, mcp_protocol_version)
+ tools_result = await _get_tools_for_single_server(
+ server, server_auth_header
+ )
list_tools_result.extend(tools_result)
except Exception as e:
- verbose_logger.exception(f"Error getting tools from {server.name}: {e}")
+ verbose_logger.exception(
+ f"Error getting tools from {server.name}: {e}"
+ )
errors.append(f"{server.name}: {str(e)}")
continue
-
+
if errors and not list_tools_result:
- error_message = "Failed to get tools from servers: " + "; ".join(errors)
-
+ error_message = "Failed to get tools from servers: " + "; ".join(
+ errors
+ )
+
return {
"tools": list_tools_result,
"error": "partial_failure" if error_message else None,
- "message": error_message if error_message else "Successfully retrieved tools"
+ "message": error_message
+ if error_message
+ else "Successfully retrieved tools",
}
-
+
except Exception as e:
- verbose_logger.exception("Unexpected error in list_tool_rest_api: %s", str(e))
+ verbose_logger.exception(
+ "Unexpected error in list_tool_rest_api: %s", str(e)
+ )
return {
"tools": [],
"error": "unexpected_error",
- "message": f"An unexpected error occurred: {str(e)}"
+ "message": f"An unexpected error occurred: {str(e)}",
}
@router.post("/tools/call", dependencies=[Depends(user_api_key_auth)])
@@ -196,9 +222,9 @@ if MCP_AVAILABLE:
detail={
"error": "blocked_pii_entity",
"message": str(e),
- "entity_type": getattr(e, 'entity_type', None),
- "guardrail_name": getattr(e, 'guardrail_name', None)
- }
+ "entity_type": getattr(e, "entity_type", None),
+ "guardrail_name": getattr(e, "guardrail_name", None),
+ },
)
except GuardrailRaisedException as e:
verbose_logger.error(f"GuardrailRaisedException in MCP tool call: {str(e)}")
@@ -207,8 +233,8 @@ if MCP_AVAILABLE:
detail={
"error": "guardrail_violation",
"message": str(e),
- "guardrail_name": getattr(e, 'guardrail_name', None)
- }
+ "guardrail_name": getattr(e, "guardrail_name", None),
+ },
)
except HTTPException as e:
# Re-raise HTTPException as-is to preserve status code and detail
@@ -220,10 +246,10 @@ if MCP_AVAILABLE:
status_code=500,
detail={
"error": "internal_server_error",
- "message": f"An unexpected error occurred: {str(e)}"
- }
+ "message": f"An unexpected error occurred: {str(e)}",
+ },
)
-
+
########################################################
# MCP Connection testing routes
# /health -> Test if we can connect to the MCP server
@@ -234,15 +260,15 @@ if MCP_AVAILABLE:
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
NewMCPServerRequest,
)
-
+
async def _execute_with_mcp_client(request: NewMCPServerRequest, operation):
"""
Common helper to create MCP client, execute operation, and ensure proper cleanup.
-
+
Args:
request: MCP server configuration
operation: Async function that takes a client and returns the operation result
-
+
Returns:
Operation result or error response
"""
@@ -254,15 +280,14 @@ if MCP_AVAILABLE:
name=request.alias or request.server_name or "",
url=request.url,
transport=request.transport,
- spec_version=_convert_protocol_version_to_enum(request.spec_version),
auth_type=request.auth_type,
mcp_info=request.mcp_info,
),
mcp_auth_header=None,
)
-
+
return await operation(client)
-
+
except Exception as e:
verbose_logger.error(f"Error in MCP operation: {e}", exc_info=True)
return {"status": "error", "message": "An internal error has occurred."}
@@ -273,6 +298,7 @@ if MCP_AVAILABLE:
await client.disconnect()
except Exception as e:
verbose_logger.warning(f"Error disconnecting MCP client: {e}")
+
@router.post("/test/connection")
async def test_connection(
request: NewMCPServerRequest,
@@ -280,13 +306,13 @@ if MCP_AVAILABLE:
"""
Test if we can connect to the provided MCP server before adding it
"""
+
async def _test_connection_operation(client):
await client.connect()
return {"status": "ok"}
-
+
return await _execute_with_mcp_client(request, _test_connection_operation)
-
-
+
@router.post("/test/tools/list")
async def test_tools_list(
request: NewMCPServerRequest,
@@ -295,13 +321,16 @@ if MCP_AVAILABLE:
"""
Preview tools available from MCP server before adding it
"""
+
async def _list_tools_operation(client):
list_tools_result: List[MCPTool] = await client.list_tools()
- model_dumped_tools: List[dict] = [tool.model_dump() for tool in list_tools_result]
+ model_dumped_tools: List[dict] = [
+ tool.model_dump() for tool in list_tools_result
+ ]
return {
"tools": model_dumped_tools,
"error": None,
- "message": "Successfully retrieved tools"
+ "message": "Successfully retrieved tools",
}
-
+
return await _execute_with_mcp_client(request, _list_tools_operation)
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index e095f73fcc9..3e45fccdc28 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -130,7 +130,9 @@ if MCP_AVAILABLE:
await _sse_session_manager_cm.__aenter__()
_SESSION_MANAGERS_INITIALIZED = True
- verbose_logger.info("MCP Server started with StreamableHTTP and SSE session managers!")
+ verbose_logger.info(
+ "MCP Server started with StreamableHTTP and SSE session managers!"
+ )
async def shutdown_session_managers():
"""Shutdown the session managers."""
@@ -171,11 +173,18 @@ if MCP_AVAILABLE:
"""
try:
# Get user authentication from context variable
- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = (
- get_auth_context()
+ (
+ user_api_key_auth,
+ mcp_auth_header,
+ mcp_servers,
+ mcp_server_auth_headers,
+ ) = get_auth_context()
+ verbose_logger.debug(
+ f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}"
+ )
+ verbose_logger.debug(
+ f"MCP list_tools - MCP servers from context: {mcp_servers}"
)
- verbose_logger.debug(f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}")
- verbose_logger.debug(f"MCP list_tools - MCP servers from context: {mcp_servers}")
verbose_logger.debug(
f"MCP list_tools - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}"
)
@@ -186,9 +195,10 @@ if MCP_AVAILABLE:
mcp_auth_header=mcp_auth_header,
mcp_servers=mcp_servers,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
)
- verbose_logger.info(f"MCP list_tools - Successfully returned {len(tools)} tools")
+ verbose_logger.info(
+ f"MCP list_tools - Successfully returned {len(tools)} tools"
+ )
return tools
except Exception as e:
verbose_logger.exception(f"Error in list_tools endpoint: {str(e)}")
@@ -220,9 +230,16 @@ if MCP_AVAILABLE:
from litellm.proxy.proxy_server import proxy_config
# Validate arguments
- user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers, mcp_protocol_version = get_auth_context()
-
- verbose_logger.debug(f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}")
+ (
+ user_api_key_auth,
+ mcp_auth_header,
+ _,
+ mcp_server_auth_headers,
+ ) = get_auth_context()
+
+ verbose_logger.debug(
+ f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}"
+ )
try:
# Create a body date for logging
body_data = {"name": name, "arguments": arguments}
@@ -249,17 +266,22 @@ if MCP_AVAILABLE:
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
**data, # for logging
)
except BlockedPiiEntityError as e:
verbose_logger.error(f"BlockedPiiEntityError in MCP tool call: {str(e)}")
# Return error as text content for MCP protocol
- return [TextContent(text=f"Error: Blocked PII entity detected - {str(e)}", type="text")]
+ return [
+ TextContent(
+ text=f"Error: Blocked PII entity detected - {str(e)}", type="text"
+ )
+ ]
except GuardrailRaisedException as e:
verbose_logger.error(f"GuardrailRaisedException in MCP tool call: {str(e)}")
# Return error as text content for MCP protocol
- return [TextContent(text=f"Error: Guardrail violation - {str(e)}", type="text")]
+ return [
+ TextContent(text=f"Error: Guardrail violation - {str(e)}", type="text")
+ ]
except HTTPException as e:
verbose_logger.error(f"HTTPException in MCP tool call: {str(e)}")
# Return error as text content for MCP protocol
@@ -287,6 +309,7 @@ if MCP_AVAILABLE:
Get the filtered MCP servers from the MCP server names
"""
from typing import Set
+
filtered_server_ids: Set[str] = set()
# Filter servers based on mcp_servers parameter if provided
if mcp_servers is not None:
@@ -297,7 +320,11 @@ if MCP_AVAILABLE:
server = global_mcp_server_manager.get_mcp_server_by_id(server_id)
if server:
- match_list = [s.lower() for s in [server.alias, server.server_name, server_id] if s is not None]
+ match_list = [
+ s.lower()
+ for s in [server.alias, server.server_name, server_id]
+ if s is not None
+ ]
if server_or_group.lower() in match_list:
filtered_server_ids.add(server_id)
@@ -306,19 +333,23 @@ if MCP_AVAILABLE:
if not server_name_matched:
try:
- access_group_server_ids = await MCPRequestHandler._get_mcp_servers_from_access_groups(
- [server_or_group]
+ access_group_server_ids = (
+ await MCPRequestHandler._get_mcp_servers_from_access_groups(
+ [server_or_group]
+ )
)
# Only include servers that the user has access to
for server_id in access_group_server_ids:
if server_id in allowed_mcp_servers:
filtered_server_ids.add(server_id)
except Exception as e:
- verbose_logger.debug(f"Could not resolve '{server_or_group}' as access group: {e}")
+ verbose_logger.debug(
+ f"Could not resolve '{server_or_group}' as access group: {e}"
+ )
if filtered_server_ids:
allowed_mcp_servers = list(filtered_server_ids)
-
+
return allowed_mcp_servers
async def _get_tools_from_mcp_servers(
@@ -326,7 +357,6 @@ if MCP_AVAILABLE:
mcp_auth_header: Optional[str],
mcp_servers: Optional[List[str]],
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
) -> List[MCPTool]:
"""
Helper method to fetch tools from MCP servers based on server filtering criteria.
@@ -344,7 +374,9 @@ if MCP_AVAILABLE:
return []
# Get allowed MCP servers based on user permissions
- allowed_mcp_servers = await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth)
+ allowed_mcp_servers = await global_mcp_server_manager.get_allowed_mcp_servers(
+ user_api_key_auth
+ )
if mcp_servers is not None:
allowed_mcp_servers = await _get_allowed_mcp_servers_from_mcp_server_names(
@@ -352,7 +384,6 @@ if MCP_AVAILABLE:
allowed_mcp_servers=allowed_mcp_servers,
)
-
# Get tools from each allowed server
all_tools = []
for server_id in allowed_mcp_servers:
@@ -375,15 +406,20 @@ if MCP_AVAILABLE:
tools = await global_mcp_server_manager._get_tools_from_server(
server=server,
mcp_auth_header=server_auth_header,
- mcp_protocol_version=mcp_protocol_version,
)
all_tools.extend(tools)
- verbose_logger.debug(f"Successfully fetched {len(tools)} tools from server {server.name}")
+ verbose_logger.debug(
+ f"Successfully fetched {len(tools)} tools from server {server.name}"
+ )
except Exception as e:
- verbose_logger.exception(f"Error getting tools from server {server.name}: {str(e)}")
+ verbose_logger.exception(
+ f"Error getting tools from server {server.name}: {str(e)}"
+ )
# Continue with other servers instead of failing completely
- verbose_logger.info(f"Successfully fetched {len(all_tools)} tools total from all MCP servers")
+ verbose_logger.info(
+ f"Successfully fetched {len(all_tools)} tools total from all MCP servers"
+ )
return all_tools
async def _list_mcp_tools(
@@ -391,7 +427,6 @@ if MCP_AVAILABLE:
mcp_auth_header: Optional[str] = None,
mcp_servers: Optional[List[str]] = None,
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
) -> List[MCPTool]:
"""
List all available MCP tools.
@@ -415,11 +450,14 @@ if MCP_AVAILABLE:
mcp_auth_header=mcp_auth_header,
mcp_servers=mcp_servers,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
)
- verbose_logger.debug(f"Successfully fetched {len(managed_tools)} tools from managed MCP servers")
+ verbose_logger.debug(
+ f"Successfully fetched {len(managed_tools)} tools from managed MCP servers"
+ )
except Exception as e:
- verbose_logger.exception(f"Error getting tools from managed MCP servers: {str(e)}")
+ verbose_logger.exception(
+ f"Error getting tools from managed MCP servers: {str(e)}"
+ )
# Continue with empty managed tools list instead of failing completely
# Get tools from local registry
@@ -430,10 +468,16 @@ if MCP_AVAILABLE:
# Convert local tools to MCPTool format
for tool in local_tools_raw:
# Convert from litellm.types.mcp_server.tool_registry.MCPTool to mcp.types.Tool
- mcp_tool = MCPTool(name=tool.name, description=tool.description, inputSchema=tool.input_schema)
+ mcp_tool = MCPTool(
+ name=tool.name,
+ description=tool.description,
+ inputSchema=tool.input_schema,
+ )
local_tools.append(mcp_tool)
except Exception as e:
- verbose_logger.exception(f"Error getting tools from local registry: {str(e)}")
+ verbose_logger.exception(
+ f"Error getting tools from local registry: {str(e)}"
+ )
# Continue with empty local tools list instead of failing completely
# Combine all tools
@@ -448,7 +492,6 @@ if MCP_AVAILABLE:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
**kwargs: Any,
) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""
@@ -456,35 +499,46 @@ if MCP_AVAILABLE:
"""
start_time = datetime.now()
if arguments is None:
- raise HTTPException(status_code=400, detail="Request arguments are required")
+ raise HTTPException(
+ status_code=400, detail="Request arguments are required"
+ )
# Remove prefix from tool name for logging and processing
- original_tool_name, server_name_from_prefix = get_server_name_prefix_tool_mcp(name)
+ original_tool_name, server_name_from_prefix = get_server_name_prefix_tool_mcp(
+ name
+ )
- standard_logging_mcp_tool_call: StandardLoggingMCPToolCall = _get_standard_logging_mcp_tool_call(
- name=original_tool_name, # Use original name for logging
- arguments=arguments,
- server_name=server_name_from_prefix,
+ standard_logging_mcp_tool_call: StandardLoggingMCPToolCall = (
+ _get_standard_logging_mcp_tool_call(
+ name=original_tool_name, # Use original name for logging
+ arguments=arguments,
+ server_name=server_name_from_prefix,
+ )
+ )
+ litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get(
+ "litellm_logging_obj", None
)
- litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get("litellm_logging_obj", None)
if litellm_logging_obj:
- litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = standard_logging_mcp_tool_call
+ litellm_logging_obj.model_call_details[
+ "mcp_tool_call_metadata"
+ ] = standard_logging_mcp_tool_call
litellm_logging_obj.model = f"MCP: {name}"
# Try managed server tool first (pass the full prefixed name)
# Primary and recommended way to use MCP servers
#########################################################
- mcp_server: Optional[MCPServer] = global_mcp_server_manager._get_mcp_server_from_tool_name(name)
+ mcp_server: Optional[
+ MCPServer
+ ] = global_mcp_server_manager._get_mcp_server_from_tool_name(name)
if mcp_server:
- standard_logging_mcp_tool_call["mcp_server_cost_info"] = (mcp_server.mcp_info or {}).get(
- "mcp_server_cost_info"
- )
+ standard_logging_mcp_tool_call["mcp_server_cost_info"] = (
+ mcp_server.mcp_info or {}
+ ).get("mcp_server_cost_info")
response = await _handle_managed_mcp_tool(
name=name, # Pass the full name (potentially prefixed)
arguments=arguments,
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
litellm_logging_obj=litellm_logging_obj,
)
@@ -537,7 +591,6 @@ if MCP_AVAILABLE:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
litellm_logging_obj: Optional[Any] = None,
) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""Handle tool execution for managed server tools"""
@@ -577,6 +630,7 @@ if MCP_AVAILABLE:
Get the MCP servers from the path
"""
import re
+
mcp_servers_from_path: Optional[List[str]] = None
# Match /mcp/<servers>/<optional_path>
# Where <servers> can be comma-separated list of server names
@@ -627,7 +681,6 @@ if MCP_AVAILABLE:
mcp_auth_header,
_,
mcp_server_auth_headers,
- mcp_protocol_version,
) = await MCPRequestHandler.process_mcp_request(scope)
mcp_servers = mcp_servers_from_path
else:
@@ -636,11 +689,12 @@ if MCP_AVAILABLE:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
- mcp_protocol_version,
) = await MCPRequestHandler.process_mcp_request(scope)
- return user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version
+ return user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers
- async def handle_streamable_http_mcp(scope: Scope, receive: Receive, send: Send) -> None:
+ async def handle_streamable_http_mcp(
+ scope: Scope, receive: Receive, send: Send
+ ) -> None:
"""Handle MCP requests through StreamableHTTP."""
try:
path = scope.get("path", "")
@@ -649,20 +703,19 @@ if MCP_AVAILABLE:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
- mcp_protocol_version,
) = await extract_mcp_auth_context(scope, path)
- verbose_logger.debug(f"MCP request mcp_servers (header/path): {mcp_servers}")
+ verbose_logger.debug(
+ f"MCP request mcp_servers (header/path): {mcp_servers}"
+ )
verbose_logger.debug(
f"MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}"
)
- verbose_logger.debug(f"MCP protocol version: {mcp_protocol_version}")
# Set the auth context variable for easy access in MCP functions
set_auth_context(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
mcp_servers=mcp_servers,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
)
# Ensure session managers are initialized
@@ -686,7 +739,9 @@ if MCP_AVAILABLE:
)
await error_response(scope, receive, send)
except Exception as response_error:
- verbose_logger.exception(f"Failed to send error response: {response_error}")
+ verbose_logger.exception(
+ f"Failed to send error response: {response_error}"
+ )
# If we can't send a proper response, re-raise the original error
raise e
@@ -699,19 +754,18 @@ if MCP_AVAILABLE:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
- mcp_protocol_version,
) = await extract_mcp_auth_context(scope, path)
- verbose_logger.debug(f"MCP request mcp_servers (header/path): {mcp_servers}")
+ verbose_logger.debug(
+ f"MCP request mcp_servers (header/path): {mcp_servers}"
+ )
verbose_logger.debug(
f"MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}"
)
- verbose_logger.debug(f"MCP protocol version: {mcp_protocol_version}")
set_auth_context(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
mcp_servers=mcp_servers,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
)
if not _SESSION_MANAGERS_INITIALIZED:
@@ -733,7 +787,9 @@ if MCP_AVAILABLE:
)
await error_response(scope, receive, send)
except Exception as response_error:
- verbose_logger.exception(f"Failed to send error response: {response_error}")
+ verbose_logger.exception(
+ f"Failed to send error response: {response_error}"
+ )
# If we can't send a proper response, re-raise the original error
raise e
@@ -769,7 +825,6 @@ if MCP_AVAILABLE:
mcp_auth_header: Optional[str] = None,
mcp_servers: Optional[List[str]] = None,
mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
) -> None:
"""
Set the UserAPIKeyAuth in the auth context variable.
@@ -785,13 +840,17 @@ if MCP_AVAILABLE:
mcp_auth_header=mcp_auth_header,
mcp_servers=mcp_servers,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=mcp_protocol_version,
)
auth_context_var.set(auth_user)
- def get_auth_context() -> Tuple[
- Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]], Optional[str]
- ]:
+ def get_auth_context() -> (
+ Tuple[
+ Optional[UserAPIKeyAuth],
+ Optional[str],
+ Optional[List[str]],
+ Optional[Dict[str, str]],
+ ]
+ ):
"""
Get the UserAPIKeyAuth from the auth context variable.
@@ -806,9 +865,8 @@ if MCP_AVAILABLE:
auth_user.mcp_auth_header,
auth_user.mcp_servers,
auth_user.mcp_server_auth_headers,
- auth_user.mcp_protocol_version,
)
- return None, None, None, None, None
+ return None, None, None, None
########################################################
############ End of Auth Context Functions #############
diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
index a26ae32229a..1912c54920c 100644
--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
@@ -1,5 +1,3 @@
-
-
"""
1. Allow proxy admin to perform create, update, and delete operations on MCP servers in the db.
2. Allows users to view the mcp servers they have access to.
@@ -82,7 +80,6 @@ if MCP_AVAILABLE:
return True
return False
-
# Router to fetch all MCP tools available for the current key
@router.get(
@@ -91,18 +88,18 @@ if MCP_AVAILABLE:
dependencies=[Depends(user_api_key_auth)],
)
async def get_mcp_tools(
- user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
Get all MCP tools available for the current key, including those from access groups
"""
from litellm.proxy._experimental.mcp_server.server import _list_mcp_tools
+
tools = await _list_mcp_tools(
user_api_key_auth=user_api_key_dict,
mcp_auth_header=None,
mcp_servers=None,
mcp_server_auth_headers=None,
- mcp_protocol_version=None,
)
dumped_tools = [dict(tool) for tool in tools]
@@ -114,7 +111,7 @@ if MCP_AVAILABLE:
dependencies=[Depends(user_api_key_auth)],
)
async def get_mcp_access_groups(
- user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
Get all available MCP access groups from the database AND config
@@ -136,7 +133,10 @@ if MCP_AVAILABLE:
try:
mcp_servers = await prisma_client.db.litellm_mcpservertable.find_many()
for server in mcp_servers:
- if hasattr(server, 'mcp_access_groups') and server.mcp_access_groups:
+ if (
+ hasattr(server, "mcp_access_groups")
+ and server.mcp_access_groups
+ ):
access_groups.update(server.mcp_access_groups)
except Exception as e:
verbose_proxy_logger.debug(f"Error getting MCP access groups: {e}")
@@ -194,10 +194,14 @@ if MCP_AVAILABLE:
# Perform health check using server manager
try:
- health_result = await global_mcp_server_manager.health_check_server(server_id)
+ health_result = await global_mcp_server_manager.health_check_server(
+ server_id
+ )
return health_result
except Exception as e:
- verbose_proxy_logger.exception(f"Error performing health check on MCP server {server_id}: {str(e)}")
+ verbose_proxy_logger.exception(
+ f"Error performing health check on MCP server {server_id}: {str(e)}"
+ )
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"error": f"Error performing health check: {str(e)}"},
@@ -220,19 +224,33 @@ if MCP_AVAILABLE:
"""
# Use server manager to get health checks for allowed servers
try:
- all_health_results = await global_mcp_server_manager.health_check_allowed_servers(
- user_api_key_auth=user_api_key_dict
+ all_health_results = (
+ await global_mcp_server_manager.health_check_allowed_servers(
+ user_api_key_auth=user_api_key_dict
+ )
)
-
+
return {
"total_servers": len(all_health_results),
- "healthy_count": len([r for r in all_health_results.values() if r["status"] == "healthy"]),
- "unhealthy_count": len([r for r in all_health_results.values() if r["status"] == "unhealthy"]),
- "unknown_count": len([r for r in all_health_results.values() if r["status"] == "unknown"]),
- "servers": all_health_results
+ "healthy_count": len(
+ [r for r in all_health_results.values() if r["status"] == "healthy"]
+ ),
+ "unhealthy_count": len(
+ [
+ r
+ for r in all_health_results.values()
+ if r["status"] == "unhealthy"
+ ]
+ ),
+ "unknown_count": len(
+ [r for r in all_health_results.values() if r["status"] == "unknown"]
+ ),
+ "servers": all_health_results,
}
except Exception as e:
- verbose_proxy_logger.exception(f"Error performing health checks on MCP servers: {str(e)}")
+ verbose_proxy_logger.exception(
+ f"Error performing health checks on MCP servers: {str(e)}"
+ )
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"error": f"Error performing health checks: {str(e)}"},
@@ -256,8 +274,10 @@ if MCP_AVAILABLE:
```
"""
# Use server manager to get all servers with health and team data
- return await global_mcp_server_manager.get_all_mcp_servers_with_health_and_teams(
- user_api_key_auth=user_api_key_dict
+ return (
+ await global_mcp_server_manager.get_all_mcp_servers_with_health_and_teams(
+ user_api_key_auth=user_api_key_dict
+ )
)
@router.get(
@@ -293,13 +313,23 @@ if MCP_AVAILABLE:
# Perform health check on the server using server manager
try:
- health_result = await global_mcp_server_manager.health_check_server(server_id)
+ health_result = await global_mcp_server_manager.health_check_server(
+ server_id
+ )
# Update the server object with health check results
mcp_server.status = health_result.get("status", "unknown")
- mcp_server.last_health_check = datetime.fromisoformat(health_result.get("last_health_check", datetime.now().isoformat())) if health_result.get("last_health_check") else None
+ mcp_server.last_health_check = (
+ datetime.fromisoformat(
+ health_result.get("last_health_check", datetime.now().isoformat())
+ )
+ if health_result.get("last_health_check")
+ else None
+ )
mcp_server.health_check_error = health_result.get("error")
except Exception as e:
- verbose_proxy_logger.debug(f"Error performing health check on server {server_id}: {e}")
+ verbose_proxy_logger.debug(
+ f"Error performing health check on server {server_id}: {e}"
+ )
mcp_server.status = "unknown"
mcp_server.last_health_check = datetime.now()
mcp_server.health_check_error = str(e)
@@ -390,7 +420,7 @@ if MCP_AVAILABLE:
touched_by=user_api_key_dict.user_id or LITELLM_PROXY_ADMIN_NAME,
)
global_mcp_server_manager.add_update_server(new_mcp_server)
-
+
# Ensure registry is up to date by reloading from database
await global_mcp_server_manager.reload_servers_from_database()
except Exception as e:
@@ -451,7 +481,7 @@ if MCP_AVAILABLE:
detail={"error": f"MCP Server not found, passed server_id={server_id}"},
)
global_mcp_server_manager.remove_server(mcp_server_record_deleted)
-
+
# Ensure registry is up to date by reloading from database
await global_mcp_server_manager.reload_servers_from_database()
@@ -526,7 +556,7 @@ if MCP_AVAILABLE:
},
)
global_mcp_server_manager.add_update_server(mcp_server_record_updated)
-
+
# Ensure registry is up to date by reloading from database
await global_mcp_server_manager.reload_servers_from_database()
@@ -535,4 +565,3 @@ if MCP_AVAILABLE:
pass
return mcp_server_record_updated
-
diff --git a/litellm/responses/mcp/litellm_proxy_mcp_handler.py b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
index 8470003b325..3e5ab38af2f 100644
--- a/litellm/responses/mcp/litellm_proxy_mcp_handler.py
+++ b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
@@ -13,6 +13,7 @@ else:
LITELLM_PROXY_MCP_SERVER_URL = "litellm_proxy"
LITELLM_PROXY_MCP_SERVER_URL_PREFIX = f"{LITELLM_PROXY_MCP_SERVER_URL}/mcp/"
+
class LiteLLM_Proxy_MCP_Handler:
"""
Helper class with static methods for MCP integration with Responses API.
@@ -29,34 +30,40 @@ class LiteLLM_Proxy_MCP_Handler:
for tool in tools:
if isinstance(tool, dict) and tool.get("type") == "mcp":
server_url = tool.get("server_url", "")
- if isinstance(server_url, str) and server_url.startswith(LITELLM_PROXY_MCP_SERVER_URL):
+ if isinstance(server_url, str) and server_url.startswith(
+ LITELLM_PROXY_MCP_SERVER_URL
+ ):
return True
return False
-
+
@staticmethod
- def _parse_mcp_tools(tools: Optional[Iterable[ToolParam]]) -> Tuple[List[ToolParam], List[Any]]:
+ def _parse_mcp_tools(
+ tools: Optional[Iterable[ToolParam]],
+ ) -> Tuple[List[ToolParam], List[Any]]:
"""
Parse tools and separate MCP tools with litellm_proxy from other tools.
-
+
Returns:
Tuple of (mcp_tools_with_litellm_proxy, other_tools)
"""
mcp_tools_with_litellm_proxy: List[ToolParam] = []
other_tools: List[Any] = []
-
+
if tools:
for tool in tools:
if isinstance(tool, dict) and tool.get("type") == "mcp":
server_url = tool.get("server_url", "")
- if isinstance(server_url, str) and server_url.startswith(LITELLM_PROXY_MCP_SERVER_URL):
+ if isinstance(server_url, str) and server_url.startswith(
+ LITELLM_PROXY_MCP_SERVER_URL
+ ):
mcp_tools_with_litellm_proxy.append(tool)
else:
other_tools.append(tool)
else:
other_tools.append(tool)
-
+
return mcp_tools_with_litellm_proxy, other_tools
-
+
@staticmethod
async def _get_mcp_tools_from_manager(
user_api_key_auth: Any,
@@ -64,7 +71,7 @@ class LiteLLM_Proxy_MCP_Handler:
) -> List[MCPTool]:
"""
Get available tools from the MCP server manager.
-
+
Args:
user_api_key_auth: User authentication info for access control
mcp_tools_with_litellm_proxy: ToolParam objects with server_url starting with "litellm_proxy"
@@ -72,48 +79,57 @@ class LiteLLM_Proxy_MCP_Handler:
from litellm.proxy._experimental.mcp_server.server import (
_get_tools_from_mcp_servers,
)
+
mcp_servers: List[str] = []
if mcp_tools_with_litellm_proxy:
for _tool in mcp_tools_with_litellm_proxy:
# if user specifies servers as server_url: litellm_proxy/mcp/zapier,github then return zapier,github
- server_url = _tool.get("server_url", "") if isinstance(_tool, dict) else ""
- if isinstance(server_url, str) and server_url.startswith(LITELLM_PROXY_MCP_SERVER_URL_PREFIX):
+ server_url = (
+ _tool.get("server_url", "") if isinstance(_tool, dict) else ""
+ )
+ if isinstance(server_url, str) and server_url.startswith(
+ LITELLM_PROXY_MCP_SERVER_URL_PREFIX
+ ):
mcp_servers.append(server_url.split("/")[-1])
-
+
return await _get_tools_from_mcp_servers(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=None,
mcp_servers=mcp_servers,
mcp_server_auth_headers=None,
- mcp_protocol_version=None,
)
-
+
@staticmethod
def _deduplicate_mcp_tools(mcp_tools: List[Any]) -> List[Any]:
"""
Deduplicate MCP tools by name, keeping the first occurrence of each tool.
-
+
Args:
mcp_tools: List of MCP tools that may contain duplicates
-
+
Returns:
List of deduplicated MCP tools
"""
seen_names = set()
deduplicated_tools = []
-
+
for tool in mcp_tools:
- tool_name = getattr(tool, 'name', None) if hasattr(tool, 'name') else tool.get('name') if isinstance(tool, dict) else None
+ tool_name = (
+ getattr(tool, "name", None)
+ if hasattr(tool, "name")
+ else tool.get("name")
+ if isinstance(tool, dict)
+ else None
+ )
if tool_name and tool_name not in seen_names:
seen_names.add(tool_name)
deduplicated_tools.append(tool)
-
+
return deduplicated_tools
@staticmethod
def _filter_mcp_tools_by_allowed_tools(
- mcp_tools: List[Any],
- mcp_tools_with_litellm_proxy: List[ToolParam]
+ mcp_tools: List[Any], mcp_tools_with_litellm_proxy: List[ToolParam]
) -> List[Any]:
"""Filter MCP tools based on allowed_tools parameter from the original tool configs."""
# Collect all allowed tool names from all MCP tool configs
@@ -123,127 +139,135 @@ class LiteLLM_Proxy_MCP_Handler:
allowed_tools = tool_config.get("allowed_tools", [])
if isinstance(allowed_tools, list):
allowed_tool_names.update(allowed_tools)
-
+
# If no allowed_tools specified, return all tools
if not allowed_tool_names:
return mcp_tools
-
+
# Filter tools based on allowed names
filtered_tools = []
for mcp_tool in mcp_tools:
- tool_name = getattr(mcp_tool, 'name', None) if hasattr(mcp_tool, 'name') else mcp_tool.get('name') if isinstance(mcp_tool, dict) else None
+ tool_name = (
+ getattr(mcp_tool, "name", None)
+ if hasattr(mcp_tool, "name")
+ else mcp_tool.get("name")
+ if isinstance(mcp_tool, dict)
+ else None
+ )
if tool_name and tool_name in allowed_tool_names:
filtered_tools.append(mcp_tool)
-
+
return filtered_tools
-
+
@staticmethod
async def _process_mcp_tools_to_openai_format(
- user_api_key_auth: Any,
- mcp_tools_with_litellm_proxy: List[ToolParam]
+ user_api_key_auth: Any, mcp_tools_with_litellm_proxy: List[ToolParam]
) -> List[Any]:
"""
Centralized method to process MCP tools through the complete pipeline:
1. Fetch tools from MCP manager
- 2. Filter based on allowed_tools parameter
+ 2. Filter based on allowed_tools parameter
3. Deduplicate tools by name
4. Transform to OpenAI format
-
+
Args:
user_api_key_auth: User authentication info for access control
mcp_tools_with_litellm_proxy: ToolParam objects with server_url starting with "litellm_proxy"
-
+
Returns:
List of tools in OpenAI format ready to be sent to the LLM
"""
if not mcp_tools_with_litellm_proxy:
return []
-
+
# Step 1: Fetch MCP tools from manager
mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(
user_api_key_auth=user_api_key_auth,
mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
)
-
+
# Step 2: Filter tools based on allowed_tools parameter
- filtered_mcp_tools = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
- mcp_tools=mcp_tools_fetched,
- mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ filtered_mcp_tools = (
+ LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mcp_tools_fetched,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ )
)
-
+
# Step 3: Deduplicate tools after filtering
deduplicated_mcp_tools = LiteLLM_Proxy_MCP_Handler._deduplicate_mcp_tools(
filtered_mcp_tools
)
-
+
# Step 4: Transform to OpenAI format
openai_tools = LiteLLM_Proxy_MCP_Handler._transform_mcp_tools_to_openai(
deduplicated_mcp_tools
)
-
+
return openai_tools
-
+
@staticmethod
async def _process_mcp_tools_without_openai_transform(
- user_api_key_auth: Any,
- mcp_tools_with_litellm_proxy: List[ToolParam]
+ user_api_key_auth: Any, mcp_tools_with_litellm_proxy: List[ToolParam]
) -> List[Any]:
"""
Process MCP tools through filtering and deduplication pipeline without OpenAI transformation.
This is useful for cases where we need the original MCP tool objects (e.g., for events).
-
+
Args:
user_api_key_auth: User authentication info for access control
mcp_tools_with_litellm_proxy: ToolParam objects with server_url starting with "litellm_proxy"
-
+
Returns:
List of filtered and deduplicated MCP tools in their original format
"""
if not mcp_tools_with_litellm_proxy:
return []
-
+
# Step 1: Fetch MCP tools from manager
mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(
user_api_key_auth=user_api_key_auth,
mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
)
-
+
# Step 2: Filter tools based on allowed_tools parameter
- filtered_mcp_tools = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
- mcp_tools=mcp_tools_fetched,
- mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ filtered_mcp_tools = (
+ LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mcp_tools_fetched,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ )
)
-
+
# Step 3: Deduplicate tools after filtering
deduplicated_mcp_tools = LiteLLM_Proxy_MCP_Handler._deduplicate_mcp_tools(
filtered_mcp_tools
)
-
+
return deduplicated_mcp_tools
-
+
@staticmethod
def _transform_mcp_tools_to_openai(mcp_tools: List[Any]) -> List[Any]:
"""Transform MCP tools to OpenAI-compatible format."""
from litellm.experimental_mcp_client.tools import (
transform_mcp_tool_to_openai_responses_api_tool,
)
-
+
openai_tools = []
for mcp_tool in mcp_tools:
openai_tool = transform_mcp_tool_to_openai_responses_api_tool(mcp_tool)
openai_tools.append(openai_tool)
-
+
return openai_tools
-
+
@staticmethod
def _should_auto_execute_tools(
- mcp_tools_with_litellm_proxy: Union[List[Dict[str, Any]], List[ToolParam]],
+ mcp_tools_with_litellm_proxy: Union[List[Dict[str, Any]], List[ToolParam]],
) -> bool:
"""Check if we should auto-execute tool calls.
Only auto-execute tools if user passed a MCP tool with require_approval set to "never".
-
-
+
+
"""
for tool in mcp_tools_with_litellm_proxy:
if isinstance(tool, dict):
@@ -252,24 +276,31 @@ class LiteLLM_Proxy_MCP_Handler:
elif getattr(tool, "require_approval", None) == "never":
return True
return False
-
+
@staticmethod
def _extract_tool_calls_from_response(response: ResponsesAPIResponse) -> List[Any]:
"""Extract tool calls from the response output."""
tool_calls: List[Any] = []
for output_item in response.output:
# Check if this is a function call output item
- if (isinstance(output_item, dict) and
- output_item.get("type") == "function_call"):
+ if (
+ isinstance(output_item, dict)
+ and output_item.get("type") == "function_call"
+ ):
tool_calls.append(output_item)
- elif hasattr(output_item, 'type') and getattr(output_item, 'type') == "function_call":
+ elif (
+ hasattr(output_item, "type")
+ and getattr(output_item, "type") == "function_call"
+ ):
# Handle pydantic model case
tool_calls.append(output_item)
-
+
return tool_calls
-
+
@staticmethod
- def _extract_tool_call_details(tool_call) -> Tuple[Optional[str], Optional[str], Optional[str]]:
+ def _extract_tool_call_details(
+ tool_call,
+ ) -> Tuple[Optional[str], Optional[str], Optional[str]]:
"""Extract tool name, arguments, and call_id from a tool call."""
if isinstance(tool_call, dict):
tool_name = tool_call.get("name")
@@ -278,15 +309,17 @@ class LiteLLM_Proxy_MCP_Handler:
else:
tool_name = getattr(tool_call, "name", None)
tool_arguments = getattr(tool_call, "arguments", None)
- tool_call_id = getattr(tool_call, "call_id", None) or getattr(tool_call, "id", None)
-
+ tool_call_id = getattr(tool_call, "call_id", None) or getattr(
+ tool_call, "id", None
+ )
+
return tool_name, tool_arguments, tool_call_id
-
+
@staticmethod
def _parse_tool_arguments(tool_arguments: Any) -> Dict[str, Any]:
"""Parse tool arguments, handling both string and dict formats."""
import json
-
+
if isinstance(tool_arguments, str):
try:
return json.loads(tool_arguments)
@@ -294,23 +327,23 @@ class LiteLLM_Proxy_MCP_Handler:
return {}
else:
return tool_arguments or {}
-
+
@staticmethod
def _parse_mcp_result(result: Any) -> str:
"""Parse MCP tool call result and extract meaningful content."""
- if not result or not hasattr(result, 'content') or not result.content:
+ if not result or not hasattr(result, "content") or not result.content:
return "Tool executed successfully"
-
+
# Import MCP content types for isinstance checks
try:
from mcp.types import EmbeddedResource, ImageContent, TextContent
except ImportError:
# Fallback to generic handling if MCP types not available
return "Tool executed successfully"
-
+
text_parts = []
other_content_types = []
-
+
for content_item in result.content:
if isinstance(content_item, TextContent):
# Text content - extract the text
@@ -325,21 +358,20 @@ class LiteLLM_Proxy_MCP_Handler:
# Other unknown content types
content_type = type(content_item).__name__
other_content_types.append(content_type)
-
+
# Combine text parts if any
result_text = " ".join(text_parts) if text_parts else ""
-
+
# Add info about other content types
if other_content_types:
other_info = f"[Generated {', '.join(other_content_types)}]"
result_text = f"{result_text} {other_info}".strip()
-
+
return result_text or "Tool executed successfully"
-
+
@staticmethod
async def _execute_tool_calls(
- tool_calls: List[Any],
- user_api_key_auth: Any
+ tool_calls: List[Any], user_api_key_auth: Any
) -> List[Dict[str, Any]]:
"""Execute tool calls and return results."""
from fastapi import HTTPException
@@ -348,107 +380,115 @@ class LiteLLM_Proxy_MCP_Handler:
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
-
+
tool_results = []
tool_call_id: Optional[str] = None
for tool_call in tool_calls:
try:
- tool_name, tool_arguments, tool_call_id = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
-
+ (
+ tool_name,
+ tool_arguments,
+ tool_call_id,
+ ) = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
+
if not tool_name:
verbose_logger.warning(f"Tool call missing name: {tool_call}")
continue
-
- parsed_arguments = LiteLLM_Proxy_MCP_Handler._parse_tool_arguments(tool_arguments)
-
+
+ parsed_arguments = LiteLLM_Proxy_MCP_Handler._parse_tool_arguments(
+ tool_arguments
+ )
+
# Import here to avoid circular import
from litellm.proxy.proxy_server import proxy_logging_obj
-
+
result = await global_mcp_server_manager.call_tool(
name=tool_name,
arguments=parsed_arguments,
user_api_key_auth=user_api_key_auth,
proxy_logging_obj=proxy_logging_obj,
)
-
+
# Format result for inclusion in response
result_text = LiteLLM_Proxy_MCP_Handler._parse_mcp_result(result)
- tool_results.append({
- "tool_call_id": tool_call_id,
- "result": result_text
- })
-
+ tool_results.append(
+ {"tool_call_id": tool_call_id, "result": result_text}
+ )
+
except BlockedPiiEntityError as e:
- verbose_logger.error(f"BlockedPiiEntityError in MCP tool call: {str(e)}")
+ verbose_logger.error(
+ f"BlockedPiiEntityError in MCP tool call: {str(e)}"
+ )
error_message = f"Tool call blocked: PII entity '{getattr(e, 'entity_type', 'unknown')}' detected by guardrail '{getattr(e, 'guardrail_name', 'unknown')}'. {str(e)}"
- tool_results.append({
- "tool_call_id": tool_call_id,
- "result": error_message
- })
+ tool_results.append(
+ {"tool_call_id": tool_call_id, "result": error_message}
+ )
except GuardrailRaisedException as e:
- verbose_logger.error(f"GuardrailRaisedException in MCP tool call: {str(e)}")
+ verbose_logger.error(
+ f"GuardrailRaisedException in MCP tool call: {str(e)}"
+ )
error_message = f"Tool call blocked: Guardrail '{getattr(e, 'guardrail_name', 'unknown')}' violation. {str(e)}"
- tool_results.append({
- "tool_call_id": tool_call_id,
- "result": error_message
- })
+ tool_results.append(
+ {"tool_call_id": tool_call_id, "result": error_message}
+ )
except HTTPException as e:
verbose_logger.error(f"HTTPException in MCP tool call: {str(e)}")
error_message = f"Tool call failed: {str(e.detail) if hasattr(e, 'detail') else str(e)}"
- tool_results.append({
- "tool_call_id": tool_call_id,
- "result": error_message
- })
+ tool_results.append(
+ {"tool_call_id": tool_call_id, "result": error_message}
+ )
except Exception as e:
verbose_logger.exception(f"Error executing MCP tool call: {e}")
- tool_results.append({
- "tool_call_id": tool_call_id,
- "result": f"Error executing tool: {str(e)}"
- })
-
+ tool_results.append(
+ {
+ "tool_call_id": tool_call_id,
+ "result": f"Error executing tool: {str(e)}",
+ }
+ )
+
return tool_results
-
+
@staticmethod
def _create_follow_up_input(
- response: ResponsesAPIResponse,
- tool_results: List[Dict[str, Any]],
- original_input: Any = None
+ response: ResponsesAPIResponse,
+ tool_results: List[Dict[str, Any]],
+ original_input: Any = None,
) -> List[Any]:
"""Create follow-up input with tool results in proper format."""
follow_up_input: List[Any] = []
-
+
# Add original user input if available to maintain conversation context
if original_input:
if isinstance(original_input, str):
- follow_up_input.append({
- "type": "message",
- "role": "user",
- "content": original_input
- })
+ follow_up_input.append(
+ {"type": "message", "role": "user", "content": original_input}
+ )
elif isinstance(original_input, list):
follow_up_input.extend(original_input)
else:
follow_up_input.append(original_input)
-
+
# Add the assistant message with function calls
assistant_message_content: List[Any] = []
function_calls: List[Dict[str, Any]] = []
-
+
for output_item in response.output:
if isinstance(output_item, dict):
if output_item.get("type") == "function_call":
call_id = output_item.get("call_id") or output_item.get("id")
name = output_item.get("name")
arguments = output_item.get("arguments")
-
+
# Only add if we have required fields
if call_id and name:
- function_calls.append({
- "type": "function_call",
- "call_id": call_id,
- "name": name,
- "arguments": arguments
- })
+ function_calls.append(
+ {
+ "type": "function_call",
+ "call_id": call_id,
+ "name": name,
+ "arguments": arguments,
+ }
+ )
elif output_item.get("type") == "message":
# Extract content from message
content = output_item.get("content", [])
@@ -456,36 +496,40 @@ class LiteLLM_Proxy_MCP_Handler:
assistant_message_content.extend(content)
else:
assistant_message_content.append(content)
-
+
# Add assistant message with content and function calls
if assistant_message_content or function_calls:
- follow_up_input.append({
- "type": "message",
- "role": "assistant",
- "content": assistant_message_content
- })
-
+ follow_up_input.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": assistant_message_content,
+ }
+ )
+
# Add function calls after assistant message
for function_call in function_calls:
follow_up_input.append(function_call)
-
+
# Add tool results (function call outputs)
for tool_result in tool_results:
- follow_up_input.append({
- "type": "function_call_output",
- "call_id": tool_result["tool_call_id"],
- "output": tool_result["result"]
- })
-
+ follow_up_input.append(
+ {
+ "type": "function_call_output",
+ "call_id": tool_result["tool_call_id"],
+ "output": tool_result["result"],
+ }
+ )
+
return follow_up_input
-
+
@staticmethod
async def _make_follow_up_call(
follow_up_input: List[Any],
model: str,
all_tools: Optional[List[Any]],
response_id: str,
- **call_params: Any
+ **call_params: Any,
) -> Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator]:
"""Make follow-up response API call with tool results."""
return await aresponses(
@@ -493,7 +537,7 @@ class LiteLLM_Proxy_MCP_Handler:
model=model,
tools=all_tools, # Keep tools for potential future calls
previous_response_id=response_id, # Link to previous response
- **call_params
+ **call_params,
)
@staticmethod
@@ -505,11 +549,11 @@ class LiteLLM_Proxy_MCP_Handler:
mcp_discovery_events: List[Any],
call_params: Dict[str, Any],
previous_response_id: Optional[str],
- **kwargs
+ **kwargs,
) -> Any:
"""
Create MCP enhanced streaming response that handles the full MCP workflow.
-
+
This creates a streaming iterator that:
1. Immediately emits MCP discovery events
2. Makes the LLM call and streams the response
@@ -526,16 +570,16 @@ class LiteLLM_Proxy_MCP_Handler:
all_tools=all_tools,
call_params=call_params,
previous_response_id=previous_response_id,
- **kwargs
+ **kwargs,
)
-
+
# Create the enhanced streaming iterator that will handle everything
return MCPEnhancedStreamingIterator(
base_iterator=None, # Will be created internally
mcp_events=mcp_discovery_events, # Pre-generated MCP discovery events
mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
user_api_key_auth=kwargs.get("user_api_key_auth"),
- original_request_params=request_params
+ original_request_params=request_params,
)
@staticmethod
@@ -545,126 +589,127 @@ class LiteLLM_Proxy_MCP_Handler:
all_tools: Optional[List[Any]],
call_params: Dict[str, Any],
previous_response_id: Optional[str],
- **kwargs
+ **kwargs,
) -> Dict[str, Any]:
"""
Build a clean request parameters dictionary for MCP streaming.
-
+
Combines input, model, tools with call_params and additional kwargs
in a clean, maintainable way.
"""
# Start with the core required parameters
request_params = {
- 'input': input,
- 'model': model,
- 'tools': all_tools,
+ "input": input,
+ "model": model,
+ "tools": all_tools,
}
-
+
# Add previous_response_id if provided
if previous_response_id is not None:
- request_params['previous_response_id'] = previous_response_id
-
+ request_params["previous_response_id"] = previous_response_id
+
# Merge in all call_params (which contains most of the API parameters)
request_params.update(call_params)
-
+
# Merge in any additional kwargs
request_params.update(kwargs)
-
+
return request_params
@staticmethod
def _create_tool_execution_events(
- tool_calls: List[Any],
- tool_results: List[Dict[str, Any]]
+ tool_calls: List[Any], tool_results: List[Dict[str, Any]]
) -> List[Any]:
"""
Create MCP tool execution events for streaming.
-
+
Args:
tool_calls: List of tool calls from the LLM response
tool_results: List of tool execution results
-
+
Returns:
List of MCP tool execution events for streaming
"""
import uuid
from litellm.responses.mcp.mcp_streaming_iterator import create_mcp_call_events
-
+
tool_execution_events: List[Any] = []
-
+
# Create events for each tool execution
for tool_result in tool_results:
tool_call_id = tool_result.get("tool_call_id", "unknown")
result_text = tool_result.get("result", "")
-
+
# Extract tool name and arguments from tool calls
tool_name = "unknown"
tool_arguments = "{}"
for tool_call in tool_calls:
- name, args, call_id = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
+ (
+ name,
+ args,
+ call_id,
+ ) = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
if call_id == tool_call_id:
tool_name = name or "unknown"
tool_arguments = args or "{}"
break
-
+
execution_events = create_mcp_call_events(
tool_name=tool_name,
tool_call_id=tool_call_id,
arguments=tool_arguments, # Use actual arguments
result=result_text,
base_item_id=f"mcp_{uuid.uuid4().hex[:8]}", # Unique ID for each tool call
- sequence_start=len(tool_execution_events) + 1
+ sequence_start=len(tool_execution_events) + 1,
)
tool_execution_events.extend(execution_events)
-
+
return tool_execution_events
@staticmethod
def _prepare_initial_call_params(
- call_params: Dict[str, Any],
- should_auto_execute: bool
+ call_params: Dict[str, Any], should_auto_execute: bool
) -> Dict[str, Any]:
"""
Prepare call parameters for the initial LLM call.
-
+
For auto-execute scenarios, we need to disable streaming for the initial call
so we can process the tool calls before streaming the final response.
"""
initial_params = call_params.copy()
-
+
if should_auto_execute:
# Disable streaming for initial call when auto-executing tools
initial_params["stream"] = False
-
+
return initial_params
@staticmethod
def _prepare_follow_up_call_params(
- call_params: Dict[str, Any],
- original_stream_setting: bool
+ call_params: Dict[str, Any], original_stream_setting: bool
) -> Dict[str, Any]:
"""
Prepare call parameters for the follow-up LLM call after tool execution.
-
+
Restores the original streaming setting and removes tool_choice since
we're now providing tool results, not requesting tool calls.
"""
follow_up_params = call_params.copy()
-
+
# Restore original streaming setting for follow-up call
follow_up_params["stream"] = original_stream_setting
-
+
# Remove tool_choice since we're providing results, not requesting tool calls
follow_up_params.pop("tool_choice", None)
-
+
return follow_up_params
@staticmethod
def _add_mcp_output_elements_to_response(
response: ResponsesAPIResponse,
mcp_tools_fetched: List[Any],
- tool_results: List[Dict[str, Any]]
+ tool_results: List[Dict[str, Any]],
) -> ResponsesAPIResponse:
"""Add custom output elements to the final response for MCP tool execution."""
# Import the required classes for creating output items
@@ -683,11 +728,11 @@ class LiteLLM_Proxy_MCP_Handler:
OutputText(
type="output_text",
text=json.dumps(mcp_tools_fetched, indent=2, default=str),
- annotations=[]
+ annotations=[],
)
- ]
+ ],
)
-
+
# Create output element for tool execution results
tool_results_output = GenericResponseOutputItem(
type="tool_execution_results",
@@ -698,13 +743,13 @@ class LiteLLM_Proxy_MCP_Handler:
OutputText(
type="output_text",
text=json.dumps(tool_results, indent=2, default=str),
- annotations=[]
+ annotations=[],
)
- ]
+ ],
)
-
+
# Add the new output elements to the response
response.output.append(mcp_tools_output.model_dump()) # type: ignore
response.output.append(tool_results_output.model_dump()) # type: ignore
-
+
return response
diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.py
index 11b058db8dd..e7bd67b23e6 100644
--- a/litellm/types/mcp_server/mcp_server_manager.py
+++ b/litellm/types/mcp_server/mcp_server_manager.py
@@ -21,7 +21,6 @@ class MCPServer(BaseModel):
server_name: Optional[str] = None
url: Optional[str] = None
transport: MCPTransportType
- spec_version: MCPSpecVersionType
auth_type: Optional[MCPAuthType] = None
authentication_token: Optional[str] = None
mcp_info: Optional[MCPInfo] = None
diff --git a/tests/mcp_tests/test_mcp_auth_priority.py b/tests/mcp_tests/test_mcp_auth_priority.py
index b1dcb02ccb4..bd159ef1a00 100644
--- a/tests/mcp_tests/test_mcp_auth_priority.py
+++ b/tests/mcp_tests/test_mcp_auth_priority.py
@@ -23,22 +23,21 @@ def test_mcp_server_works_without_config_auth_value():
name="Test MCP Server No Config Auth",
server_name="test_server_no_config",
alias="test_no_config",
- url="https://api.example.com/mcp",
+ url="https://api.example.com/mcp",
transport=MCPTransport.http,
spec_version=MCPSpecVersion.jun_2025,
auth_type=MCPAuth.authorization,
- authentication_token=None # No config auth
+ authentication_token=None, # No config auth
)
-
+
manager = MCPServerManager()
-
+
# Test that it works with only header auth
client = manager._create_mcp_client(
server=server_without_config_auth,
mcp_auth_header="Bearer token_from_header_only",
- protocol_version="2025-06-18"
)
-
+
# Verify header token is used
assert client._mcp_auth_value == "Bearer token_from_header_only"
assert client.auth_type == MCPAuth.authorization
diff --git a/tests/mcp_tests/test_mcp_client_unit.py b/tests/mcp_tests/test_mcp_client_unit.py
index 7b8e22eda72..247ae512161 100644
--- a/tests/mcp_tests/test_mcp_client_unit.py
+++ b/tests/mcp_tests/test_mcp_client_unit.py
@@ -17,7 +17,7 @@ from mcp.types import Tool as MCPTool, CallToolResult as MCPCallToolResult
class TestMCPClientUnitTests:
"""Unit tests for MCPClient functionality."""
-
+
def test_init_with_auth(self):
"""Test initialization with authentication."""
client = MCPClient(
@@ -25,43 +25,48 @@ class TestMCPClientUnitTests:
transport_type=MCPTransport.sse,
auth_type=MCPAuth.bearer_token,
auth_value="test_token",
- timeout=30.0
+ timeout=30.0,
)
assert client.server_url == "http://example.com"
assert client.transport_type == MCPTransport.sse
assert client.auth_type == MCPAuth.bearer_token
assert client.timeout == 30.0
assert client._mcp_auth_value == "test_token"
-
+
def test_get_auth_headers(self):
"""Test authentication header generation for different auth types."""
# Bearer token
client = MCPClient(
- "http://example.com",
+ "http://example.com",
auth_type=MCPAuth.bearer_token,
- auth_value="test_token"
+ auth_value="test_token",
)
headers = client._get_auth_headers()
- assert headers == {"Authorization": "Bearer test_token", "MCP-Protocol-Version": "2025-06-18"}
-
+ assert headers == {
+ "Authorization": "Bearer test_token",
+ "MCP-Protocol-Version": "2025-06-18",
+ }
+
# Basic auth
client = MCPClient(
- "http://example.com",
- auth_type=MCPAuth.basic,
- auth_value="user:pass"
+ "http://example.com", auth_type=MCPAuth.basic, auth_value="user:pass"
)
expected_encoded = base64.b64encode("user:pass".encode("utf-8")).decode()
headers = client._get_auth_headers()
- assert headers == {"Authorization": f"Basic {expected_encoded}", "MCP-Protocol-Version": "2025-06-18"}
-
+ assert headers == {
+ "Authorization": f"Basic {expected_encoded}",
+ "MCP-Protocol-Version": "2025-06-18",
+ }
+
# API key
client = MCPClient(
- "http://example.com",
- auth_type=MCPAuth.api_key,
- auth_value="api_key_123"
+ "http://example.com", auth_type=MCPAuth.api_key, auth_value="api_key_123"
)
headers = client._get_auth_headers()
- assert headers == {"X-API-Key": "api_key_123", "MCP-Protocol-Version": "2025-06-18"}
+ assert headers == {
+ "X-API-Key": "api_key_123",
+ "MCP-Protocol-Version": "2025-06-18",
+ }
# Custom authorization header
client = MCPClient(
@@ -74,24 +79,15 @@ class TestMCPClientUnitTests:
"Authorization": "Token custom_token",
"MCP-Protocol-Version": "2025-06-18",
}
-
+
# No auth
client = MCPClient("http://example.com")
headers = client._get_auth_headers()
assert headers == {"MCP-Protocol-Version": "2025-06-18"}
-
- # Custom protocol version
- from litellm.types.mcp import MCPSpecVersion
- client = MCPClient(
- "http://example.com",
- protocol_version=MCPSpecVersion.mar_2025
- )
- headers = client._get_auth_headers()
- assert headers == {"MCP-Protocol-Version": "2025-03-26"}
-
+
@pytest.mark.asyncio
- @patch('litellm.experimental_mcp_client.client.streamablehttp_client')
- @patch('litellm.experimental_mcp_client.client.ClientSession')
+ @patch("litellm.experimental_mcp_client.client.streamablehttp_client")
+ @patch("litellm.experimental_mcp_client.client.ClientSession")
async def test_connect(self, mock_session_class, mock_transport):
"""Test connecting to MCP server with authentication."""
# Setup mocks
@@ -99,30 +95,33 @@ class TestMCPClientUnitTests:
mock_transport.return_value = mock_transport_ctx
mock_transport_instance = MagicMock()
mock_transport_ctx.__aenter__ = AsyncMock(return_value=mock_transport_instance)
-
+
mock_session_ctx = AsyncMock()
mock_session_class.return_value = mock_session_ctx
mock_session_instance = AsyncMock()
mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_session_instance)
-
+
client = MCPClient(
"http://example.com",
auth_type=MCPAuth.bearer_token,
- auth_value="test_token"
+ auth_value="test_token",
)
await client.connect()
-
+
# Verify transport was created with auth headers
call_args = mock_transport.call_args
- assert call_args[1]['headers'] == {"Authorization": "Bearer test_token", "MCP-Protocol-Version": "2025-06-18"}
-
+ assert call_args[1]["headers"] == {
+ "Authorization": "Bearer test_token",
+ "MCP-Protocol-Version": "2025-06-18",
+ }
+
# Verify session was initialized
mock_session_instance.initialize.assert_called_once()
assert client._session == mock_session_instance
-
+
@pytest.mark.asyncio
- @patch('litellm.experimental_mcp_client.client.streamablehttp_client')
- @patch('litellm.experimental_mcp_client.client.ClientSession')
+ @patch("litellm.experimental_mcp_client.client.streamablehttp_client")
+ @patch("litellm.experimental_mcp_client.client.ClientSession")
async def test_list_tools(self, mock_session_class, mock_transport):
"""Test listing tools from the server."""
# Setup mocks
@@ -130,70 +129,71 @@ class TestMCPClientUnitTests:
mock_transport.return_value = mock_transport_ctx
mock_transport_instance = MagicMock()
mock_transport_ctx.__aenter__ = AsyncMock(return_value=mock_transport_instance)
-
+
mock_session_ctx = AsyncMock()
mock_session_class.return_value = mock_session_ctx
mock_session_instance = AsyncMock()
mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_session_instance)
-
+
mock_tools = [
MCPTool(
- name="test_tool",
+ name="test_tool",
description="Test tool",
inputSchema={
"type": "object",
"properties": {"arg1": {"type": "string"}},
- "required": ["arg1"]
- }
+ "required": ["arg1"],
+ },
)
]
mock_result = MagicMock()
mock_result.tools = mock_tools
mock_session_instance.list_tools.return_value = mock_result
-
+
client = MCPClient("http://example.com")
result = await client.list_tools()
-
+
assert result == mock_tools
mock_session_instance.initialize.assert_called_once()
mock_session_instance.list_tools.assert_called_once()
-
+
@pytest.mark.asyncio
- @patch('litellm.experimental_mcp_client.client.streamablehttp_client')
- @patch('litellm.experimental_mcp_client.client.ClientSession')
+ @patch("litellm.experimental_mcp_client.client.streamablehttp_client")
+ @patch("litellm.experimental_mcp_client.client.ClientSession")
async def test_call_tool(self, mock_session_class, mock_transport):
"""Test calling a tool."""
from mcp.types import CallToolRequestParams
-
+
# Setup mocks
mock_transport_ctx = AsyncMock()
mock_transport.return_value = mock_transport_ctx
mock_transport_instance = MagicMock()
mock_transport_ctx.__aenter__ = AsyncMock(return_value=mock_transport_instance)
-
+
mock_session_ctx = AsyncMock()
mock_session_class.return_value = mock_session_ctx
mock_session_instance = AsyncMock()
mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_session_instance)
-
+
mock_result = MCPCallToolResult(content=[])
mock_session_instance.call_tool.return_value = mock_result
-
+
client = MCPClient("http://example.com")
params = CallToolRequestParams(name="test_tool", arguments={"arg1": "value1"})
result = await client.call_tool(params)
-
+
assert result == mock_result
mock_session_instance.initialize.assert_called_once()
mock_session_instance.call_tool.assert_called_once_with(
- name="test_tool",
- arguments={"arg1": "value1"}
+ name="test_tool", arguments={"arg1": "value1"}
)
def test_protocol_version_header_extraction(self):
"""Test that MCP protocol version header is correctly extracted from requests."""
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
-
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+
# Mock scope with headers
mock_scope = {
"type": "http",
@@ -203,26 +203,37 @@ class TestMCPClientUnitTests:
(b"authorization", b"Bearer test_token"),
(b"mcp-protocol-version", b"2025-06-18"),
(b"content-type", b"application/json"),
- ]
+ ],
}
-
+
# Mock the user_api_key_auth function
- with patch('litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth') as mock_auth:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth"
+ ) as mock_auth:
mock_auth.return_value = MagicMock()
-
+
# Call process_mcp_request
import asyncio
+
result = asyncio.run(MCPRequestHandler.process_mcp_request(mock_scope))
-
+
# Verify the protocol version is extracted
- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = result
-
+ (
+ user_api_key_auth,
+ mcp_auth_header,
+ mcp_servers,
+ mcp_server_auth_headers,
+ mcp_protocol_version,
+ ) = result
+
assert mcp_protocol_version == "2025-06-18"
def test_protocol_version_header_missing(self):
"""Test that MCP protocol version header is None when not provided."""
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
-
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+
# Mock scope without protocol version header
mock_scope = {
"type": "http",
@@ -231,22 +242,31 @@ class TestMCPClientUnitTests:
"headers": [
(b"authorization", b"Bearer test_token"),
(b"content-type", b"application/json"),
- ]
+ ],
}
-
+
# Mock the user_api_key_auth function
- with patch('litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth') as mock_auth:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth"
+ ) as mock_auth:
mock_auth.return_value = MagicMock()
-
+
# Call process_mcp_request
import asyncio
+
result = asyncio.run(MCPRequestHandler.process_mcp_request(mock_scope))
-
+
# Verify the protocol version is None
- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers, mcp_protocol_version = result
-
+ (
+ user_api_key_auth,
+ mcp_auth_header,
+ mcp_servers,
+ mcp_server_auth_headers,
+ mcp_protocol_version,
+ ) = result
+
assert mcp_protocol_version is None
if __name__ == "__main__":
- pytest.main([__file__, "-v"])
\ No newline at end of file
+ pytest.main([__file__, "-v"])
diff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.py
index 8a390412495..6b9e6e75b57 100644
--- a/tests/mcp_tests/test_mcp_server.py
+++ b/tests/mcp_tests/test_mcp_server.py
@@ -52,30 +52,33 @@ async def test_mcp_server_manager_https_server():
"properties": {
"body": {"type": "string"},
"message": {"type": "string"},
- "instructions": {"type": "string"}
+ "instructions": {"type": "string"},
},
- "required": ["body"]
- }
+ "required": ["body"],
+ },
)
]
-
+
mock_result = CallToolResult(
content=[TextContent(type="text", text="Email sent successfully")],
- isError=False
+ isError=False,
)
-
+
# Create a mock MCPClient
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=mock_tools)
mock_client.call_tool = AsyncMock(return_value=mock_result)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
# Mock the MCPClient constructor
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
mcp_server_manager.load_servers_from_config(
{
"zapier_mcp_server": {
@@ -84,20 +87,24 @@ async def test_mcp_server_manager_https_server():
}
}
)
-
+
tools = await mcp_server_manager.list_tools()
print("TOOLS FROM MCP SERVER MANAGER== ", tools)
-
+
# Verify tools were returned and properly prefixed
assert len(tools) == 1
# The server should use the server_name as prefix since no alias is provided
expected_prefix = "zapier_mcp_server"
assert tools[0].name == f"{expected_prefix}-gmail_send_email"
-
+
# Manually set up the tool mapping for the call_tool test
- mcp_server_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = expected_prefix
- mcp_server_manager.tool_name_to_mcp_server_name_mapping[f"{expected_prefix}-gmail_send_email"] = expected_prefix
-
+ mcp_server_manager.tool_name_to_mcp_server_name_mapping[
+ "gmail_send_email"
+ ] = expected_prefix
+ mcp_server_manager.tool_name_to_mcp_server_name_mapping[
+ f"{expected_prefix}-gmail_send_email"
+ ] = expected_prefix
+
result = await mcp_server_manager.call_tool(
name=f"{expected_prefix}-gmail_send_email",
arguments={
@@ -108,13 +115,13 @@ async def test_mcp_server_manager_https_server():
proxy_logging_obj=None,
)
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
-
+
# Verify result
assert result.isError is False
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Email sent successfully"
-
+
# Verify client methods were called
mock_client.__aenter__.assert_called()
mock_client.list_tools.assert_called()
@@ -124,10 +131,10 @@ async def test_mcp_server_manager_https_server():
@pytest.mark.asyncio
async def test_mcp_http_transport_list_tools_mock():
"""Test HTTP transport list_tools functionality with mocked dependencies"""
-
+
# Create a fresh manager for testing
test_manager = MCPServerManager()
-
+
# Mock tools that should be returned
mock_tools = [
MCPTool(
@@ -138,10 +145,10 @@ async def test_mcp_http_transport_list_tools_mock():
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
- "body": {"type": "string"}
+ "body": {"type": "string"},
},
- "required": ["to", "subject", "body"]
- }
+ "required": ["to", "subject", "body"],
+ },
),
MCPTool(
name="calendar_create_event",
@@ -151,113 +158,130 @@ async def test_mcp_http_transport_list_tools_mock():
"properties": {
"title": {"type": "string"},
"date": {"type": "string"},
- "time": {"type": "string"}
+ "time": {"type": "string"},
},
- "required": ["title", "date"]
- }
- )
+ "required": ["title", "date"],
+ },
+ ),
]
-
+
# Create a mock MCPClient that returns our test tools
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=mock_tools)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
# Mock the MCPClient constructor to return our mock
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
-
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Load server config with HTTP transport
- test_manager.load_servers_from_config({
- "test_http_server": {
- "url": "https://test-mcp-server.com/mcp",
- "transport": MCPTransport.http,
- "description": "Test HTTP MCP Server"
+ test_manager.load_servers_from_config(
+ {
+ "test_http_server": {
+ "url": "https://test-mcp-server.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Test HTTP MCP Server",
+ }
}
- })
-
+ )
+
# Call list_tools
tools = await test_manager.list_tools()
-
+
# Assertions
assert len(tools) == 2
# The server should use the server_name as prefix since no alias is provided
expected_prefix = "test_http_server"
assert tools[0].name == f"{expected_prefix}-gmail_send_email"
assert tools[1].name == f"{expected_prefix}-calendar_create_event"
-
+
# Verify client methods were called
mock_client.list_tools.assert_called()
-
+
# Verify tool mapping was updated
expected_prefix = "test_http_server"
- assert test_manager.tool_name_to_mcp_server_name_mapping[f"{expected_prefix}-gmail_send_email"] == expected_prefix
- assert test_manager.tool_name_to_mcp_server_name_mapping[f"{expected_prefix}-calendar_create_event"] == expected_prefix
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping[
+ f"{expected_prefix}-gmail_send_email"
+ ]
+ == expected_prefix
+ )
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping[
+ f"{expected_prefix}-calendar_create_event"
+ ]
+ == expected_prefix
+ )
@pytest.mark.asyncio
async def test_mcp_http_transport_call_tool_mock():
"""Test HTTP transport call_tool functionality with mocked dependencies"""
-
+
# Create a fresh manager for testing
test_manager = MCPServerManager()
-
+
# Mock tool call result
mock_result = CallToolResult(
content=[
- TextContent(
- type="text",
- text="Email sent successfully to [email protected]"
- )
+ TextContent(type="text", text="Email sent successfully to [email protected]")
],
- isError=False
+ isError=False,
)
-
+
# Create a mock MCPClient that returns our test result
mock_client = AsyncMock()
mock_client.call_tool = AsyncMock(return_value=mock_result)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
# Mock the MCPClient constructor to return our mock
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
-
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Load server config with HTTP transport
- test_manager.load_servers_from_config({
- "test_http_server": {
- "url": "https://test-mcp-server.com/mcp",
- "transport": MCPTransport.http,
- "description": "Test HTTP MCP Server"
+ test_manager.load_servers_from_config(
+ {
+ "test_http_server": {
+ "url": "https://test-mcp-server.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Test HTTP MCP Server",
+ }
}
- })
-
+ )
+
# Manually set up tool mapping (normally done by list_tools)
- test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = "test_http_server"
-
+ test_manager.tool_name_to_mcp_server_name_mapping[
+ "gmail_send_email"
+ ] = "test_http_server"
+
# Call the tool
result = await test_manager.call_tool(
name="gmail_send_email",
arguments={
"subject": "Test Subject",
- "body": "Test email body"
+ "body": "Test email body",
},
proxy_logging_obj=None,
)
-
+
# Assertions
assert result.isError is False
assert len(result.content) == 1
# Type check before accessing text attribute
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Email sent successfully to [email protected]"
-
+
# Verify client methods were called
mock_client.__aenter__.assert_called()
mock_client.call_tool.assert_called_once()
@@ -266,59 +290,60 @@ async def test_mcp_http_transport_call_tool_mock():
@pytest.mark.asyncio
async def test_mcp_http_transport_call_tool_error_mock():
"""Test HTTP transport call_tool error handling with mocked dependencies"""
-
+
# Create a fresh manager for testing
test_manager = MCPServerManager()
-
+
# Mock tool call error result
mock_error_result = CallToolResult(
- content=[
- TextContent(
- type="text",
- text="Error: Invalid email address"
- )
- ],
- isError=True
+ content=[TextContent(type="text", text="Error: Invalid email address")],
+ isError=True,
)
-
+
# Create a mock MCPClient that returns our test error result
mock_client = AsyncMock()
mock_client.call_tool = AsyncMock(return_value=mock_error_result)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
# Mock the MCPClient constructor to return our mock
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
-
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Load server config with HTTP transport
- test_manager.load_servers_from_config({
- "test_http_server": {
- "url": "https://test-mcp-server.com/mcp",
- "transport": MCPTransport.http,
- "description": "Test HTTP MCP Server"
+ test_manager.load_servers_from_config(
+ {
+ "test_http_server": {
+ "url": "https://test-mcp-server.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Test HTTP MCP Server",
+ }
}
- })
-
+ )
+
# Manually set up tool mapping
- test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = "test_http_server"
-
+ test_manager.tool_name_to_mcp_server_name_mapping[
+ "gmail_send_email"
+ ] = "test_http_server"
+
# Call the tool with invalid data
result = await test_manager.call_tool(
name="gmail_send_email",
arguments={"to": "invalid-email", "subject": "Test", "body": "Test"},
proxy_logging_obj=None,
)
-
+
# Assertions for error case
assert result.isError is True
assert len(result.content) == 1
# Type check before accessing text attribute
assert isinstance(result.content[0], TextContent)
assert "Error: Invalid email address" in result.content[0].text
-
+
# Verify client methods were called
mock_client.__aenter__.assert_called()
mock_client.call_tool.assert_called_once()
@@ -327,19 +352,21 @@ async def test_mcp_http_transport_call_tool_error_mock():
@pytest.mark.asyncio
async def test_mcp_http_transport_tool_not_found():
"""Test calling a tool that doesn't exist"""
-
+
# Create a fresh manager for testing
test_manager = MCPServerManager()
-
+
# Load server config
- test_manager.load_servers_from_config({
- "test_http_server": {
- "url": "https://test-mcp-server.com/mcp",
- "transport": MCPTransport.http,
- "description": "Test HTTP MCP Server"
+ test_manager.load_servers_from_config(
+ {
+ "test_http_server": {
+ "url": "https://test-mcp-server.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Test HTTP MCP Server",
+ }
}
- })
-
+ )
+
# Try to call a tool that doesn't exist in mapping
with pytest.raises(ValueError, match="Tool nonexistent_tool not found"):
await test_manager.call_tool(
@@ -352,32 +379,38 @@ async def test_mcp_http_transport_tool_not_found():
@pytest.mark.asyncio
async def test_streamable_http_mcp_handler_mock():
"""Test the streamable HTTP MCP handler functionality"""
-
+
# Mock the session manager and its methods
mock_session_manager = AsyncMock()
mock_session_manager.handle_request = AsyncMock()
-
+
# Mock scope, receive, send with proper ASGI scope format
mock_scope = {
"type": "http",
- "method": "POST",
+ "method": "POST",
"path": "/mcp",
"headers": [(b"content-type", b"application/json")],
"query_string": b"",
"server": ("localhost", 8000),
- "scheme": "http"
+ "scheme": "http",
}
mock_receive = AsyncMock()
mock_send = AsyncMock()
-
- with patch('litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED', True), \
- patch('litellm.proxy._experimental.mcp_server.server.session_manager', mock_session_manager):
-
- from litellm.proxy._experimental.mcp_server.server import handle_streamable_http_mcp
-
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
+ True,
+ ), patch(
+ "litellm.proxy._experimental.mcp_server.server.session_manager",
+ mock_session_manager,
+ ):
+ from litellm.proxy._experimental.mcp_server.server import (
+ handle_streamable_http_mcp,
+ )
+
# Call the handler
await handle_streamable_http_mcp(mock_scope, mock_receive, mock_send)
-
+
# Verify session manager handle_request was called
mock_session_manager.handle_request.assert_called_once_with(
mock_scope, mock_receive, mock_send
@@ -387,11 +420,11 @@ async def test_streamable_http_mcp_handler_mock():
@pytest.mark.asyncio
async def test_sse_mcp_handler_mock():
"""Test the SSE MCP handler functionality"""
-
+
# Mock the SSE session manager and its methods
mock_sse_session_manager = AsyncMock()
mock_sse_session_manager.handle_request = AsyncMock()
-
+
# Mock scope, receive, send with proper ASGI scope format
mock_scope = {
"type": "http",
@@ -400,19 +433,23 @@ async def test_sse_mcp_handler_mock():
"headers": [(b"accept", b"text/event-stream")],
"query_string": b"",
"server": ("localhost", 8000),
- "scheme": "http"
+ "scheme": "http",
}
mock_receive = AsyncMock()
mock_send = AsyncMock()
-
- with patch('litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED', True), \
- patch('litellm.proxy._experimental.mcp_server.server.sse_session_manager', mock_sse_session_manager):
-
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
+ True,
+ ), patch(
+ "litellm.proxy._experimental.mcp_server.server.sse_session_manager",
+ mock_sse_session_manager,
+ ):
from litellm.proxy._experimental.mcp_server.server import handle_sse_mcp
-
+
# Call the handler
await handle_sse_mcp(mock_scope, mock_receive, mock_send)
-
+
# Verify SSE session manager handle_request was called
mock_sse_session_manager.handle_request.assert_called_once_with(
mock_scope, mock_receive, mock_send
@@ -422,18 +459,18 @@ async def test_sse_mcp_handler_mock():
def test_generate_stable_server_id():
"""
Test the _generate_stable_server_id method to ensure hash stability across releases.
-
+
This test verifies that:
1. The same inputs always produce the same hash output
2. Different inputs produce different hash outputs
3. The hash format is consistent (32 character hex string)
4. Edge cases work correctly (None auth_type)
-
+
IMPORTANT: If this test fails, it means the hashing algorithm has changed
and will break backwards compatibility with existing server IDs!
"""
manager = MCPServerManager()
-
+
# Test Case 1: Basic functionality with known inputs
# These expected values MUST remain stable across releases
test_cases = [
@@ -443,9 +480,9 @@ def test_generate_stable_server_id():
"url": "https://actions.zapier.com/mcp/sse",
"transport": "sse",
"spec_version": "2025-03-26",
- "auth_type": "api_key"
+ "auth_type": "api_key",
},
- "expected_hash": "8d5c9f8a12e3b7c4f6a2d8e1b5c9f2a4"
+ "expected_hash": "8d5c9f8a12e3b7c4f6a2d8e1b5c9f2a4",
},
{
"params": {
@@ -453,9 +490,9 @@ def test_generate_stable_server_id():
"url": "https://drive.google.com/mcp/http",
"transport": "http",
"spec_version": "2024-11-20",
- "auth_type": None
+ "auth_type": None,
},
- "expected_hash": "7a4b2e8f3c1d9e6b5a7c8f2d4e1b9c6a"
+ "expected_hash": "7a4b2e8f3c1d9e6b5a7c8f2d4e1b9c6a",
},
{
"params": {
@@ -463,37 +500,39 @@ def test_generate_stable_server_id():
"url": "http://localhost:8080/mcp",
"transport": "http",
"spec_version": "2025-03-26",
- "auth_type": "basic"
+ "auth_type": "basic",
},
- "expected_hash": "2f1e8d7c6b5a4e3f2d1c9b8a7e6f5d4c"
- }
+ "expected_hash": "2f1e8d7c6b5a4e3f2d1c9b8a7e6f5d4c",
+ },
]
-
+
# Test that our known inputs produce expected hash values
for test_case in test_cases:
result = manager._generate_stable_server_id(**test_case["params"])
-
+
# For now, just verify the format and stability, not exact hash
# (since we need to first run to see what the actual hashes are)
assert len(result) == 32, f"Hash should be 32 characters, got {len(result)}"
assert result.isalnum(), f"Hash should be alphanumeric, got: {result}"
assert result.islower(), f"Hash should be lowercase, got: {result}"
-
+
# Test stability - same inputs should always produce same output
result2 = manager._generate_stable_server_id(**test_case["params"])
- assert result == result2, f"Hash should be stable for same inputs: {result} != {result2}"
-
+ assert (
+ result == result2
+ ), f"Hash should be stable for same inputs: {result} != {result2}"
+
# Test Case 2: Different inputs produce different outputs
base_params = {
"server_name": "test_server",
"url": "https://test.com/mcp",
"transport": "sse",
"spec_version": "2025-03-26",
- "auth_type": "api_key"
+ "auth_type": "api_key",
}
-
+
base_hash = manager._generate_stable_server_id(**base_params)
-
+
# Change each parameter and verify hash changes
variations = [
{"server_name": "different_server"},
@@ -501,38 +540,44 @@ def test_generate_stable_server_id():
{"transport": "http"},
{"spec_version": "2024-11-20"},
{"auth_type": "basic"},
- {"auth_type": None}
+ {"auth_type": None},
]
-
+
for variation in variations:
modified_params = {**base_params, **variation}
modified_hash = manager._generate_stable_server_id(**modified_params)
- assert modified_hash != base_hash, f"Different params should produce different hash: {variation}"
- assert len(modified_hash) == 32, f"Modified hash should be 32 characters: {variation}"
-
+ assert (
+ modified_hash != base_hash
+ ), f"Different params should produce different hash: {variation}"
+ assert (
+ len(modified_hash) == 32
+ ), f"Modified hash should be 32 characters: {variation}"
+
# Test Case 3: Edge case with None auth_type
params_with_none = {
"server_name": "test_server",
"url": "https://test.com/mcp",
"transport": "sse",
"spec_version": "2025-03-26",
- "auth_type": None
+ "auth_type": None,
}
-
+
params_with_empty = {
"server_name": "test_server",
"url": "https://test.com/mcp",
"transport": "sse",
"spec_version": "2025-03-26",
- "auth_type": ""
+ "auth_type": "",
}
-
+
hash_none = manager._generate_stable_server_id(**params_with_none)
hash_empty = manager._generate_stable_server_id(**params_with_empty)
-
+
# None and empty string should produce the same hash (both become empty string)
- assert hash_none == hash_empty, "None auth_type should be equivalent to empty string"
-
+ assert (
+ hash_none == hash_empty
+ ), "None auth_type should be equivalent to empty string"
+
# Test Case 4: Real-world example hashes that must remain stable
# These are based on common configurations and MUST NOT CHANGE
zapier_sse_hash = manager._generate_stable_server_id(
@@ -540,34 +585,34 @@ def test_generate_stable_server_id():
url="https://actions.zapier.com/mcp/sk-ak-example/sse",
transport="sse",
spec_version="2025-03-26",
- auth_type="api_key"
+ auth_type="api_key",
)
-
+
github_http_hash = manager._generate_stable_server_id(
- server_name="github_mcp_server",
+ server_name="github_mcp_server",
url="https://api.github.com/mcp/http",
transport="http",
spec_version="2025-03-26",
- auth_type=None
+ auth_type=None,
)
-
+
# These should be deterministic - same call should produce same result
assert zapier_sse_hash == manager._generate_stable_server_id(
server_name="zapier_mcp_server",
- url="https://actions.zapier.com/mcp/sk-ak-example/sse",
+ url="https://actions.zapier.com/mcp/sk-ak-example/sse",
transport="sse",
spec_version="2025-03-26",
- auth_type="api_key"
+ auth_type="api_key",
)
-
+
assert github_http_hash == manager._generate_stable_server_id(
server_name="github_mcp_server",
url="https://api.github.com/mcp/http",
- transport="http",
+ transport="http",
spec_version="2025-03-26",
- auth_type=None
+ auth_type=None,
)
-
+
# Verify format
assert len(zapier_sse_hash) == 32
assert len(github_http_hash) == 32
@@ -583,7 +628,7 @@ async def test_list_tools_rest_api_server_not_found():
# Mock UserAPIKeyAuth
mock_user_auth = UserAPIKeyAuth(api_key="test", user_id="test")
-
+
# Mock request
mock_request = MagicMock()
mock_request.headers = {}
@@ -592,72 +637,83 @@ async def test_list_tools_rest_api_server_not_found():
response = await list_tool_rest_api(
request=mock_request,
server_id="non_existent_server_id",
- user_api_key_dict=mock_user_auth
+ user_api_key_dict=mock_user_auth,
)
-
+
assert isinstance(response, dict)
assert response["tools"] == []
assert response["error"] == "server_not_found"
assert "Server with id non_existent_server_id not found" in response["message"]
+
@pytest.mark.asyncio
async def test_list_tools_rest_api_success():
"""Test the list_tools REST API successful case"""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api, global_mcp_server_manager
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ list_tool_rest_api,
+ global_mcp_server_manager,
+ )
from fastapi import Query
from litellm.proxy._types import UserAPIKeyAuth
# Store original registry to restore after test
original_registry = global_mcp_server_manager.get_registry().copy()
- original_tool_mapping = global_mcp_server_manager.tool_name_to_mcp_server_name_mapping.copy()
+ original_tool_mapping = (
+ global_mcp_server_manager.tool_name_to_mcp_server_name_mapping.copy()
+ )
try:
# Clear existing registry
global_mcp_server_manager.tool_name_to_mcp_server_name_mapping.clear()
global_mcp_server_manager.registry.clear()
global_mcp_server_manager.config_mcp_servers.clear()
-
+
# Mock successful tools
mock_tools = [
MCPTool(
name="test_tool",
description="A test tool",
- inputSchema={"type": "object"}
+ inputSchema={"type": "object"},
)
]
-
+
# Create mock client
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=mock_tools)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Load server config into global manager
- global_mcp_server_manager.load_servers_from_config({
- "test_server": {
- "url": "https://test-server.com/mcp",
- "transport": MCPTransport.http,
+ global_mcp_server_manager.load_servers_from_config(
+ {
+ "test_server": {
+ "url": "https://test-server.com/mcp",
+ "transport": MCPTransport.http,
+ }
}
- })
-
+ )
+
# Mock UserAPIKeyAuth
mock_user_auth = UserAPIKeyAuth(api_key="test", user_id="test")
-
+
# Get the server ID
server_id = list(global_mcp_server_manager.get_registry().keys())[0]
-
+
# Mock request
mock_request = MagicMock()
mock_request.headers = {}
-
+
# Test successful case
response = await list_tool_rest_api(
request=mock_request,
server_id=server_id,
- user_api_key_dict=mock_user_auth
+ user_api_key_dict=mock_user_auth,
)
assert isinstance(response, dict)
@@ -669,15 +725,23 @@ async def test_list_tools_rest_api_success():
# Restore original state
global_mcp_server_manager.registry = {}
global_mcp_server_manager.config_mcp_servers = original_registry
- global_mcp_server_manager.tool_name_to_mcp_server_name_mapping = original_tool_mapping
+ global_mcp_server_manager.tool_name_to_mcp_server_name_mapping = (
+ original_tool_mapping
+ )
@pytest.mark.asyncio
async def test_get_tools_from_mcp_servers():
"""Test _get_tools_from_mcp_servers function with both specific and no server filters"""
- from litellm.proxy._experimental.mcp_server.server import _get_tools_from_mcp_servers
+ from litellm.proxy._experimental.mcp_server.server import (
+ _get_tools_from_mcp_servers,
+ )
from litellm.proxy._types import UserAPIKeyAuth
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import MCPServer, MCPTransport, MCPSpecVersion
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ MCPServer,
+ MCPTransport,
+ MCPSpecVersion,
+ )
# Mock data
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
@@ -688,7 +752,6 @@ async def test_get_tools_from_mcp_servers():
server_name="server1",
url="http://test1.com",
transport=MCPTransport.http,
- spec_version=MCPSpecVersion.nov_2024
)
mock_server_2 = MCPServer(
server_id="server2_id",
@@ -696,7 +759,6 @@ async def test_get_tools_from_mcp_servers():
server_name="server2",
url="http://test2.com",
transport=MCPTransport.http,
- spec_version=MCPSpecVersion.nov_2024
)
mock_server_3 = MCPServer(
server_id="server3_id",
@@ -704,8 +766,7 @@ async def test_get_tools_from_mcp_servers():
server_name="server3",
url="http://test3.com",
transport=MCPTransport.http,
- spec_version=MCPSpecVersion.nov_2024,
- access_groups=["group-a"]
+ access_groups=["group-a"],
)
mock_tool_1 = MCPTool(name="tool1", description="test tool 1", inputSchema={})
mock_tool_2 = MCPTool(name="tool2", description="test tool 2", inputSchema={})
@@ -724,11 +785,16 @@ async def test_get_tools_from_mcp_servers():
# Create a mock manager
mock_manager = AsyncMock()
- mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["server1_id", "server2_id"])
+ mock_manager.get_allowed_mcp_servers = AsyncMock(
+ return_value=["server1_id", "server2_id"]
+ )
mock_manager.get_mcp_server_by_id = mock_get_server_by_id
mock_manager._get_tools_from_server = AsyncMock(return_value=[mock_tool_1])
- with patch('litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager', mock_manager):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
+ mock_manager,
+ ):
# Test with specific servers
result = await _get_tools_from_mcp_servers(
user_api_key_auth=mock_user_auth,
@@ -741,30 +807,48 @@ async def test_get_tools_from_mcp_servers():
# Test Case 2: Without specific MCP servers
# Create a different mock manager for the second test case
mock_manager_2 = AsyncMock()
- mock_manager_2.get_allowed_mcp_servers = AsyncMock(return_value=["server1_id", "server2_id"])
+ mock_manager_2.get_allowed_mcp_servers = AsyncMock(
+ return_value=["server1_id", "server2_id"]
+ )
mock_manager_2.get_mcp_server_by_id = mock_get_server_by_id
- mock_manager_2._get_tools_from_server = AsyncMock(side_effect=lambda server, mcp_auth_header=None, mcp_protocol_version=None:
- [mock_tool_1] if server.server_id == "server1_id" else [mock_tool_2])
+ mock_manager_2._get_tools_from_server = AsyncMock(
+ side_effect=lambda server, mcp_auth_header=None: [mock_tool_1]
+ if server.server_id == "server1_id"
+ else [mock_tool_2]
+ )
- with patch('litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager', mock_manager_2):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
+ mock_manager_2,
+ ):
result = await _get_tools_from_mcp_servers(
user_api_key_auth=mock_user_auth,
mcp_auth_header=mock_auth_header,
mcp_servers=None,
)
assert len(result) == 2, "Should return tools from all servers"
- assert result[0].name == "tool1" and result[1].name == "tool2", "Should return tools from all servers"
+ assert (
+ result[0].name == "tool1" and result[1].name == "tool2"
+ ), "Should return tools from all servers"
#
# Test Case 3: With specific MCP servers and access groups
# Create a mock manager
mock_manager = AsyncMock()
- mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["server1_id", "server2_id", "server3_id"])
+ mock_manager.get_allowed_mcp_servers = AsyncMock(
+ return_value=["server1_id", "server2_id", "server3_id"]
+ )
mock_manager.get_mcp_server_by_id = mock_get_server_by_id
mock_manager._get_tools_from_server = AsyncMock(return_value=[mock_tool_1])
- with patch('litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager', mock_manager):
- with patch('litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.MCPRequestHandler._get_mcp_servers_from_access_groups', AsyncMock(return_value=["server3_id"])):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
+ mock_manager,
+ ):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.MCPRequestHandler._get_mcp_servers_from_access_groups",
+ AsyncMock(return_value=["server3_id"]),
+ ):
# Test with specific servers
result = await _get_tools_from_mcp_servers(
user_api_key_auth=mock_user_auth,
@@ -774,7 +858,6 @@ async def test_get_tools_from_mcp_servers():
assert len(result) == 1, "Should only return tools from server3"
assert result[0].name == "tool1", "Should return tool from server1"
-
except AssertionError as e:
pytest.fail(f"Test failed: {str(e)}")
except Exception as e:
@@ -789,37 +872,44 @@ async def test_list_tools_only_returns_allowed_servers(monkeypatch):
test_manager = MCPServerManager()
# Setup two servers in the config
- test_manager.load_servers_from_config({
- "server_a": {
- "url": "https://server-a.com/mcp",
- "transport": MCPTransport.http,
- "description": "Server A"
- },
- "server_b": {
- "url": "https://server-b.com/mcp",
- "transport": MCPTransport.http,
- "description": "Server B"
+ test_manager.load_servers_from_config(
+ {
+ "server_a": {
+ "url": "https://server-a.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Server A",
+ },
+ "server_b": {
+ "url": "https://server-b.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Server B",
+ },
}
- })
+ )
# Patch get_allowed_mcp_servers to only allow server_a
async def mock_get_allowed_mcp_servers(self, user_api_key_auth=None):
- return [list(test_manager.get_registry().keys())[0]] # Only first server (server_a)
- monkeypatch.setattr(MCPServerManager, "get_allowed_mcp_servers", mock_get_allowed_mcp_servers)
+ return [
+ list(test_manager.get_registry().keys())[0]
+ ] # Only first server (server_a)
+
+ monkeypatch.setattr(
+ MCPServerManager, "get_allowed_mcp_servers", mock_get_allowed_mcp_servers
+ )
# Mock tools for each server
mock_tools_a = [
MCPTool(
name="send_email",
description="Send an email via Server A",
- inputSchema={"type": "object"}
+ inputSchema={"type": "object"},
)
]
mock_tools_b = [
MCPTool(
name="create_event",
description="Create an event via Server B",
- inputSchema={"type": "object"}
+ inputSchema={"type": "object"},
)
]
@@ -835,7 +925,10 @@ async def test_list_tools_only_returns_allowed_servers(monkeypatch):
mock_client.__aexit__ = AsyncMock(return_value=None)
return mock_client
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Call list_tools
tools = await test_manager.list_tools(user_api_key_auth=MagicMock())
# Should only return tools from server_a
@@ -844,40 +937,70 @@ async def test_list_tools_only_returns_allowed_servers(monkeypatch):
expected_prefix = "server_a"
assert tools[0].name.startswith(f"{expected_prefix}-")
+
def test_mcp_server_manager_access_groups_from_config():
"""
Test that access_groups are loaded from config and can be resolved.
"""
test_manager = MCPServerManager()
- test_manager.load_servers_from_config({
- "config_server": {
- "url": "https://config-mcp-server.com/mcp",
- "transport": MCPTransport.http,
- "access_groups": ["group-a", "group-b"]
- },
- "other_server": {
- "url": "https://other-mcp-server.com/mcp",
- "transport": MCPTransport.http,
- "access_groups": ["group-b", "group-c"]
+ test_manager.load_servers_from_config(
+ {
+ "config_server": {
+ "url": "https://config-mcp-server.com/mcp",
+ "transport": MCPTransport.http,
+ "access_groups": ["group-a", "group-b"],
+ },
+ "other_server": {
+ "url": "https://other-mcp-server.com/mcp",
+ "transport": MCPTransport.http,
+ "access_groups": ["group-b", "group-c"],
+ },
}
- })
+ )
# Check that access_groups are loaded
- config_server = next((s for s in test_manager.config_mcp_servers.values() if s.name == "config_server"), None)
+ config_server = next(
+ (
+ s
+ for s in test_manager.config_mcp_servers.values()
+ if s.name == "config_server"
+ ),
+ None,
+ )
assert config_server is not None
assert set(config_server.access_groups) == {"group-a", "group-b"}
# Check that the lookup logic finds the correct server ids
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+
# Patch global_mcp_server_manager for this test
import litellm.proxy._experimental.mcp_server.mcp_server_manager as mcp_server_manager_mod
+
mcp_server_manager_mod.global_mcp_server_manager = test_manager
# Should find config_server for group-a, both for group-b, other_server for group-c
import asyncio
- server_ids_a = asyncio.run(MCPRequestHandler._get_mcp_servers_from_access_groups(["group-a"]))
- server_ids_b = asyncio.run(MCPRequestHandler._get_mcp_servers_from_access_groups(["group-b"]))
- server_ids_c = asyncio.run(MCPRequestHandler._get_mcp_servers_from_access_groups(["group-c"]))
+
+ server_ids_a = asyncio.run(
+ MCPRequestHandler._get_mcp_servers_from_access_groups(["group-a"])
+ )
+ server_ids_b = asyncio.run(
+ MCPRequestHandler._get_mcp_servers_from_access_groups(["group-b"])
+ )
+ server_ids_c = asyncio.run(
+ MCPRequestHandler._get_mcp_servers_from_access_groups(["group-c"])
+ )
assert any(config_server.server_id == sid for sid in server_ids_a)
- assert set(server_ids_b) == set([s.server_id for s in test_manager.config_mcp_servers.values() if "group-b" in s.access_groups])
- assert any(s.name == "other_server" and s.server_id in server_ids_c for s in test_manager.config_mcp_servers.values())
+ assert set(server_ids_b) == set(
+ [
+ s.server_id
+ for s in test_manager.config_mcp_servers.values()
+ if "group-b" in s.access_groups
+ ]
+ )
+ assert any(
+ s.name == "other_server" and s.server_id in server_ids_c
+ for s in test_manager.config_mcp_servers.values()
+ )
def test_mcp_server_manager_config_integration_with_database():
@@ -887,81 +1010,87 @@ def test_mcp_server_manager_config_integration_with_database():
"""
import datetime
from litellm.proxy._types import LiteLLM_MCPServerTable
-
+
test_manager = MCPServerManager()
-
+
# Test 1: Load config with access_groups and description
- test_manager.load_servers_from_config({
- "config_server_with_groups": {
- "url": "https://config-server.com/mcp",
- "transport": MCPTransport.http,
- "description": "Test config server",
- "access_groups": ["fr_staff", "admin"]
+ test_manager.load_servers_from_config(
+ {
+ "config_server_with_groups": {
+ "url": "https://config-server.com/mcp",
+ "transport": MCPTransport.http,
+ "description": "Test config server",
+ "access_groups": ["fr_staff", "admin"],
+ }
}
- })
-
+ )
+
# Verify config server has correct access_groups
config_servers = test_manager.config_mcp_servers
assert len(config_servers) == 1
config_server = next(iter(config_servers.values()))
assert config_server.access_groups == ["fr_staff", "admin"]
assert config_server.mcp_info["description"] == "Test config server"
-
+
# Test 2: Create a database server record and test add_update_server method
db_server = LiteLLM_MCPServerTable(
- server_id='db-server-123',
- server_name='database-server',
- url='https://db-server.com/mcp',
- transport='http',
- spec_version='2025-03-26',
- auth_type='none',
- description='Database server description',
+ server_id="db-server-123",
+ server_name="database-server",
+ url="https://db-server.com/mcp",
+ transport="http",
+ spec_version="2025-03-26",
+ auth_type="none",
+ description="Database server description",
created_at=datetime.datetime.now(),
updated_at=datetime.datetime.now(),
- mcp_access_groups=['db_group', 'test_group']
+ mcp_access_groups=["db_group", "test_group"],
)
-
+
# Test the add_update_server method (this tests our fix)
test_manager.add_update_server(db_server)
-
+
# Verify the server was added with correct access_groups
registry = test_manager.get_registry()
- assert 'db-server-123' in registry
-
- db_server_in_registry = registry['db-server-123']
- assert db_server_in_registry.access_groups == ['db_group', 'test_group']
- assert db_server_in_registry.server_name == 'database-server'
-
+ assert "db-server-123" in registry
+
+ db_server_in_registry = registry["db-server-123"]
+ assert db_server_in_registry.access_groups == ["db_group", "test_group"]
+ assert db_server_in_registry.server_name == "database-server"
+
# Test 3: Test config server conversion to LiteLLM_MCPServerTable format
# This tests that config servers are properly converted with access_groups and description fields
-
+
# Mock user auth to get all servers
from litellm.proxy._types import UserAPIKeyAuth
+
mock_user_auth = UserAPIKeyAuth(user_role="proxy_admin")
-
- # Mock the get_allowed_mcp_servers to return only config server IDs
+
+ # Mock the get_allowed_mcp_servers to return only config server IDs
# (to avoid database dependency in this test)
async def mock_get_allowed_servers(user_auth=None):
config_server_ids = list(test_manager.config_mcp_servers.keys())
return config_server_ids
-
+
test_manager.get_allowed_mcp_servers = mock_get_allowed_servers
-
+
# Test the method (this tests our second fix)
import asyncio
- servers_list = asyncio.run(test_manager.get_all_mcp_servers_with_health_and_teams(
- user_api_key_auth=mock_user_auth
- ))
-
+
+ servers_list = asyncio.run(
+ test_manager.get_all_mcp_servers_with_health_and_teams(
+ user_api_key_auth=mock_user_auth
+ )
+ )
+
# Verify we have the config server properly converted
assert len(servers_list) == 1
-
+
# Find the config server in the list
config_server_in_list = servers_list[0]
- assert config_server_in_list.server_name == 'config_server_with_groups'
+ assert config_server_in_list.server_name == "config_server_with_groups"
assert config_server_in_list.mcp_access_groups == ["fr_staff", "admin"]
assert config_server_in_list.description == "Test config server"
-
+
# Verify the mcp_info is also correct
assert config_server_in_list.mcp_info["description"] == "Test config server"
assert config_server_in_list.mcp_info["server_name"] == "config_server_with_groups"
@@ -973,13 +1102,13 @@ def test_get_server_prefix_with_alias():
Test that get_server_prefix returns alias when present.
"""
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
-
+
# Create a mock server with alias
mock_server = MagicMock()
mock_server.alias = "my_alias"
mock_server.server_name = "My Server Name"
mock_server.server_id = "server-123"
-
+
prefix = get_server_prefix(mock_server)
assert prefix == "my_alias"
@@ -989,13 +1118,13 @@ def test_get_server_prefix_without_alias():
Test that get_server_prefix falls back to server_name when alias is not present.
"""
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
-
+
# Create a mock server without alias
mock_server = MagicMock()
mock_server.alias = None
mock_server.server_name = "My Server Name"
mock_server.server_id = "server-123"
-
+
prefix = get_server_prefix(mock_server)
assert prefix == "My Server Name"
@@ -1005,13 +1134,13 @@ def test_get_server_prefix_fallback_to_server_id():
Test that get_server_prefix falls back to server_id when neither alias nor server_name are present.
"""
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
-
+
# Create a mock server without alias or server_name
mock_server = MagicMock()
mock_server.alias = None
mock_server.server_name = None
mock_server.server_id = "server-123"
-
+
prefix = get_server_prefix(mock_server)
assert prefix == "server-123"
@@ -1021,13 +1150,13 @@ def test_get_server_prefix_empty_strings():
Test that get_server_prefix handles empty strings correctly.
"""
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
-
+
# Create a mock server with empty strings
mock_server = MagicMock()
mock_server.alias = ""
mock_server.server_name = ""
mock_server.server_id = "server-123"
-
+
prefix = get_server_prefix(mock_server)
assert prefix == "server-123"
@@ -1038,7 +1167,7 @@ async def test_mcp_server_manager_alias_tool_prefixing():
Test that MCP server manager uses alias for tool prefixing when available.
"""
test_manager = MCPServerManager()
-
+
# Create a mock server with alias
mock_server = MCPServer(
server_id="test-server-123",
@@ -1047,41 +1176,49 @@ async def test_mcp_server_manager_alias_tool_prefixing():
server_name="Test Server",
url="https://test-server.com/mcp",
transport=MCPTransport.http,
- spec_version="2025-03-26"
)
-
+
# Add server to registry
test_manager.registry["test-server-123"] = mock_server
-
+
# Mock tools
mock_tools = [
MCPTool(
name="send_email",
description="Send an email",
- inputSchema={"type": "object"}
+ inputSchema={"type": "object"},
)
]
-
+
# Mock MCPClient
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=mock_tools)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Get tools from server
tools = await test_manager._get_tools_from_server(mock_server)
-
+
# Verify tool is prefixed with alias
assert len(tools) == 1
assert tools[0].name == "my_alias-send_email"
-
+
# Verify mapping is updated correctly
- assert test_manager.tool_name_to_mcp_server_name_mapping["send_email"] == "my_alias"
- assert test_manager.tool_name_to_mcp_server_name_mapping["my_alias-send_email"] == "my_alias"
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
+ == "my_alias"
+ )
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping["my_alias-send_email"]
+ == "my_alias"
+ )
@pytest.mark.asyncio
@@ -1090,7 +1227,7 @@ async def test_mcp_server_manager_server_name_tool_prefixing():
Test that MCP server manager falls back to server_name for tool prefixing when alias is not available.
"""
test_manager = MCPServerManager()
-
+
# Create a mock server without alias
mock_server = MCPServer(
server_id="test-server-123",
@@ -1099,41 +1236,49 @@ async def test_mcp_server_manager_server_name_tool_prefixing():
server_name="Test Server",
url="https://test-server.com/mcp",
transport=MCPTransport.http,
- spec_version="2025-03-26"
)
-
+
# Add server to registry
test_manager.registry["test-server-123"] = mock_server
-
+
# Mock tools
mock_tools = [
MCPTool(
name="send_email",
description="Send an email",
- inputSchema={"type": "object"}
+ inputSchema={"type": "object"},
)
]
-
+
# Mock MCPClient
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=mock_tools)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Get tools from server
tools = await test_manager._get_tools_from_server(mock_server)
-
+
# Verify tool is prefixed with server_name (normalized)
assert len(tools) == 1
assert tools[0].name == "Test_Server-send_email"
-
+
# Verify mapping is updated correctly
- assert test_manager.tool_name_to_mcp_server_name_mapping["send_email"] == "Test Server"
- assert test_manager.tool_name_to_mcp_server_name_mapping["Test_Server-send_email"] == "Test Server"
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
+ == "Test Server"
+ )
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping["Test_Server-send_email"]
+ == "Test Server"
+ )
@pytest.mark.asyncio
@@ -1142,7 +1287,7 @@ async def test_mcp_server_manager_server_id_tool_prefixing():
Test that MCP server manager falls back to server_id for tool prefixing when neither alias nor server_name are available.
"""
test_manager = MCPServerManager()
-
+
# Create a mock server without alias or server_name
mock_server = MCPServer(
server_id="test-server-123",
@@ -1151,41 +1296,51 @@ async def test_mcp_server_manager_server_id_tool_prefixing():
server_name=None,
url="https://test-server.com/mcp",
transport=MCPTransport.http,
- spec_version="2025-03-26"
)
-
+
# Add server to registry
test_manager.registry["test-server-123"] = mock_server
-
+
# Mock tools
mock_tools = [
MCPTool(
name="send_email",
description="Send an email",
- inputSchema={"type": "object"}
+ inputSchema={"type": "object"},
)
]
-
+
# Mock MCPClient
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=mock_tools)
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
def mock_client_constructor(*args, **kwargs):
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Get tools from server
tools = await test_manager._get_tools_from_server(mock_server)
-
+
# Verify tool is prefixed with server_id
assert len(tools) == 1
assert tools[0].name == "test-server-123-send_email"
-
+
# Verify mapping is updated correctly
- assert test_manager.tool_name_to_mcp_server_name_mapping["send_email"] == "test-server-123"
- assert test_manager.tool_name_to_mcp_server_name_mapping["test-server-123-send_email"] == "test-server-123"
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
+ == "test-server-123"
+ )
+ assert (
+ test_manager.tool_name_to_mcp_server_name_mapping[
+ "test-server-123-send_email"
+ ]
+ == "test-server-123"
+ )
def test_add_update_server_with_alias():
@@ -1193,7 +1348,7 @@ def test_add_update_server_with_alias():
Test that add_update_server correctly handles servers with alias.
"""
test_manager = MCPServerManager()
-
+
# Create a mock LiteLLM_MCPServerTable with alias
mock_mcp_server = MagicMock()
mock_mcp_server.server_id = "test-server-123"
@@ -1208,10 +1363,10 @@ def test_add_update_server_with_alias():
mock_mcp_server.command = None
mock_mcp_server.args = []
mock_mcp_server.env = None
-
+
# Add server to manager
test_manager.add_update_server(mock_mcp_server)
-
+
# Verify server was added with correct name (should use alias)
assert "test-server-123" in test_manager.registry
added_server = test_manager.registry["test-server-123"]
@@ -1225,7 +1380,7 @@ def test_add_update_server_without_alias():
Test that add_update_server correctly handles servers without alias.
"""
test_manager = MCPServerManager()
-
+
# Create a mock LiteLLM_MCPServerTable without alias
mock_mcp_server = MagicMock()
mock_mcp_server.server_id = "test-server-123"
@@ -1240,10 +1395,10 @@ def test_add_update_server_without_alias():
mock_mcp_server.command = None
mock_mcp_server.args = []
mock_mcp_server.env = None
-
+
# Add server to manager
test_manager.add_update_server(mock_mcp_server)
-
+
# Verify server was added with correct name (should use server_name)
assert "test-server-123" in test_manager.registry
added_server = test_manager.registry["test-server-123"]
@@ -1257,7 +1412,7 @@ def test_add_update_server_fallback_to_server_id():
Test that add_update_server falls back to server_id when neither alias nor server_name are available.
"""
test_manager = MCPServerManager()
-
+
# Create a mock LiteLLM_MCPServerTable without alias or server_name
mock_mcp_server = MagicMock()
mock_mcp_server.server_id = "test-server-123"
@@ -1272,10 +1427,10 @@ def test_add_update_server_fallback_to_server_id():
mock_mcp_server.command = None
mock_mcp_server.args = []
mock_mcp_server.env = None
-
+
# Add server to manager
test_manager.add_update_server(mock_mcp_server)
-
+
# Verify server was added with correct name (should use server_id)
assert "test-server-123" in test_manager.registry
added_server = test_manager.registry["test-server-123"]
@@ -1289,19 +1444,19 @@ def test_normalize_server_name():
Test that normalize_server_name correctly replaces spaces with underscores.
"""
from litellm.proxy._experimental.mcp_server.utils import normalize_server_name
-
+
# Test basic space replacement
assert normalize_server_name("My Server Name") == "My_Server_Name"
-
+
# Test multiple consecutive spaces
assert normalize_server_name("My Server Name") == "My__Server___Name"
-
+
# Test no spaces
assert normalize_server_name("MyServerName") == "MyServerName"
-
+
# Test empty string
assert normalize_server_name("") == ""
-
+
# Test string with only spaces
assert normalize_server_name(" ") == "___"
@@ -1310,20 +1465,22 @@ def test_add_server_prefix_to_tool_name():
"""
Test that add_server_prefix_to_tool_name correctly formats tool names.
"""
- from litellm.proxy._experimental.mcp_server.utils import add_server_prefix_to_tool_name
-
+ from litellm.proxy._experimental.mcp_server.utils import (
+ add_server_prefix_to_tool_name,
+ )
+
# Test basic prefixing
result = add_server_prefix_to_tool_name("send_email", "My Server")
assert result == "My_Server-send_email"
-
+
# Test with server name that already has underscores
result = add_server_prefix_to_tool_name("create_event", "my_server")
assert result == "my_server-create_event"
-
+
# Test with empty tool name
result = add_server_prefix_to_tool_name("", "My Server")
assert result == "My_Server-"
-
+
# Test with empty server name
result = add_server_prefix_to_tool_name("send_email", "")
assert result == "-send_email"
@@ -1332,116 +1489,137 @@ def test_add_server_prefix_to_tool_name():
@pytest.mark.asyncio
async def test_mcp_protocol_version_passed_to_client():
"""Test that MCP protocol version from request is correctly passed to MCPClient."""
-
+
# Create a test manager
test_manager = MCPServerManager()
-
+
# Mock MCPClient
mock_client = AsyncMock()
mock_client.list_tools = AsyncMock(return_value=[])
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
-
+
def mock_client_constructor(*args, **kwargs):
# Verify that the protocol version from request is used
- if 'protocol_version' in kwargs:
- assert kwargs['protocol_version'] == "2025-03-26"
+ if "protocol_version" in kwargs:
+ assert kwargs["protocol_version"] == "2025-03-26"
return mock_client
-
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
+ mock_client_constructor,
+ ):
# Load a test server
- test_manager.load_servers_from_config({
- "test_server": {
- "url": "https://test-server.com/mcp",
- "transport": "http",
- "description": "Test Server"
+ test_manager.load_servers_from_config(
+ {
+ "test_server": {
+ "url": "https://test-server.com/mcp",
+ "transport": "http",
+ "description": "Test Server",
+ }
}
- })
-
+ )
+
# Call list_tools with a specific protocol version from request
- await test_manager.list_tools(mcp_protocol_version="2025-03-26")
-
+ await test_manager.list_tools()
+
# Verify the client was created with the correct protocol version
mock_client.list_tools.assert_called()
def test_get_server_auth_header_with_alias():
"""Test _get_server_auth_header function with server alias."""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import _get_server_auth_header
-
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ _get_server_auth_header,
+ )
+
# Create a mock server with alias
mock_server = MagicMock()
mock_server.alias = "zapier"
mock_server.server_name = "zapier_server"
-
+
# Test with server-specific auth headers
mcp_server_auth_headers = {
"zapier": "Bearer zapier_token",
- "slack": "Bearer slack_token"
+ "slack": "Bearer slack_token",
}
mcp_auth_header = "Bearer default_token"
-
- result = _get_server_auth_header(mock_server, mcp_server_auth_headers, mcp_auth_header)
+
+ result = _get_server_auth_header(
+ mock_server, mcp_server_auth_headers, mcp_auth_header
+ )
assert result == "Bearer zapier_token"
-
+
# Test case-insensitive matching
mcp_server_auth_headers = {
"ZAPIER": "Bearer zapier_token_upper",
- "slack": "Bearer slack_token"
+ "slack": "Bearer slack_token",
}
-
- result = _get_server_auth_header(mock_server, mcp_server_auth_headers, mcp_auth_header)
+
+ result = _get_server_auth_header(
+ mock_server, mcp_server_auth_headers, mcp_auth_header
+ )
assert result == "Bearer zapier_token_upper"
def test_get_server_auth_header_with_server_name():
"""Test _get_server_auth_header function with server name (no alias)."""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import _get_server_auth_header
-
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ _get_server_auth_header,
+ )
+
# Create a mock server with server_name but no alias
mock_server = MagicMock()
mock_server.alias = None
mock_server.server_name = "slack_server"
-
+
# Test with server-specific auth headers
mcp_server_auth_headers = {
"slack_server": "Bearer slack_token",
- "zapier": "Bearer zapier_token"
+ "zapier": "Bearer zapier_token",
}
mcp_auth_header = "Bearer default_token"
-
- result = _get_server_auth_header(mock_server, mcp_server_auth_headers, mcp_auth_header)
+
+ result = _get_server_auth_header(
+ mock_server, mcp_server_auth_headers, mcp_auth_header
+ )
assert result == "Bearer slack_token"
-
+
# Test case-insensitive matching
mcp_server_auth_headers = {
"SLACK_SERVER": "Bearer slack_token_upper",
- "zapier": "Bearer zapier_token"
+ "zapier": "Bearer zapier_token",
}
-
- result = _get_server_auth_header(mock_server, mcp_server_auth_headers, mcp_auth_header)
+
+ result = _get_server_auth_header(
+ mock_server, mcp_server_auth_headers, mcp_auth_header
+ )
assert result == "Bearer slack_token_upper"
def test_get_server_auth_header_fallback_to_default():
"""Test _get_server_auth_header function fallback to default auth header."""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import _get_server_auth_header
-
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ _get_server_auth_header,
+ )
+
# Create a mock server
mock_server = MagicMock()
mock_server.alias = "unknown_server"
mock_server.server_name = "unknown_server_name"
-
+
# Test with no matching server-specific headers
mcp_server_auth_headers = {
"zapier": "Bearer zapier_token",
- "slack": "Bearer slack_token"
+ "slack": "Bearer slack_token",
}
mcp_auth_header = "Bearer default_token"
-
- result = _get_server_auth_header(mock_server, mcp_server_auth_headers, mcp_auth_header)
+
+ result = _get_server_auth_header(
+ mock_server, mcp_server_auth_headers, mcp_auth_header
+ )
assert result == "Bearer default_token"
-
+
# Test with no server-specific headers at all
result = _get_server_auth_header(mock_server, None, mcp_auth_header)
assert result == "Bearer default_token"
@@ -1449,47 +1627,51 @@ def test_get_server_auth_header_fallback_to_default():
def test_get_server_auth_header_no_auth_headers():
"""Test _get_server_auth_header function with no auth headers."""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import _get_server_auth_header
-
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ _get_server_auth_header,
+ )
+
# Create a mock server
mock_server = MagicMock()
mock_server.alias = "zapier"
mock_server.server_name = "zapier_server"
-
+
# Test with no auth headers
result = _get_server_auth_header(mock_server, None, None)
assert result is None
-
+
result = _get_server_auth_header(mock_server, {}, None)
assert result is None
def test_create_tool_response_objects():
"""Test _create_tool_response_objects function."""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import _create_tool_response_objects
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ _create_tool_response_objects,
+ )
from mcp.types import Tool as MCPTool
-
+
# Create mock tools
mock_tools = [
MCPTool(
name="send_email",
description="Send an email",
- inputSchema={"type": "object", "properties": {"to": {"type": "string"}}}
+ inputSchema={"type": "object", "properties": {"to": {"type": "string"}}},
),
MCPTool(
name="create_event",
description="Create a calendar event",
- inputSchema={"type": "object", "properties": {"title": {"type": "string"}}}
- )
+ inputSchema={"type": "object", "properties": {"title": {"type": "string"}}},
+ ),
]
-
+
server_mcp_info = {
"server_name": "zapier",
- "logo_url": "https://zapier.com/logo.png"
+ "logo_url": "https://zapier.com/logo.png",
}
-
+
result = _create_tool_response_objects(mock_tools, server_mcp_info)
-
+
assert len(result) == 2
assert result[0].name == "send_email"
assert result[0].description == "Send an email"
@@ -1502,35 +1684,38 @@ def test_create_tool_response_objects():
@pytest.mark.asyncio
async def test_get_tools_for_single_server():
"""Test _get_tools_for_single_server function."""
- from litellm.proxy._experimental.mcp_server.rest_endpoints import _get_tools_for_single_server
+ from litellm.proxy._experimental.mcp_server.rest_endpoints import (
+ _get_tools_for_single_server,
+ )
from mcp.types import Tool as MCPTool
-
+
# Create a mock server
mock_server = MagicMock()
mock_server.mcp_info = {"server_name": "zapier"}
-
+
# Create mock tools
mock_tools = [
MCPTool(
name="send_email",
description="Send an email",
- inputSchema={"type": "object", "properties": {"to": {"type": "string"}}}
+ inputSchema={"type": "object", "properties": {"to": {"type": "string"}}},
)
]
-
+
# Mock the global_mcp_server_manager
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager') as mock_manager:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
+ ) as mock_manager:
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
-
- result = await _get_tools_for_single_server(mock_server, "Bearer test_token", "2025-03-26")
-
+
+ result = await _get_tools_for_single_server(mock_server, "Bearer test_token")
+
# Verify the manager was called with correct parameters
mock_manager._get_tools_from_server.assert_called_once_with(
server=mock_server,
mcp_auth_header="Bearer test_token",
- mcp_protocol_version="2025-03-26"
)
-
+
# Verify the result
assert len(result) == 1
assert result[0].name == "send_email"
@@ -1541,72 +1726,86 @@ async def test_get_tools_for_single_server():
async def test_list_tool_rest_api_with_server_specific_auth():
"""Test list_tool_rest_api with server-specific auth headers."""
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
-
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+
# Create mock request with server-specific auth headers
mock_request = MagicMock()
mock_request.headers = {
"authorization": "Bearer user_token",
"x-mcp-zapier-authorization": "Bearer zapier_token",
"x-mcp-slack-authorization": "Bearer slack_token",
- "MCP-Protocol-Version": "2025-06-18"
+ "MCP-Protocol-Version": "2025-06-18",
}
-
+
# Create mock user_api_key_dict
mock_user_api_key_dict = MagicMock()
mock_user_api_key_dict.user_id = "test_user"
-
+
# Mock the MCPRequestHandler methods
- with patch.object(MCPRequestHandler, '_get_mcp_auth_header_from_headers') as mock_get_auth:
- with patch.object(MCPRequestHandler, '_get_mcp_server_auth_headers_from_headers') as mock_get_server_auth:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_auth_header_from_headers"
+ ) as mock_get_auth:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
+ ) as mock_get_server_auth:
mock_get_auth.return_value = "Bearer default_token"
mock_get_server_auth.return_value = {
"zapier": "Bearer zapier_token",
- "slack": "Bearer slack_token"
+ "slack": "Bearer slack_token",
}
-
+
# Mock the global_mcp_server_manager
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager') as mock_manager:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
+ ) as mock_manager:
# Create a mock server
mock_server = MagicMock()
mock_server.server_id = "test-server-123"
mock_server.alias = "zapier"
mock_server.name = "zapier_server"
mock_server.mcp_info = {"server_name": "zapier"}
-
+
mock_manager.get_mcp_server_by_id.return_value = mock_server
-
+
# Mock the _get_tools_for_single_server function
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server') as mock_get_tools:
- from litellm.proxy._experimental.mcp_server.server import ListMCPToolsRestAPIResponseObject
-
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
+ ) as mock_get_tools:
+ from litellm.proxy._experimental.mcp_server.server import (
+ ListMCPToolsRestAPIResponseObject,
+ )
+
mock_tools = [
ListMCPToolsRestAPIResponseObject(
name="send_email",
description="Send an email",
inputSchema={"type": "object"},
- mcp_info={"server_name": "zapier"}
+ mcp_info={"server_name": "zapier"},
)
]
mock_get_tools.return_value = mock_tools
-
+
# Call the function
result = await list_tool_rest_api(
request=mock_request,
server_id="test-server-123",
- user_api_key_dict=mock_user_api_key_dict
+ user_api_key_dict=mock_user_api_key_dict,
)
-
+
# Verify the result
assert result["error"] is None
assert len(result["tools"]) == 1
assert result["tools"][0].name == "send_email"
-
+
# Verify that _get_tools_for_single_server was called with the correct auth header
mock_get_tools.assert_called_once()
call_args = mock_get_tools.call_args
assert call_args[0][0] == mock_server # server
- assert call_args[0][1] == "Bearer zapier_token" # server_auth_header
+ assert (
+ call_args[0][1] == "Bearer zapier_token"
+ ) # server_auth_header
assert call_args[0][2] == "2025-06-18" # mcp_protocol_version
@@ -1614,68 +1813,82 @@ async def test_list_tool_rest_api_with_server_specific_auth():
async def test_list_tool_rest_api_with_default_auth():
"""Test list_tool_rest_api with default auth header when no server-specific header is found."""
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
-
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+
# Create mock request with default auth header only
mock_request = MagicMock()
mock_request.headers = {
"authorization": "Bearer user_token",
"x-mcp-authorization": "Bearer default_token",
- "MCP-Protocol-Version": "2025-06-18"
+ "MCP-Protocol-Version": "2025-06-18",
}
-
+
# Create mock user_api_key_dict
mock_user_api_key_dict = MagicMock()
mock_user_api_key_dict.user_id = "test_user"
-
+
# Mock the MCPRequestHandler methods
- with patch.object(MCPRequestHandler, '_get_mcp_auth_header_from_headers') as mock_get_auth:
- with patch.object(MCPRequestHandler, '_get_mcp_server_auth_headers_from_headers') as mock_get_server_auth:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_auth_header_from_headers"
+ ) as mock_get_auth:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
+ ) as mock_get_server_auth:
mock_get_auth.return_value = "Bearer default_token"
mock_get_server_auth.return_value = {} # No server-specific headers
-
+
# Mock the global_mcp_server_manager
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager') as mock_manager:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
+ ) as mock_manager:
# Create a mock server
mock_server = MagicMock()
mock_server.server_id = "test-server-123"
mock_server.alias = "unknown_server"
mock_server.name = "unknown_server"
mock_server.mcp_info = {"server_name": "unknown_server"}
-
+
mock_manager.get_mcp_server_by_id.return_value = mock_server
-
+
# Mock the _get_tools_for_single_server function
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server') as mock_get_tools:
- from litellm.proxy._experimental.mcp_server.server import ListMCPToolsRestAPIResponseObject
-
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
+ ) as mock_get_tools:
+ from litellm.proxy._experimental.mcp_server.server import (
+ ListMCPToolsRestAPIResponseObject,
+ )
+
mock_tools = [
ListMCPToolsRestAPIResponseObject(
name="send_email",
description="Send an email",
inputSchema={"type": "object"},
- mcp_info={"server_name": "unknown_server"}
+ mcp_info={"server_name": "unknown_server"},
)
]
mock_get_tools.return_value = mock_tools
-
+
# Call the function
result = await list_tool_rest_api(
request=mock_request,
server_id="test-server-123",
- user_api_key_dict=mock_user_api_key_dict
+ user_api_key_dict=mock_user_api_key_dict,
)
-
+
# Verify the result
assert result["error"] is None
assert len(result["tools"]) == 1
assert result["tools"][0].name == "send_email"
-
+
# Verify that _get_tools_for_single_server was called with the default auth header
mock_get_tools.assert_called_once()
call_args = mock_get_tools.call_args
assert call_args[0][0] == mock_server # server
- assert call_args[0][1] == "Bearer default_token" # server_auth_header
+ assert (
+ call_args[0][1] == "Bearer default_token"
+ ) # server_auth_header
assert call_args[0][2] == "2025-06-18" # mcp_protocol_version
@@ -1683,90 +1896,106 @@ async def test_list_tool_rest_api_with_default_auth():
async def test_list_tool_rest_api_all_servers_with_auth():
"""Test list_tool_rest_api for all servers with server-specific auth headers."""
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
-
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
+
# Create mock request with server-specific auth headers
mock_request = MagicMock()
mock_request.headers = {
"authorization": "Bearer user_token",
"x-mcp-zapier-authorization": "Bearer zapier_token",
"x-mcp-slack-authorization": "Bearer slack_token",
- "MCP-Protocol-Version": "2025-06-18"
+ "MCP-Protocol-Version": "2025-06-18",
}
-
+
# Create mock user_api_key_dict
mock_user_api_key_dict = MagicMock()
mock_user_api_key_dict.user_id = "test_user"
-
+
# Mock the MCPRequestHandler methods
- with patch.object(MCPRequestHandler, '_get_mcp_auth_header_from_headers') as mock_get_auth:
- with patch.object(MCPRequestHandler, '_get_mcp_server_auth_headers_from_headers') as mock_get_server_auth:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_auth_header_from_headers"
+ ) as mock_get_auth:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
+ ) as mock_get_server_auth:
mock_get_auth.return_value = "Bearer default_token"
mock_get_server_auth.return_value = {
"zapier": "Bearer zapier_token",
- "slack": "Bearer slack_token"
+ "slack": "Bearer slack_token",
}
-
+
# Mock the global_mcp_server_manager
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager') as mock_manager:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
+ ) as mock_manager:
# Create mock servers
mock_zapier_server = MagicMock()
mock_zapier_server.alias = "zapier"
mock_zapier_server.server_name = "zapier_server"
mock_zapier_server.mcp_info = {"server_name": "zapier"}
-
+
mock_slack_server = MagicMock()
mock_slack_server.alias = "slack"
mock_slack_server.server_name = "slack_server"
mock_slack_server.mcp_info = {"server_name": "slack"}
-
+
mock_manager.get_registry.return_value = {
"zapier": mock_zapier_server,
- "slack": mock_slack_server
+ "slack": mock_slack_server,
}
-
+
# Mock the _get_tools_for_single_server function
- with patch('litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server') as mock_get_tools:
- from litellm.proxy._experimental.mcp_server.server import ListMCPToolsRestAPIResponseObject
-
+ with patch(
+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
+ ) as mock_get_tools:
+ from litellm.proxy._experimental.mcp_server.server import (
+ ListMCPToolsRestAPIResponseObject,
+ )
+
# Mock tools for each server
mock_get_tools.side_effect = [
- [ListMCPToolsRestAPIResponseObject(
- name="send_email",
- description="Send an email",
- inputSchema={"type": "object"},
- mcp_info={"server_name": "zapier"}
- )],
- [ListMCPToolsRestAPIResponseObject(
- name="send_message",
- description="Send a message",
- inputSchema={"type": "object"},
- mcp_info={"server_name": "slack"}
- )]
+ [
+ ListMCPToolsRestAPIResponseObject(
+ name="send_email",
+ description="Send an email",
+ inputSchema={"type": "object"},
+ mcp_info={"server_name": "zapier"},
+ )
+ ],
+ [
+ ListMCPToolsRestAPIResponseObject(
+ name="send_message",
+ description="Send a message",
+ inputSchema={"type": "object"},
+ mcp_info={"server_name": "slack"},
+ )
+ ],
]
-
+
# Call the function without server_id (query all servers)
result = await list_tool_rest_api(
request=mock_request,
server_id=None,
- user_api_key_dict=mock_user_api_key_dict
+ user_api_key_dict=mock_user_api_key_dict,
)
-
+
# Verify the result
assert result["error"] is None
assert len(result["tools"]) == 2
assert result["tools"][0].name == "send_email"
assert result["tools"][1].name == "send_message"
-
+
# Verify that _get_tools_for_single_server was called for both servers with correct auth headers
assert mock_get_tools.call_count == 2
calls = mock_get_tools.call_args_list
-
+
# First call should be for zapier server with zapier auth
assert calls[0][0][0] == mock_zapier_server # server
assert calls[0][0][1] == "Bearer zapier_token" # server_auth_header
assert calls[0][0][2] == "2025-06-18" # mcp_protocol_version
-
+
# Second call should be for slack server with slack auth
assert calls[1][0][0] == mock_slack_server # server
assert calls[1][0][1] == "Bearer slack_token" # server_auth_header
@@ -1776,58 +2005,81 @@ async def test_list_tool_rest_api_all_servers_with_auth():
@pytest.mark.asyncio
async def test_mcp_access_group_permission_inheritance_integration():
"""Integration test for MCP access group permission inheritance"""
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
from litellm.proxy._types import UserAPIKeyAuth
-
+
# Test scenario: team has access groups, key has no permissions -> should inherit
# Use direct mocking of the helper functions instead of complex database mocking
- with patch.object(MCPRequestHandler, "_get_allowed_mcp_servers_for_key") as mock_key:
- with patch.object(MCPRequestHandler, "_get_allowed_mcp_servers_for_team") as mock_team:
+ with patch.object(
+ MCPRequestHandler, "_get_allowed_mcp_servers_for_key"
+ ) as mock_key:
+ with patch.object(
+ MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
+ ) as mock_team:
# Key has no permissions, team has servers
mock_key.return_value = [] # Key inherits nothing directly
- mock_team.return_value = ["staff-server-1", "staff-server-2", "ops-server-1"] # Team has servers
-
- # Create user auth object
+ mock_team.return_value = [
+ "staff-server-1",
+ "staff-server-2",
+ "ops-server-1",
+ ] # Team has servers
+
+ # Create user auth object
user_auth = UserAPIKeyAuth(
api_key="test-key",
user_id="test-user",
team_id="team-staff",
- object_permission_id=None # Key has no explicit permissions
+ object_permission_id=None, # Key has no explicit permissions
)
-
+
# Test the inheritance logic
allowed_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_auth)
-
+
# Should inherit all team servers since key has no permissions
expected_servers = ["staff-server-1", "staff-server-2", "ops-server-1"]
assert sorted(allowed_servers) == sorted(expected_servers)
async def test_mcp_access_group_permission_intersection_integration():
"""Integration test for MCP access group permission intersection"""
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
from litellm.proxy._types import UserAPIKeyAuth
-
+
# Test scenario: both team and key have access groups -> should intersect
# Use direct mocking of the helper functions instead of complex database mocking
- with patch.object(MCPRequestHandler, "_get_allowed_mcp_servers_for_key") as mock_key:
- with patch.object(MCPRequestHandler, "_get_allowed_mcp_servers_for_team") as mock_team:
+ with patch.object(
+ MCPRequestHandler, "_get_allowed_mcp_servers_for_key"
+ ) as mock_key:
+ with patch.object(
+ MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
+ ) as mock_team:
# Both key and team have permissions - should intersect
- mock_key.return_value = ["ops-server", "external-server"] # Key has these servers
- mock_team.return_value = ["staff-server", "ops-server", "admin-server"] # Team has these servers
-
+ mock_key.return_value = [
+ "ops-server",
+ "external-server",
+ ] # Key has these servers
+ mock_team.return_value = [
+ "staff-server",
+ "ops-server",
+ "admin-server",
+ ] # Team has these servers
+
# Create user auth object
user_auth = UserAPIKeyAuth(
api_key="test-key",
user_id="test-user",
- team_id="team-staff",
- object_permission_id="key-permission-id" # Key has explicit permissions
+ team_id="team-staff",
+ object_permission_id="key-permission-id", # Key has explicit permissions
)
-
+
# Test the intersection logic
allowed_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_auth)
-
+
# Should only get intersection (ops-server is common)
expected_servers = ["ops-server"]
assert sorted(allowed_servers) == sorted(expected_servers)
@@ -1836,46 +2088,49 @@ async def test_mcp_access_group_permission_intersection_integration():
@pytest.mark.asyncio
async def test_mcp_server_manager_with_access_groups_integration():
"""Integration test for MCPServerManager with access group filtering"""
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler
+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ MCPRequestHandler,
+ )
from litellm.proxy._types import UserAPIKeyAuth
-
+
# Create a test manager
test_manager = MCPServerManager()
-
+
# Load servers with access groups
- test_manager.load_servers_from_config({
- "staff_server": {
- "url": "https://staff-server.com/mcp",
- "access_groups": ["staff"],
- "transport": MCPTransport.http,
- },
- "ops_server": {
- "url": "https://ops-server.com/mcp",
- "access_groups": ["ops"],
- "transport": MCPTransport.http,
- },
- "admin_server": {
- "url": "https://admin-server.com/mcp",
- "access_groups": ["admin"],
- "transport": MCPTransport.http,
+ test_manager.load_servers_from_config(
+ {
+ "staff_server": {
+ "url": "https://staff-server.com/mcp",
+ "access_groups": ["staff"],
+ "transport": MCPTransport.http,
+ },
+ "ops_server": {
+ "url": "https://ops-server.com/mcp",
+ "access_groups": ["ops"],
+ "transport": MCPTransport.http,
+ },
+ "admin_server": {
+ "url": "https://admin-server.com/mcp",
+ "access_groups": ["admin"],
+ "transport": MCPTransport.http,
+ },
}
- })
-
+ )
+
# Mock user with specific access groups
user_auth = UserAPIKeyAuth(
- api_key="test-key",
- user_id="test-user",
- team_id="team-staff"
+ api_key="test-key", user_id="test-user", team_id="team-staff"
)
-
+
# Mock the permission lookup to return staff access group
with patch.object(MCPRequestHandler, "get_allowed_mcp_servers") as mock_get_allowed:
- mock_get_allowed.return_value = ["staff-server-id", "ops-server-id"] # User has access to staff and ops
-
+ mock_get_allowed.return_value = [
+ "staff-server-id",
+ "ops-server-id",
+ ] # User has access to staff and ops
+
allowed_servers = await test_manager.get_allowed_mcp_servers(user_auth)
-
+
# Should only get servers user has access to
assert len(allowed_servers) >= 0 # At least verify no errors
mock_get_allowed.assert_called_once_with(user_auth)
-
-
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
index bbfefed106a..2dcca0b34cd 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
@@ -23,7 +23,6 @@ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
@pytest.mark.asyncio
class TestMCPRequestHandler:
-
@pytest.mark.parametrize(
"user_api_key_auth,object_permission_id,prisma_client_available,db_result,expected_result",
[
@@ -172,7 +171,10 @@ class TestMCPRequestHandler:
with patch.object(
MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
) as mock_team_servers:
+<<<<<<< HEAD
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
# Configure mocks to return the test data
mock_key_servers.return_value = key_servers
mock_team_servers.return_value = team_servers
@@ -344,11 +346,17 @@ class TestMCPRequestHandler:
# Create an async mock for user_api_key_auth
async def mock_user_api_key_auth(api_key, request):
return UserAPIKeyAuth(
+<<<<<<< HEAD
token=(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
if api_key
else None
),
+=======
+ token="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ if api_key
+ else None,
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
api_key=api_key,
user_id="test-user-id" if api_key else None,
team_id="test-team-id" if api_key else None,
@@ -366,7 +374,10 @@ class TestMCPRequestHandler:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
+<<<<<<< HEAD
mcp_protocol_version,
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
) = await MCPRequestHandler.process_mcp_request(scope)
# Assert the results
@@ -377,7 +388,6 @@ class TestMCPRequestHandler:
assert mcp_server_auth_headers == expected_server_auth_headers
# For these tests, mcp_servers should be None
assert mcp_servers is None
- assert mcp_protocol_version is None
@pytest.mark.parametrize(
"headers,expected_result",
@@ -547,15 +557,16 @@ class TestMCPRequestHandler:
mcp_auth_header,
mcp_servers_result,
mcp_server_auth_headers,
+<<<<<<< HEAD
mcp_protocol_version,
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
) = await MCPRequestHandler.process_mcp_request(scope)
assert auth_result == mock_auth_result
assert mcp_auth_header == expected_result["mcp_auth"]
assert mcp_servers_result == expected_result["mcp_servers"]
# For these tests, mcp_server_auth_headers should be empty
assert mcp_server_auth_headers == {}
- # For these tests, mcp_protocol_version should be None
- assert mcp_protocol_version is None
class TestMCPCustomHeaderName:
@@ -588,7 +599,10 @@ class TestMCPCustomHeaderName:
with patch(
"litellm.proxy.proxy_server.general_settings"
) as mock_general_settings:
+<<<<<<< HEAD
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
# Configure mocks
mock_get_secret.return_value = env_var
mock_general_settings.get.return_value = general_setting
@@ -692,7 +706,10 @@ class TestMCPCustomHeaderName:
"_get_mcp_client_side_auth_header_name",
return_value="custom-auth-header",
):
+<<<<<<< HEAD
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
# Create ASGI scope with custom header
scope = {
"type": "http",
@@ -725,7 +742,10 @@ class TestMCPCustomHeaderName:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
+<<<<<<< HEAD
mcp_protocol_version,
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
) = await MCPRequestHandler.process_mcp_request(scope)
# Assert the results
@@ -733,7 +753,6 @@ class TestMCPCustomHeaderName:
assert mcp_auth_header == "custom-auth-token"
assert mcp_servers is None
assert mcp_server_auth_headers == {}
- assert mcp_protocol_version is None
# Verify the mock was called
mock_auth.assert_called_once()
@@ -897,7 +916,6 @@ class TestMCPAccessGroupsE2E:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
- mcp_protocol_version,
) = await MCPRequestHandler.process_mcp_request(scope)
# Assert the results
@@ -907,7 +925,6 @@ class TestMCPAccessGroupsE2E:
mcp_servers is None
) # x-mcp-access-groups is not parsed as mcp_servers
assert mcp_server_auth_headers == {}
- assert mcp_protocol_version is None
# Verify the mock was called
mock_auth.assert_called_once()
@@ -948,7 +965,10 @@ class TestMCPAccessGroupsE2E:
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
+<<<<<<< HEAD
mcp_protocol_version,
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
) = await MCPRequestHandler.process_mcp_request(scope)
# Assert the results
@@ -956,7 +976,6 @@ class TestMCPAccessGroupsE2E:
assert mcp_auth_header is None
assert mcp_servers == ["server1", "dev_group", "server2"]
assert mcp_server_auth_headers == {}
- assert mcp_protocol_version is None
# Verify the mock was called
mock_auth.assert_called_once()
@@ -978,7 +997,10 @@ def test_mcp_path_based_server_segregation(monkeypatch):
mcp_auth_header,
mcp_servers,
mcp_server_auth_headers,
+<<<<<<< HEAD
mcp_protocol_version,
+=======
+>>>>>>> 78d744e15d (fix: remove adding Mcp-Protocol-Version header (#14069))
) = get_auth_context()
# Capture the MCP servers for testing
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
index 088438556fd..9d8f3b0cf6b 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
@@ -88,19 +88,21 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():
working_server = MagicMock()
working_server.name = "working_server"
working_server.alias = "working"
-
+
failing_server = MagicMock()
failing_server.name = "failing_server"
failing_server.alias = "failing"
# Mock global_mcp_server_manager
mock_manager = MagicMock()
- mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["working_server", "failing_server"])
+ mock_manager.get_allowed_mcp_servers = AsyncMock(
+ return_value=["working_server", "failing_server"]
+ )
mock_manager.get_mcp_server_by_id = lambda server_id: (
working_server if server_id == "working_server" else failing_server
)
-
- async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):
+
+ async def mock_get_tools_from_server(server, mcp_auth_header=None):
if server.name == "working_server":
# Working server returns tools
tool1 = MagicMock()
@@ -111,7 +113,7 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():
else:
# Failing server raises an exception
raise Exception("Server connection failed")
-
+
mock_manager._get_tools_from_server = mock_get_tools_from_server
with patch(
@@ -124,26 +126,29 @@ async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():
# Test with server-specific auth headers
mcp_server_auth_headers = {
"working": "Bearer working-token",
- "failing": "Bearer failing-token"
+ "failing": "Bearer failing-token",
}
-
+
result = await _get_tools_from_mcp_servers(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=None,
mcp_servers=None,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=None
)
-
+
# Verify that tools from the working server are returned
assert len(result) == 1
assert result[0].name == "working_tool_1"
-
+
# Verify failure logging
- mock_logger.exception.assert_any_call("Error getting tools from server failing_server: Server connection failed")
-
+ mock_logger.exception.assert_any_call(
+ "Error getting tools from server failing_server: Server connection failed"
+ )
+
# Verify success logging
- mock_logger.info.assert_any_call("Successfully fetched 1 tools total from all MCP servers")
+ mock_logger.info.assert_any_call(
+ "Successfully fetched 1 tools total from all MCP servers"
+ )
@pytest.mark.asyncio
@@ -165,22 +170,24 @@ async def test_get_tools_from_mcp_servers_handles_all_servers_failing():
failing_server1 = MagicMock()
failing_server1.name = "failing_server1"
failing_server1.alias = "failing1"
-
+
failing_server2 = MagicMock()
failing_server2.name = "failing_server2"
failing_server2.alias = "failing2"
# Mock global_mcp_server_manager
mock_manager = MagicMock()
- mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["failing_server1", "failing_server2"])
+ mock_manager.get_allowed_mcp_servers = AsyncMock(
+ return_value=["failing_server1", "failing_server2"]
+ )
mock_manager.get_mcp_server_by_id = lambda server_id: (
failing_server1 if server_id == "failing_server1" else failing_server2
)
-
- async def mock_get_tools_from_server(server, mcp_auth_header=None, mcp_protocol_version=None):
+
+ async def mock_get_tools_from_server(server, mcp_auth_header=None):
# All servers fail
raise Exception(f"Server {server.name} connection failed")
-
+
mock_manager._get_tools_from_server = mock_get_tools_from_server
with patch(
@@ -193,26 +200,31 @@ async def test_get_tools_from_mcp_servers_handles_all_servers_failing():
# Test with server-specific auth headers
mcp_server_auth_headers = {
"failing1": "Bearer failing1-token",
- "failing2": "Bearer failing2-token"
+ "failing2": "Bearer failing2-token",
}
-
+
result = await _get_tools_from_mcp_servers(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=None,
mcp_servers=None,
mcp_server_auth_headers=mcp_server_auth_headers,
- mcp_protocol_version=None
)
-
+
# Verify that empty list is returned
assert len(result) == 0
-
+
# Verify failure logging for both servers
- mock_logger.exception.assert_any_call("Error getting tools from server failing_server1: Server failing_server1 connection failed")
- mock_logger.exception.assert_any_call("Error getting tools from server failing_server2: Server failing_server2 connection failed")
-
+ mock_logger.exception.assert_any_call(
+ "Error getting tools from server failing_server1: Server failing_server1 connection failed"
+ )
+ mock_logger.exception.assert_any_call(
+ "Error getting tools from server failing_server2: Server failing_server2 connection failed"
+ )
+
# Verify total logging
- mock_logger.info.assert_any_call("Successfully fetched 0 tools total from all MCP servers")
+ mock_logger.info.assert_any_call(
+ "Successfully fetched 0 tools total from all MCP servers"
+ )
@pytest.mark.asyncio
@@ -288,55 +300,66 @@ async def test_concurrent_initialize_session_managers():
)
except ImportError:
pytest.skip("MCP server not available")
-
+
# Import the module to reset state
import litellm.proxy._experimental.mcp_server.server as mcp_server
-
+
# Reset state before test
original_initialized = mcp_server._SESSION_MANAGERS_INITIALIZED
original_session_cm = mcp_server._session_manager_cm
original_sse_session_cm = mcp_server._sse_session_manager_cm
-
+
try:
mcp_server._SESSION_MANAGERS_INITIALIZED = False
mcp_server._session_manager_cm = None
mcp_server._sse_session_manager_cm = None
-
+
# Mock the session managers to avoid actual MCP initialization
- with patch('litellm.proxy._experimental.mcp_server.server.session_manager') as mock_session_manager, \
- patch('litellm.proxy._experimental.mcp_server.server.sse_session_manager') as mock_sse_session_manager, \
- patch('litellm.proxy._experimental.mcp_server.server.verbose_logger'):
-
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.session_manager"
+ ) as mock_session_manager, patch(
+ "litellm.proxy._experimental.mcp_server.server.sse_session_manager"
+ ) as mock_sse_session_manager, patch(
+ "litellm.proxy._experimental.mcp_server.server.verbose_logger"
+ ):
# Mock the run() method to return a mock context manager
mock_cm = AsyncMock()
mock_cm.__aenter__ = AsyncMock()
mock_cm.__aexit__ = AsyncMock()
-
+
mock_session_manager.run.return_value = mock_cm
mock_sse_session_manager.run.return_value = mock_cm
-
+
# Create multiple concurrent tasks that call initialize_session_managers
async def init_task():
await initialize_session_managers()
return "success"
-
+
# Run 10 concurrent initialization attempts
tasks = [init_task() for _ in range(10)]
results = await asyncio.gather(*tasks, return_exceptions=True)
-
+
# All tasks should complete successfully (no exceptions)
- assert all(result == "success" for result in results), f"Some tasks failed: {results}"
-
+ assert all(
+ result == "success" for result in results
+ ), f"Some tasks failed: {results}"
+
# session_manager.run() should only be called once due to the lock
- assert mock_session_manager.run.call_count == 1, f"Expected 1 call to session_manager.run(), got {mock_session_manager.run.call_count}"
- assert mock_sse_session_manager.run.call_count == 1, f"Expected 1 call to sse_session_manager.run(), got {mock_sse_session_manager.run.call_count}"
-
+ assert (
+ mock_session_manager.run.call_count == 1
+ ), f"Expected 1 call to session_manager.run(), got {mock_session_manager.run.call_count}"
+ assert (
+ mock_sse_session_manager.run.call_count == 1
+ ), f"Expected 1 call to sse_session_manager.run(), got {mock_sse_session_manager.run.call_count}"
+
# The context managers should only be entered once each
- assert mock_cm.__aenter__.call_count == 2, f"Expected 2 calls to __aenter__ (one for each session manager), got {mock_cm.__aenter__.call_count}"
-
+ assert (
+ mock_cm.__aenter__.call_count == 2
+ ), f"Expected 2 calls to __aenter__ (one for each session manager), got {mock_cm.__aenter__.call_count}"
+
# State should be properly set
assert mcp_server._SESSION_MANAGERS_INITIALIZED is True
-
+
finally:
# Restore original state
mcp_server._SESSION_MANAGERS_INITIALIZED = original_initialized
@@ -371,14 +394,12 @@ async def test_mcp_routing_with_conflicting_alias_and_group_name():
name="custom_solutions/user_123",
alias="custom_solutions/user_123",
transport=MCPTransport.http,
- spec_version=MCPSpecVersion.jun_2025,
)
other_server = MCPServer(
server_id="other_server_in_group_id",
name="custom_solutions/another_user_456",
alias="custom_solutions/another_user_456",
transport=MCPTransport.http,
- spec_version=MCPSpecVersion.jun_2025,
)
global_mcp_server_manager.registry[specific_server.server_id] = specific_server
global_mcp_server_manager.registry[other_server.server_id] = other_server
@@ -392,9 +413,13 @@ async def test_mcp_routing_with_conflicting_alias_and_group_name():
mock_get_tools_spy = AsyncMock(return_value=[])
# Mock the function that checks DB for an access group named "custom_solutions"
- mock_db_lookup = AsyncMock(return_value=[specific_server.server_id, other_server.server_id])
+ mock_db_lookup = AsyncMock(
+ return_value=[specific_server.server_id, other_server.server_id]
+ )
- mock_get_allowed = AsyncMock(return_value=[specific_server.server_id, other_server.server_id])
+ mock_get_allowed = AsyncMock(
+ return_value=[specific_server.server_id, other_server.server_id]
+ )
with patch(
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager.get_allowed_mcp_servers",
@@ -415,7 +440,9 @@ async def test_mcp_routing_with_conflicting_alias_and_group_name():
)
# Get the list of actual server objects that the orchestrator tried to contact
- called_servers = [call.kwargs["server"] for call in mock_get_tools_spy.call_args_list]
+ called_servers = [
+ call.kwargs["server"] for call in mock_get_tools_spy.call_args_list
+ ]
assert len(called_servers) == 1, "Should have resolved to exactly one server."
assert (
diff --git a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
index b75a55d9f2e..24bd8be6353 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
@@ -70,11 +70,6 @@ def generate_mock_mcp_server_config_record(
server_name=name,
url=url,
transport=MCPTransport.http if transport == "http" else MCPTransport.sse,
- spec_version=(
- MCPSpecVersion.mar_2025
- if spec_version == "2025-03-26"
- else MCPSpecVersion.nov_2024
- ),
auth_type=MCPAuth.api_key if auth_type == "api_key" else None,
mcp_info=MCPInfo(
server_name=name,
@@ -98,24 +93,34 @@ def generate_mock_user_api_key_auth(
)
-def generate_mock_team_record(team_id: str, team_alias: str, organization_id: str, mcp_servers: List[str]):
+def generate_mock_team_record(
+ team_id: str, team_alias: str, organization_id: str, mcp_servers: List[str]
+):
"""Generate a mock team record with object permissions"""
return MagicMock(
team_id=team_id,
team_alias=team_alias,
organization_id=organization_id,
members_with_roles=[{"user_id": "test_user_id"}],
- object_permission=MagicMock(mcp_servers=mcp_servers)
+ object_permission=MagicMock(mcp_servers=mcp_servers),
)
-def setup_mock_prisma_client(mock_prisma_client: MagicMock, team_records: List[MagicMock], mcp_servers: List[LiteLLM_MCPServerTable]):
+def setup_mock_prisma_client(
+ mock_prisma_client: MagicMock,
+ team_records: List[MagicMock],
+ mcp_servers: List[LiteLLM_MCPServerTable],
+):
"""Helper to set up a mock prisma client with proper async behavior"""
mock_prisma_client.db = MagicMock()
mock_prisma_client.db.litellm_teamtable = AsyncMock()
- mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=team_records)
+ mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(
+ return_value=team_records
+ )
mock_prisma_client.db.litellm_mcpservertable = AsyncMock()
- mock_prisma_client.db.litellm_mcpservertable.find_many = AsyncMock(return_value=mcp_servers)
+ mock_prisma_client.db.litellm_mcpservertable.find_many = AsyncMock(
+ return_value=mcp_servers
+ )
return mock_prisma_client
@@ -126,7 +131,7 @@ class TestListMCPServers:
async def test_list_mcp_servers_config_yaml_only(self):
"""
Test 1: Returns MCPs defined on the config.yaml only
-
+
Scenario: No DB MCPs, only config.yaml MCPs
Expected: Should return only config.yaml MCPs
"""
@@ -139,13 +144,13 @@ class TestListMCPServers:
team_id="team1",
team_alias="Team 1",
organization_id="org1",
- mcp_servers=["config_server_1", "config_server_2"]
+ mcp_servers=["config_server_1", "config_server_2"],
)
],
- mcp_servers=[] # No DB servers in this test
+ mcp_servers=[], # No DB servers in this test
)
mock_user_auth = generate_mock_user_api_key_auth()
-
+
# Mock config MCPs
config_server_1 = generate_mock_mcp_server_config_record(
server_id="config_server_1",
@@ -159,7 +164,7 @@ class TestListMCPServers:
url="https://mcp.deepwiki.com/mcp",
transport="http",
)
-
+
# Mock global MCP server manager
mock_manager = MagicMock()
mock_manager.config_mcp_servers = {
@@ -169,7 +174,7 @@ class TestListMCPServers:
mock_manager.get_allowed_mcp_servers = AsyncMock(
return_value=["config_server_1", "config_server_2"]
)
-
+
# Mock the new method that returns servers with health and team data
mock_servers_with_health = [
generate_mock_mcp_server_db_record(
@@ -183,12 +188,12 @@ class TestListMCPServers:
alias="DeepWiki MCP",
url="https://mcp.deepwiki.com/mcp",
transport="http",
- )
+ ),
]
mock_manager.get_all_mcp_servers_with_health_and_teams = AsyncMock(
return_value=mock_servers_with_health
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
mock_manager,
@@ -199,22 +204,21 @@ class TestListMCPServers:
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_all_mcp_servers,
)
-
+
result = await fetch_all_mcp_servers(user_api_key_dict=mock_user_auth)
-
+
# Verify results
assert len(result) == 2
-
+
# Check that both config servers are returned
server_ids = [server.server_id for server in result]
assert "config_server_1" in server_ids
assert "config_server_2" in server_ids
-
+
# Check server details
for server in result:
if server.server_id == "config_server_1":
@@ -230,7 +234,7 @@ class TestListMCPServers:
async def test_list_mcp_servers_combined_config_and_db(self):
"""
Test 2: If both config.yaml and DB then combines both and returns the result
-
+
Scenario: Both DB and config.yaml have MCPs
Expected: Should return combined list from both sources without duplicates
"""
@@ -247,7 +251,7 @@ class TestListMCPServers:
url="https://slack-mcp.example.com/mcp",
transport="http",
)
-
+
# Mock dependencies
mock_prisma_client = MagicMock()
mock_prisma_client = setup_mock_prisma_client(
@@ -257,13 +261,18 @@ class TestListMCPServers:
team_id="team1",
team_alias="Team 1",
organization_id="org1",
- mcp_servers=["db_server_1", "db_server_2", "config_server_1", "config_server_2"]
+ mcp_servers=[
+ "db_server_1",
+ "db_server_2",
+ "config_server_1",
+ "config_server_2",
+ ],
)
],
- mcp_servers=[db_server_1, db_server_2] # DB servers for this test
+ mcp_servers=[db_server_1, db_server_2], # DB servers for this test
)
mock_user_auth = generate_mock_user_api_key_auth()
-
+
# Mock config MCPs
config_server_1 = generate_mock_mcp_server_config_record(
server_id="config_server_1",
@@ -277,7 +286,7 @@ class TestListMCPServers:
url="https://mcp.deepwiki.com/mcp",
transport="http",
)
-
+
# Mock global MCP server manager
mock_manager = MagicMock()
mock_manager.config_mcp_servers = {
@@ -292,7 +301,7 @@ class TestListMCPServers:
"config_server_2",
]
)
-
+
# Mock the new method that returns servers with health and team data
mock_servers_with_health = [
db_server_1,
@@ -308,12 +317,12 @@ class TestListMCPServers:
alias="DeepWiki MCP",
url="https://mcp.deepwiki.com/mcp",
transport="http",
- )
+ ),
]
mock_manager.get_all_mcp_servers_with_health_and_teams = AsyncMock(
return_value=mock_servers_with_health
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
mock_manager,
@@ -324,24 +333,23 @@ class TestListMCPServers:
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_all_mcp_servers,
)
-
+
result = await fetch_all_mcp_servers(user_api_key_dict=mock_user_auth)
-
+
# Verify results
assert len(result) == 4
-
+
# Check that both DB and config servers are returned
server_ids = [server.server_id for server in result]
assert "db_server_1" in server_ids
assert "db_server_2" in server_ids
assert "config_server_1" in server_ids
assert "config_server_2" in server_ids
-
+
# Check server details
for server in result:
if server.server_id == "db_server_1":
@@ -365,7 +373,7 @@ class TestListMCPServers:
async def test_list_mcp_servers_non_admin_user_filtered(self):
"""
Test 3: Non-admin users only see MCPs they have access to
-
+
Scenario: Non-admin user with limited access
Expected: Should return only MCPs the user has access to
"""
@@ -375,7 +383,7 @@ class TestListMCPServers:
alias="Allowed Gmail MCP",
url="https://gmail-mcp.example.com/mcp",
)
-
+
# Mock dependencies
mock_prisma_client = MagicMock()
mock_prisma_client = setup_mock_prisma_client(
@@ -385,23 +393,23 @@ class TestListMCPServers:
team_id="team1",
team_alias="Team 1",
organization_id="org1",
- mcp_servers=["db_server_allowed", "config_server_allowed"]
+ mcp_servers=["db_server_allowed", "config_server_allowed"],
)
],
- mcp_servers=[db_server_allowed] # Only the allowed DB server
+ mcp_servers=[db_server_allowed], # Only the allowed DB server
)
mock_user_auth = generate_mock_user_api_key_auth(
user_role=LitellmUserRoles.INTERNAL_USER, # Non-admin user
team_id="team_123",
)
-
+
# Mock config MCPs - user has access to one
config_server_allowed = generate_mock_mcp_server_config_record(
server_id="config_server_allowed",
name="Allowed Zapier MCP",
url="https://actions.zapier.com/mcp/sse",
)
-
+
# Mock global MCP server manager
mock_manager = MagicMock()
mock_manager.config_mcp_servers = {
@@ -414,7 +422,7 @@ class TestListMCPServers:
mock_manager.get_allowed_mcp_servers = AsyncMock(
return_value=["db_server_allowed", "config_server_allowed"]
)
-
+
# Mock the new method that returns servers with health and team data
mock_servers_with_health = [
db_server_allowed,
@@ -422,12 +430,12 @@ class TestListMCPServers:
server_id="config_server_allowed",
alias="Allowed Zapier MCP",
url="https://actions.zapier.com/mcp/sse",
- )
+ ),
]
mock_manager.get_all_mcp_servers_with_health_and_teams = AsyncMock(
return_value=mock_servers_with_health
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
mock_manager,
@@ -438,23 +446,22 @@ class TestListMCPServers:
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_all_mcp_servers,
)
-
+
result = await fetch_all_mcp_servers(user_api_key_dict=mock_user_auth)
-
+
# Verify results - should only return servers user has access to
assert len(result) == 2
-
+
# Check that only allowed servers are returned
server_ids = [server.server_id for server in result]
assert "db_server_allowed" in server_ids
assert "config_server_allowed" in server_ids
assert "config_server_not_allowed" not in server_ids
-
+
# Check server details
for server in result:
if server.server_id == "db_server_allowed":
@@ -473,28 +480,29 @@ class TestMCPHealthCheckEndpoints:
"""Test successful health check for a specific MCP server"""
# Mock server
mock_server = generate_mock_mcp_server_db_record(
- server_id="test-server",
- alias="Test Server"
+ server_id="test-server", alias="Test Server"
)
-
+
# Mock dependencies
mock_prisma_client = MagicMock()
-
+
# Mock global MCP server manager
mock_manager = MagicMock()
- mock_manager.health_check_server = AsyncMock(return_value={
- "server_id": "test-server",
- "status": "healthy",
- "tools_count": 3,
- "last_health_check": "2024-01-01T12:00:00",
- "response_time_ms": 150.5,
- "error": None
- })
-
+ mock_manager.health_check_server = AsyncMock(
+ return_value={
+ "server_id": "test-server",
+ "status": "healthy",
+ "tools_count": 3,
+ "last_health_check": "2024-01-01T12:00:00",
+ "response_time_ms": 150.5,
+ "error": None,
+ }
+ )
+
mock_user_auth = generate_mock_user_api_key_auth(
user_role=LitellmUserRoles.PROXY_ADMIN
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
@@ -508,17 +516,15 @@ class TestMCPHealthCheckEndpoints:
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
AsyncMock(return_value=mock_server),
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
health_check_mcp_server,
)
-
+
result = await health_check_mcp_server(
- server_id="test-server",
- user_api_key_dict=mock_user_auth
+ server_id="test-server", user_api_key_dict=mock_user_auth
)
-
+
# Verify results
assert result["server_id"] == "test-server"
assert result["status"] == "healthy"
@@ -531,11 +537,11 @@ class TestMCPHealthCheckEndpoints:
"""Test health check for a server that doesn't exist"""
# Mock dependencies
mock_prisma_client = MagicMock()
-
+
mock_user_auth = generate_mock_user_api_key_auth(
user_role=LitellmUserRoles.PROXY_ADMIN
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
@@ -543,19 +549,17 @@ class TestMCPHealthCheckEndpoints:
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
AsyncMock(return_value=None),
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
health_check_mcp_server,
)
-
+
# Should raise HTTPException
with pytest.raises(Exception) as exc_info:
await health_check_mcp_server(
- server_id="non-existent-server",
- user_api_key_dict=mock_user_auth
+ server_id="non-existent-server", user_api_key_dict=mock_user_auth
)
-
+
assert "not found" in str(exc_info.value)
@pytest.mark.asyncio
@@ -563,20 +567,19 @@ class TestMCPHealthCheckEndpoints:
"""Test health check for a server user doesn't have access to"""
# Mock server
mock_server = generate_mock_mcp_server_db_record(
- server_id="test-server",
- alias="Test Server"
+ server_id="test-server", alias="Test Server"
)
-
+
# Mock dependencies
mock_prisma_client = MagicMock()
-
+
mock_user_auth = generate_mock_user_api_key_auth(
user_role=LitellmUserRoles.INTERNAL_USER # Non-admin user
)
-
+
# Mock user doesn't have access to this server
mock_user_servers = []
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
@@ -590,19 +593,17 @@ class TestMCPHealthCheckEndpoints:
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
AsyncMock(return_value=mock_server),
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
health_check_mcp_server,
)
-
+
# Should raise HTTPException
with pytest.raises(Exception) as exc_info:
await health_check_mcp_server(
- server_id="test-server",
- user_api_key_dict=mock_user_auth
+ server_id="test-server", user_api_key_dict=mock_user_auth
)
-
+
assert "permission" in str(exc_info.value)
@pytest.mark.asyncio
@@ -614,49 +615,53 @@ class TestMCPHealthCheckEndpoints:
team_id="team1",
team_alias="Team 1",
organization_id="org1",
- mcp_servers=["server1", "server2"]
+ mcp_servers=["server1", "server2"],
)
]
-
+
# Mock DB servers
db_servers = [
generate_mock_mcp_server_db_record(server_id="server1"),
- generate_mock_mcp_server_db_record(server_id="server2")
+ generate_mock_mcp_server_db_record(server_id="server2"),
]
-
+
# Mock dependencies
mock_prisma_client = MagicMock()
mock_prisma_client = setup_mock_prisma_client(
mock_prisma_client=mock_prisma_client,
team_records=team_records,
- mcp_servers=db_servers
+ mcp_servers=db_servers,
)
-
+
# Mock global MCP server manager
mock_manager = MagicMock()
- mock_manager.health_check_allowed_servers = AsyncMock(return_value={
- "server1": {
- "server_id": "server1",
- "status": "healthy",
- "tools_count": 2,
- "last_health_check": "2024-01-01T12:00:00",
- "response_time_ms": 100.0,
- "error": None
- },
- "server2": {
- "server_id": "server2",
- "status": "unhealthy",
- "last_health_check": "2024-01-01T12:00:00",
- "response_time_ms": 5000.0,
- "error": "Connection timeout"
+ mock_manager.health_check_allowed_servers = AsyncMock(
+ return_value={
+ "server1": {
+ "server_id": "server1",
+ "status": "healthy",
+ "tools_count": 2,
+ "last_health_check": "2024-01-01T12:00:00",
+ "response_time_ms": 100.0,
+ "error": None,
+ },
+ "server2": {
+ "server_id": "server2",
+ "status": "unhealthy",
+ "last_health_check": "2024-01-01T12:00:00",
+ "response_time_ms": 5000.0,
+ "error": "Connection timeout",
+ },
}
- })
- mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["server1", "server2"])
-
+ )
+ mock_manager.get_allowed_mcp_servers = AsyncMock(
+ return_value=["server1", "server2"]
+ )
+
mock_user_auth = generate_mock_user_api_key_auth(
user_role=LitellmUserRoles.INTERNAL_USER
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
@@ -667,14 +672,15 @@ class TestMCPHealthCheckEndpoints:
"litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
mock_manager,
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
health_check_all_mcp_servers,
)
-
- result = await health_check_all_mcp_servers(user_api_key_dict=mock_user_auth)
-
+
+ result = await health_check_all_mcp_servers(
+ user_api_key_dict=mock_user_auth
+ )
+
# Verify results
assert result["total_servers"] == 2
assert result["healthy_count"] == 1
@@ -682,7 +688,7 @@ class TestMCPHealthCheckEndpoints:
assert result["unknown_count"] == 0
assert "server1" in result["servers"]
assert "server2" in result["servers"]
-
+
# Check individual server results
assert result["servers"]["server1"]["status"] == "healthy"
assert result["servers"]["server1"]["tools_count"] == 2
@@ -694,32 +700,33 @@ class TestMCPHealthCheckEndpoints:
"""Test that fetch_all_mcp_servers includes health check status"""
# Mock server with health status
mock_server = generate_mock_mcp_server_db_record(
- server_id="test-server",
- alias="Test Server"
+ server_id="test-server", alias="Test Server"
)
# Add health status to the mock server
mock_server.status = "healthy"
mock_server.last_health_check = datetime.now()
mock_server.health_check_error = None
-
+
# Mock dependencies
mock_prisma_client = MagicMock()
mock_prisma_client = setup_mock_prisma_client(
mock_prisma_client=mock_prisma_client,
team_records=[],
- mcp_servers=[] # Don't add servers here since we're mocking get_all_mcp_servers
+ mcp_servers=[], # Don't add servers here since we're mocking get_all_mcp_servers
)
-
+
# Mock global MCP server manager
mock_manager = MagicMock()
mock_manager.config_mcp_servers = {}
mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=[])
- mock_manager.get_all_mcp_servers_with_health_and_teams = AsyncMock(return_value=[mock_server])
-
+ mock_manager.get_all_mcp_servers_with_health_and_teams = AsyncMock(
+ return_value=[mock_server]
+ )
+
mock_user_auth = generate_mock_user_api_key_auth(
user_role=LitellmUserRoles.PROXY_ADMIN
)
-
+
with patch(
"litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
return_value=mock_prisma_client,
@@ -730,14 +737,13 @@ class TestMCPHealthCheckEndpoints:
"litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
mock_manager,
):
-
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_all_mcp_servers,
)
-
+
result = await fetch_all_mcp_servers(user_api_key_dict=mock_user_auth)
-
+
# Verify health check status is included
assert len(result) == 1
server = result[0]