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]

[MCP Gateway] Litellm mcp multi header propagation (#13003)

Jugal D. Bhattb921e2259443
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.md
index 9a586c08893..de166864799 100644
--- a/docs/my-website/docs/mcp.md
+++ b/docs/my-website/docs/mcp.md
@@ -412,16 +412,64 @@ When creating API keys, you can assign them to specific access groups for permis
Use this if you want to pass a client side authentication token to LiteLLM to then pass to your MCP to auth to your MCP.
-You can specify your MCP auth token using the header `x-mcp-auth`. LiteLLM will forward this token to your MCP server for authentication.
+
+### New Server-Specific Auth Headers (Recommended)
+
+You can specify MCP auth tokens using server-specific headers in the format `x-mcp-{server_alias}-{header_name}`. This allows you to use different authentication for different MCP servers.
+
+**Format:** `x-mcp-{server_alias}-{header_name}: value`
+
+**Examples:**
+- `x-mcp-github-authorization: Bearer ghp_xxxxxxxxx` - GitHub MCP server with Bearer token
+- `x-mcp-zapier-x-api-key: sk-xxxxxxxxx` - Zapier MCP server with API key
+- `x-mcp-deepwiki-authorization: Basic base64_encoded_creds` - DeepWiki MCP server with Basic auth
+
+**Benefits:**
+- **Server-specific authentication**: Each MCP server can use different auth methods
+- **Better security**: No need to share the same auth token across all servers
+- **Flexible header names**: Support for different auth header types (authorization, x-api-key, etc.)
+- **Clean separation**: Each server's auth is clearly identified
+
+### Legacy Auth Header (Deprecated)
+
+You can also specify your MCP auth token using the header `x-mcp-auth`. This will be forwarded to all MCP servers and is deprecated in favor of server-specific headers.
<Tabs>
<TabItem value="openai" label="OpenAI API">
-#### Connect via OpenAI Responses API with MCP Auth
+#### Connect via OpenAI Responses API with Server-Specific Auth
+
+Use the OpenAI Responses API and include server-specific auth headers:
+
+```bash title="cURL Example with Server-Specific Auth" showLineNumbers
+curl --location 'https://api.openai.com/v1/responses' \
+--header 'Content-Type: application/json' \
+--header "Authorization: Bearer $OPENAI_API_KEY" \
+--data '{
+ "model": "gpt-4o",
+ "tools": [
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy",
+ "require_approval": "never",
+ "headers": {
+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
+ "x-mcp-github-authorization": "Bearer YOUR_GITHUB_TOKEN",
+ "x-mcp-zapier-x-api-key": "YOUR_ZAPIER_API_KEY"
+ }
+ }
+ ],
+ "input": "Run available tools",
+ "tool_choice": "required"
+}'
+```
+
+#### Connect via OpenAI Responses API with Legacy Auth
Use the OpenAI Responses API and include the `x-mcp-auth` header for your MCP server authentication:
-```bash title="cURL Example with MCP Auth" showLineNumbers
+```bash title="cURL Example with Legacy MCP Auth" showLineNumbers
curl --location 'https://api.openai.com/v1/responses' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $OPENAI_API_KEY" \
@@ -448,11 +496,39 @@ curl --location 'https://api.openai.com/v1/responses' \
<TabItem value="litellm" label="LiteLLM Proxy">
-#### Connect via LiteLLM Proxy Responses API with MCP Auth
+#### Connect via LiteLLM Proxy Responses API with Server-Specific Auth
+
+Use this when calling LiteLLM Proxy for LLM API requests to `/v1/responses` endpoint with server-specific authentication:
+
+```bash title="cURL Example with Server-Specific Auth" showLineNumbers
+curl --location '<your-litellm-proxy-base-url>/v1/responses' \
+--header 'Content-Type: application/json' \
+--header "Authorization: Bearer $LITELLM_API_KEY" \
+--data '{
+ "model": "gpt-4o",
+ "tools": [
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy",
+ "require_approval": "never",
+ "headers": {
+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
+ "x-mcp-github-authorization": "Bearer YOUR_GITHUB_TOKEN",
+ "x-mcp-zapier-x-api-key": "YOUR_ZAPIER_API_KEY"
+ }
+ }
+ ],
+ "input": "Run available tools",
+ "tool_choice": "required"
+}'
+```
+
+#### Connect via LiteLLM Proxy Responses API with Legacy Auth
Use this when calling LiteLLM Proxy for LLM API requests to `/v1/responses` endpoint with MCP authentication:
-```bash title="cURL Example with MCP Auth" showLineNumbers
+```bash title="cURL Example with Legacy MCP Auth" showLineNumbers
curl --location '<your-litellm-proxy-base-url>/v1/responses' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $LITELLM_API_KEY" \
@@ -479,7 +555,32 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \
<TabItem value="cursor" label="Cursor IDE">
-#### Connect via Cursor IDE with MCP Auth
+#### Connect via Cursor IDE with Server-Specific Auth
+
+Use tools directly from Cursor IDE with LiteLLM MCP and include server-specific authentication:
+
+**Setup Instructions:**
+
+1. **Open Cursor Settings**: Use `⇧+⌘+J` (Mac) or `Ctrl+Shift+J` (Windows/Linux)
+2. **Navigate to MCP Tools**: Go to the "MCP Tools" tab and click "New MCP Server"
+3. **Add Configuration**: Copy and paste the JSON configuration below, then save with `Cmd+S` or `Ctrl+S`
+
+```json title="Cursor MCP Configuration with Server-Specific Auth" showLineNumbers
+{
+ "mcpServers": {
+ "LiteLLM": {
+ "url": "litellm_proxy",
+ "headers": {
+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY",
+ "x-mcp-github-authorization": "Bearer $GITHUB_TOKEN",
+ "x-mcp-zapier-x-api-key": "$ZAPIER_API_KEY"
+ }
+ }
+ }
+}
+```
+
+#### Connect via Cursor IDE with Legacy Auth
Use tools directly from Cursor IDE with LiteLLM MCP and include your MCP authentication token:
@@ -489,7 +590,7 @@ Use tools directly from Cursor IDE with LiteLLM MCP and include your MCP authent
2. **Navigate to MCP Tools**: Go to the "MCP Tools" tab and click "New MCP Server"
3. **Add Configuration**: Copy and paste the JSON configuration below, then save with `Cmd+S` or `Ctrl+S`
-```json title="Cursor MCP Configuration with Auth" showLineNumbers
+```json title="Cursor MCP Configuration with Legacy Auth" showLineNumbers
{
"mcpServers": {
"LiteLLM": {
@@ -507,7 +608,23 @@ Use tools directly from Cursor IDE with LiteLLM MCP and include your MCP authent
<TabItem value="http" label="Streamable HTTP">
-#### Connect via Streamable HTTP Transport with MCP Auth
+#### Connect via Streamable HTTP Transport with Server-Specific Auth
+
+Connect to LiteLLM MCP using HTTP transport with server-specific authentication:
+
+**Server URL:**
+```text showLineNumbers
+litellm_proxy
+```
+
+**Headers:**
+```text showLineNumbers
+x-litellm-api-key: Bearer YOUR_LITELLM_API_KEY
+x-mcp-github-authorization: Bearer YOUR_GITHUB_TOKEN
+x-mcp-zapier-x-api-key: YOUR_ZAPIER_API_KEY
+```
+
+#### Connect via Streamable HTTP Transport with Legacy Auth
Connect to LiteLLM MCP using HTTP transport with MCP authentication:
@@ -528,11 +645,64 @@ This URL can be used with any MCP client that supports HTTP transport. The `x-mc
<TabItem value="fastmcp" label="Python FastMCP">
-#### Connect via Python FastMCP Client with MCP Auth
+#### Connect via Python FastMCP Client with Server-Specific Auth
+
+Use the Python FastMCP client to connect to your LiteLLM MCP server with server-specific authentication:
+
+```python title="Python FastMCP Example with Server-Specific Auth" showLineNumbers
+import asyncio
+import json
+
+from fastmcp import Client
+from fastmcp.client.transports import StreamableHttpTransport
+
+# Create the transport with your LiteLLM MCP server URL and server-specific auth headers
+server_url = "litellm_proxy"
+transport = StreamableHttpTransport(
+ server_url,
+ headers={
+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
+ "x-mcp-github-authorization": "Bearer YOUR_GITHUB_TOKEN",
+ "x-mcp-zapier-x-api-key": "YOUR_ZAPIER_API_KEY"
+ }
+)
+
+# Initialize the client with the transport
+client = Client(transport=transport)
+
+
+async def main():
+ # Connection is established here
+ print("Connecting to LiteLLM MCP server with server-specific authentication...")
+ async with client:
+ print(f"Client connected: {client.is_connected()}")
+
+ # Make MCP calls within the context
+ print("Fetching available tools...")
+ tools = await client.list_tools()
+
+ print(f"Available tools: {json.dumps([t.name for t in tools], indent=2)}")
+
+ # Example: Call a tool (replace 'tool_name' with an actual tool name)
+ if tools:
+ tool_name = tools[0].name
+ print(f"Calling tool: {tool_name}")
+
+ # Call the tool with appropriate arguments
+ result = await client.call_tool(tool_name, arguments={})
+ print(f"Tool result: {result}")
+
+
+# Run the example
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+#### Connect via Python FastMCP Client with Legacy Auth
Use the Python FastMCP client to connect to your LiteLLM MCP server with MCP authentication:
-```python title="Python FastMCP Example with MCP Auth" showLineNumbers
+```python title="Python FastMCP Example with Legacy MCP Auth" showLineNumbers
import asyncio
import json
@@ -583,7 +753,6 @@ if __name__ == "__main__":
</TabItem>
</Tabs>
-
### Customize the MCP Auth Header Name
By default, LiteLLM uses `x-mcp-auth` to pass your credentials to MCP servers. You can change this header name in one of the following ways:
diff --git a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
index fb9519a6551..cb4aab4bb1d 100644
--- a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
+++ b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Optional, Dict
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
@@ -11,11 +11,13 @@ class MCPAuthenticatedUser(AuthenticatedUser):
This class handles:
1. User API key authentication information
- 2. MCP authentication header
+ 2. MCP authentication header (deprecated)
3. MCP server configuration (can include access groups)
+ 4. Server-specific authentication headers
"""
- def __init__(self, user_api_key_auth: UserAPIKeyAuth, mcp_auth_header: Optional[str] = None, mcp_servers: Optional[List[str]] = None):
+ def __init__(self, user_api_key_auth: UserAPIKeyAuth, mcp_auth_header: Optional[str] = None, mcp_servers: Optional[List[str]] = None, mcp_server_auth_headers: Optional[Dict[str, str]] = None):
self.user_api_key_auth = user_api_key_auth
self.mcp_auth_header = mcp_auth_header
self.mcp_servers = mcp_servers
+ self.mcp_server_auth_headers = mcp_server_auth_headers or {}
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 708adf66db5..0f4acce21f2 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
@@ -1,4 +1,4 @@
-from typing import List, Optional, Tuple
+from typing import List, Optional, Tuple, Dict
from starlette.datastructures import Headers
from starlette.requests import Request
@@ -30,7 +30,7 @@ class MCPRequestHandler:
LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME = SpecialHeaders.mcp_access_groups.value
@staticmethod
- async def process_mcp_request(scope: Scope) -> Tuple[UserAPIKeyAuth, Optional[str], Optional[List[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:
@@ -43,8 +43,9 @@ class MCPRequestHandler:
Returns:
UserAPIKeyAuth containing validated authentication information
- mcp_auth_header: Optional[str] MCP auth header to be passed to the MCP server
+ 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}
Raises:
HTTPException: If headers are invalid or missing required headers
@@ -53,8 +54,13 @@ 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)
+
# Parse MCP servers from header
mcp_servers_header = headers.get(MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME)
verbose_logger.debug(f"Raw MCP servers header: {mcp_servers_header}")
@@ -76,7 +82,7 @@ class MCPRequestHandler:
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
+ return validated_user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers
@staticmethod
@@ -91,9 +97,52 @@ 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()
- return headers.get(mcp_client_side_auth_header_name)
+ auth_header = headers.get(mcp_client_side_auth_header_name)
+ if auth_header:
+ verbose_logger.warning(
+ f"The '{mcp_client_side_auth_header_name}' header is deprecated. "
+ 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():
+ continue
+
+ # Extract server_alias and header_name from x-mcp-{server_alias}-{header_name}
+ 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)
+ 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]}...")
+
+ return server_auth_headers
@staticmethod
def _get_mcp_client_side_auth_header_name() -> str:
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index 4b1432a81d2..93ac08b4f0f 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -115,10 +115,35 @@ class MCPServerManager:
for server_name, server_config in mcp_servers_config.items():
validate_mcp_server_name(server_name)
- _mcp_info: dict = server_config.get("mcp_info", None) or {}
- mcp_info = MCPInfo(**_mcp_info)
- mcp_info["server_name"] = server_name
- mcp_info["description"] = server_config.get("description", None)
+ _mcp_info: Dict[str, Any] = server_config.get("mcp_info", None) or {}
+ # Convert Dict[str, Any] to MCPInfo properly
+ mcp_info: MCPInfo = {
+ "server_name": _mcp_info.get("server_name", server_name),
+ "description": _mcp_info.get("description", server_config.get("description", None)),
+ "logo_url": _mcp_info.get("logo_url", None),
+ "mcp_server_cost_info": _mcp_info.get("mcp_server_cost_info", None),
+ }
+
+ # Use alias for name if present, else server_name
+ alias = server_config.get("alias", None)
+
+ # Apply mcp_aliases mapping if provided
+ if mcp_aliases and alias is None:
+ # Check if this server_name has an alias in mcp_aliases
+ for alias_name, target_server_name in mcp_aliases.items():
+ if target_server_name == server_name and alias_name not in used_aliases:
+ alias = alias_name
+ used_aliases.add(alias_name)
+ verbose_logger.debug(f"Mapped alias '{alias_name}' to server '{server_name}'")
+ break
+
+ # Create a temporary server object to use with get_server_prefix utility
+ temp_server = type('TempServer', (), {
+ 'alias': alias,
+ 'server_name': server_name,
+ 'server_id': None
+ })()
+ name_for_prefix = get_server_prefix(temp_server)
# Use alias for name if present, else server_name
alias = server_config.get("alias", None)
@@ -257,10 +282,16 @@ class MCPServerManager:
self,
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
) -> List[MCPTool]:
"""
List all tools available across all MCP Servers.
+ Args:
+ user_api_key_auth: User authentication
+ mcp_auth_header: MCP auth header (deprecated)
+ mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
+
Returns:
List[MCPTool]: Combined list of tools from all servers
"""
@@ -274,17 +305,32 @@ class MCPServerManager:
if server is None:
verbose_logger.warning(f"MCP Server {server_id} not found")
continue
+
+ # Get server-specific auth header if available
+ server_auth_header = None
+ if mcp_server_auth_headers and server.alias:
+ server_auth_header = mcp_server_auth_headers.get(server.alias)
+ elif mcp_server_auth_headers and server.server_name:
+ server_auth_header = mcp_server_auth_headers.get(server.server_name)
+
+ # Fall back to deprecated mcp_auth_header if no server-specific header found
+ if server_auth_header is None:
+ server_auth_header = mcp_auth_header
+
try:
tools = await self._get_tools_from_server(
server=server,
- mcp_auth_header=mcp_auth_header,
+ mcp_auth_header=server_auth_header,
)
list_tools_result.extend(tools)
+ verbose_logger.info(f"Successfully fetched {len(tools)} tools from server {server.name}")
except Exception as e:
- verbose_logger.exception(
- f"Error listing tools from server {server.name}: {str(e)}"
+ verbose_logger.warning(
+ f"Failed to list tools from server {server.name}: {str(e)}. Continuing with other servers."
)
+ # Continue with other servers instead of failing completely
+ verbose_logger.info(f"Successfully fetched {len(list_tools_result)} tools total from all servers")
return list_tools_result
#########################################################
@@ -345,7 +391,7 @@ class MCPServerManager:
List[MCPTool]: List of tools available on the server with prefixed names
"""
verbose_logger.debug(f"Connecting to url: {server.url}")
- verbose_logger.info("_get_tools_from_server...")
+ verbose_logger.info(f"_get_tools_from_server for {server.name}...")
client = None
try:
@@ -356,13 +402,21 @@ class MCPServerManager:
# Create a task for the client operations to ensure proper cancellation handling
async def _list_tools_task():
- async with client:
- tools = await client.list_tools()
- verbose_logger.debug(f"Tools from {server.name}: {tools}")
- return tools
+ try:
+ async with client:
+ tools = await client.list_tools()
+ verbose_logger.debug(f"Tools from {server.name}: {tools}")
+ return tools
+ except asyncio.CancelledError:
+ verbose_logger.warning(f"Client operation cancelled for {server.name}")
+ return []
+ except Exception as e:
+ verbose_logger.warning(f"Client operation failed for {server.name}: {str(e)}")
+ return []
try:
- tools = await _list_tools_task()
+ # Add timeout to prevent hanging
+ tools = await asyncio.wait_for(_list_tools_task(), timeout=30.0)
# Create new tools with prefixed names
prefixed_tools = []
@@ -383,15 +437,26 @@ class MCPServerManager:
self.tool_name_to_mcp_server_name_mapping[tool.name] = prefix
self.tool_name_to_mcp_server_name_mapping[prefixed_name] = prefix
+ verbose_logger.info(f"Successfully fetched {len(prefixed_tools)} tools from server {server.name}")
return prefixed_tools
+ except asyncio.TimeoutError:
+ verbose_logger.warning(f"Timeout while listing tools from {server.name}")
+ # Don't re-raise the exception, just return empty list
+ return []
except asyncio.CancelledError:
verbose_logger.warning(f"Task cancelled while listing tools from {server.name}")
- raise # Re-raise the cancellation
+ # Don't re-raise cancellation, just return empty list
+ return []
+ except ConnectionError as e:
+ verbose_logger.warning(f"Connection error while listing tools from {server.name}: {str(e)}")
+ # Don't re-raise the exception, just return empty list
+ return []
except Exception as e:
- verbose_logger.exception(f"Error listing tools from {server.name}: {str(e)}")
- raise
+ verbose_logger.warning(f"Error listing tools from {server.name}: {str(e)}")
+ # Don't re-raise the exception, just return empty list
+ return []
except Exception as e:
- verbose_logger.exception(f"Failed to get tools from server {server.name}: {str(e)}")
+ verbose_logger.warning(f"Failed to get tools from server {server.name}: {str(e)}")
return [] # Return empty list on failure
finally:
if client:
@@ -406,6 +471,7 @@ class MCPServerManager:
arguments: Dict[str, Any],
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
) -> CallToolResult:
"""
Call a tool with the given name and arguments (handles prefixed tool names)
@@ -414,7 +480,8 @@ class MCPServerManager:
name: Tool name (can be prefixed with server name)
arguments: Tool arguments
user_api_key_auth: User authentication
- mcp_auth_header: MCP auth header
+ mcp_auth_header: MCP auth header (deprecated)
+ mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
Returns:
CallToolResult from the MCP server
@@ -434,9 +501,20 @@ class MCPServerManager:
raise ValueError(
f"Tool {name} server prefix mismatch: expected {expected_prefix}, got {server_name_from_prefix}")
+ # Get server-specific auth header if available
+ server_auth_header = None
+ if mcp_server_auth_headers and mcp_server.alias:
+ server_auth_header = mcp_server_auth_headers.get(mcp_server.alias)
+ elif mcp_server_auth_headers and mcp_server.server_name:
+ server_auth_header = mcp_server_auth_headers.get(mcp_server.server_name)
+
+ # Fall back to deprecated mcp_auth_header if no server-specific header found
+ if server_auth_header is None:
+ server_auth_header = mcp_auth_header
+
client = self._create_mcp_client(
server=mcp_server,
- mcp_auth_header=mcp_auth_header,
+ mcp_auth_header=server_auth_header,
)
async with client:
# Use the original tool name (without prefix) for the actual call
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 7aab5eef987..8250b3e769a 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -20,7 +20,6 @@ from litellm.proxy._experimental.mcp_server.utils import (
LITELLM_MCP_SERVER_DESCRIPTION,
LITELLM_MCP_SERVER_NAME,
LITELLM_MCP_SERVER_VERSION,
- normalize_server_name,
)
from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.mcp_server.mcp_server_manager import MCPInfo, MCPServer
@@ -170,18 +169,22 @@ if MCP_AVAILABLE:
List all available tools
"""
# Get user authentication from context variable
- user_api_key_auth, mcp_auth_header, mcp_servers = 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 - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}"
+ )
# Get mcp_servers from context variable
return await _list_mcp_tools(
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,
)
@server.call_tool()
@@ -207,7 +210,7 @@ if MCP_AVAILABLE:
from litellm.proxy.proxy_server import proxy_config
# Validate arguments
- user_api_key_auth, mcp_auth_header, _ = get_auth_context()
+ 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}"
@@ -237,6 +240,7 @@ if MCP_AVAILABLE:
response = await call_mcp_tool(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
**data, # for logging
)
except Exception as e:
@@ -257,96 +261,129 @@ if MCP_AVAILABLE:
user_api_key_auth: Optional[UserAPIKeyAuth],
mcp_auth_header: Optional[str],
mcp_servers: Optional[List[str]],
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
) -> List[MCPTool]:
"""
Helper method to fetch tools from MCP servers based on server filtering criteria.
Args:
user_api_key_auth: User authentication info for access control
- mcp_auth_header: Optional auth header for MCP server
- mcp_servers: Optional list of server names and access groups to filter by
+ mcp_auth_header: Optional auth header for MCP server (deprecated)
+ mcp_servers: Optional list of server names/aliases to filter by
+ mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
Returns:
- List[MCPTool]: List of tools from the specified or all allowed MCP servers
+ List[MCPTool]: Combined list of tools from filtered servers
"""
- # Get all allowed servers for the user
- allowed_server_ids = await global_mcp_server_manager.get_allowed_mcp_servers(
+ if not 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
)
-
- # If mcp_servers header is present, filter servers
- if mcp_servers:
- tools = []
- filtered_server_ids = set()
-
- # For each item in mcp_servers, try to match as server name first, then as access group
- for server_or_group in mcp_servers:
- # Try to match as server name first
- server_name_matched = False
- for server_id in allowed_server_ids:
- server = global_mcp_server_manager.get_mcp_server_by_id(server_id)
- if server and normalize_server_name(server.name) == normalize_server_name(server_or_group):
- filtered_server_ids.add(server_id)
- server_name_matched = True
-
- # If no server name matched, try to treat it as an access group
- if not server_name_matched:
- try:
- 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_server_ids:
- filtered_server_ids.add(server_id)
- except Exception as e:
- verbose_logger.debug(f"Could not resolve '{server_or_group}' as access group: {e}")
+
+ # Filter servers based on mcp_servers parameter if provided
+ if mcp_servers is not None:
+ # Convert to lowercase for case-insensitive comparison
+ mcp_servers_lower = [s.lower() for s in mcp_servers]
+ allowed_mcp_servers = [
+ server_id
+ for server_id in allowed_mcp_servers
+ if any(
+ server_alias.lower() in mcp_servers_lower
+ for server in [global_mcp_server_manager.get_mcp_server_by_id(server_id)]
+ if server is not None
+ for server_alias in [
+ server.alias,
+ server.server_name,
+ server_id,
+ ]
+ if server_alias is not None
+ )
+ ]
+
+ # Get tools from each allowed server
+ all_tools = []
+ for server_id in allowed_mcp_servers:
+ server = global_mcp_server_manager.get_mcp_server_by_id(server_id)
+ if server is None:
+ continue
+
+ # Get server-specific auth header if available
+ server_auth_header = None
+ if mcp_server_auth_headers and server.alias is not None:
+ server_auth_header = mcp_server_auth_headers.get(server.alias)
+ elif mcp_server_auth_headers and server.server_name is not None:
+ server_auth_header = mcp_server_auth_headers.get(server.server_name)
- # Get tools from filtered servers
- for server_id in filtered_server_ids:
- server = global_mcp_server_manager.get_mcp_server_by_id(server_id)
- if server:
- server_tools = (
- await global_mcp_server_manager._get_tools_from_server(
- server=server,
- mcp_auth_header=mcp_auth_header,
- )
- )
- tools.extend(server_tools)
- return tools
- else:
- # If no filtering headers, get tools from all allowed servers
- return await global_mcp_server_manager.list_tools(
- user_api_key_auth=user_api_key_auth,
- mcp_auth_header=mcp_auth_header,
- )
+ # Fall back to deprecated mcp_auth_header if no server-specific header found
+ if server_auth_header is None:
+ server_auth_header = mcp_auth_header
+
+ try:
+ tools = await global_mcp_server_manager._get_tools_from_server(
+ server=server,
+ mcp_auth_header=server_auth_header,
+ )
+ all_tools.extend(tools)
+ 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)}"
+ )
+ # Continue with other servers instead of failing completely
+
+ verbose_logger.info(f"Successfully fetched {len(all_tools)} tools total from all MCP servers")
+ return all_tools
async def _list_mcp_tools(
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
mcp_servers: Optional[List[str]] = None,
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
) -> List[MCPTool]:
"""
- List all available tools
+ List all available MCP tools.
Args:
user_api_key_auth: User authentication info for access control
- mcp_auth_header: Optional auth header for MCP server
- mcp_servers: Optional list of server names and access groups to filter by
+ mcp_auth_header: Optional auth header for MCP server (deprecated)
+ mcp_servers: Optional list of server names/aliases to filter by
+ mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
+
+ Returns:
+ List[MCPTool]: Combined list of tools from all accessible servers
"""
- tools = []
+ if not MCP_AVAILABLE:
+ return []
- # Get tools from MCP servers
- tools_from_mcp_servers = await _get_tools_from_mcp_servers(
+ # Get tools from managed MCP servers
+ managed_tools = await _get_tools_from_mcp_servers(
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,
)
- verbose_logger.debug("TOOLS FROM MCP SERVERS: %s", tools_from_mcp_servers)
- if tools_from_mcp_servers is not None:
- tools.extend(tools_from_mcp_servers)
- return tools
+ # Get tools from local registry
+ local_tools_raw = global_mcp_tool_registry.list_tools()
+
+ # Convert local tools to MCPTool format
+ local_tools = []
+ 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
+ )
+ local_tools.append(mcp_tool)
+
+ # Combine all tools
+ all_tools = managed_tools + local_tools
+
+ return all_tools
@client
async def call_mcp_tool(
@@ -354,6 +391,7 @@ if MCP_AVAILABLE:
arguments: Optional[Dict[str, Any]] = None,
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
**kwargs: Any
) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""
@@ -400,6 +438,7 @@ if MCP_AVAILABLE:
arguments=arguments,
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
)
# Fall back to local tool registry (use original name)
@@ -450,6 +489,7 @@ if MCP_AVAILABLE:
arguments: Dict[str, Any],
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""Handle tool execution for managed server tools"""
call_tool_result = await global_mcp_server_manager.call_tool(
@@ -457,6 +497,7 @@ if MCP_AVAILABLE:
arguments=arguments,
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
)
verbose_logger.debug("CALL TOOL RESULT: %s", call_tool_result)
return call_tool_result.content # type: ignore[return-value]
@@ -481,7 +522,7 @@ if MCP_AVAILABLE:
async def extract_mcp_auth_context(scope, path):
"""
Extracts mcp_servers from the path and processes the MCP request for auth context.
- Returns: (user_api_key_auth, mcp_auth_header, mcp_servers)
+ Returns: (user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers)
"""
import re
mcp_servers_from_path = None
@@ -492,15 +533,15 @@ if MCP_AVAILABLE:
mcp_servers_from_path = [s.strip() for s in mcp_servers_str.split(",") if s.strip()]
if mcp_servers_from_path is not None:
- user_api_key_auth, mcp_auth_header, _ = (
+ user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers = (
await MCPRequestHandler.process_mcp_request(scope)
)
mcp_servers = mcp_servers_from_path
else:
- user_api_key_auth, mcp_auth_header, mcp_servers = (
+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = (
await MCPRequestHandler.process_mcp_request(scope)
)
- return user_api_key_auth, mcp_auth_header, mcp_servers
+ 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
@@ -508,13 +549,15 @@ if MCP_AVAILABLE:
"""Handle MCP requests through StreamableHTTP."""
try:
path = scope.get("path", "")
- user_api_key_auth, mcp_auth_header, mcp_servers = await extract_mcp_auth_context(scope, path)
+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await extract_mcp_auth_context(scope, path)
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}")
# 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,
)
# Ensure session managers are initialized
@@ -532,12 +575,14 @@ if MCP_AVAILABLE:
"""Handle MCP requests through SSE."""
try:
path = scope.get("path", "")
- user_api_key_auth, mcp_auth_header, mcp_servers = await extract_mcp_auth_context(scope, path)
+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await extract_mcp_auth_context(scope, path)
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}")
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,
)
if not _SESSION_MANAGERS_INITIALIZED:
@@ -580,30 +625,34 @@ if MCP_AVAILABLE:
user_api_key_auth: UserAPIKeyAuth,
mcp_auth_header: Optional[str] = None,
mcp_servers: Optional[List[str]] = None,
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
) -> None:
"""
Set the UserAPIKeyAuth in the auth context variable.
Args:
user_api_key_auth: UserAPIKeyAuth object
- mcp_auth_header: MCP auth header to be passed to the MCP server
+ mcp_auth_header: MCP auth header to be passed to the MCP server (deprecated)
mcp_servers: Optional list of server names and access groups to filter by
+ mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
"""
auth_user = MCPAuthenticatedUser(
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,
)
auth_context_var.set(auth_user)
def get_auth_context() -> (
- Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]]]
+ Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]]]
):
"""
Get the UserAPIKeyAuth from the auth context variable.
Returns:
- Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]]]: UserAPIKeyAuth object, MCP auth header, and MCP servers (can include access groups)
+ Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[Dict[str, str]]]:
+ UserAPIKeyAuth object, MCP auth header (deprecated), MCP servers (can include access groups), and server-specific auth headers
"""
auth_user = auth_context_var.get()
if auth_user and isinstance(auth_user, MCPAuthenticatedUser):
@@ -611,8 +660,9 @@ if MCP_AVAILABLE:
auth_user.user_api_key_auth,
auth_user.mcp_auth_header,
auth_user.mcp_servers,
+ auth_user.mcp_server_auth_headers,
)
- return None, None, None
+ return None, None, None, None
########################################################
############ End of Auth Context Functions #############
diff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.py
index 5d0dc72dc76..8401c1124a5 100644
--- a/tests/mcp_tests/test_mcp_server.py
+++ b/tests/mcp_tests/test_mcp_server.py
@@ -116,7 +116,7 @@ async def test_mcp_server_manager_https_server():
# Verify client methods were called
mock_client.__aenter__.assert_called()
- mock_client.list_tools.assert_called_once()
+ mock_client.list_tools.assert_called()
mock_client.call_tool.assert_called_once()
@@ -190,7 +190,8 @@ async def test_mcp_http_transport_list_tools_mock():
# Verify client methods were called
mock_client.__aenter__.assert_called()
- mock_client.list_tools.assert_called_once()
+ # Note: list_tools is called twice - once during initialization and once during the actual list_tools call
+ assert mock_client.list_tools.call_count == 2
# Verify tool mapping was updated
expected_prefix = "test_http_server"
@@ -672,6 +673,7 @@ async def test_get_tools_from_mcp_servers():
mock_server_1 = MCPServer(
server_id="server1_id",
name="server1",
+ server_name="server1",
url="http://test1.com",
transport=MCPTransport.http,
spec_version=MCPSpecVersion.nov_2024
@@ -679,6 +681,7 @@ async def test_get_tools_from_mcp_servers():
mock_server_2 = MCPServer(
server_id="server2_id",
name="server2",
+ server_name="server2",
url="http://test2.com",
transport=MCPTransport.http,
spec_version=MCPSpecVersion.nov_2024
@@ -696,13 +699,13 @@ async def test_get_tools_from_mcp_servers():
return mock_server_2
return None
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerManager.get_allowed_mcp_servers',
- new_callable=AsyncMock, return_value=["server1_id", "server2_id"]), \
- patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerManager.get_mcp_server_by_id',
- side_effect=mock_get_server_by_id), \
- patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerManager._get_tools_from_server',
- new_callable=AsyncMock, return_value=[mock_tool_1]):
+ # Create a mock manager
+ mock_manager = AsyncMock()
+ 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):
# Test with specific servers
result = await _get_tools_from_mcp_servers(
user_api_key_auth=mock_user_auth,
@@ -713,9 +716,14 @@ async def test_get_tools_from_mcp_servers():
assert result[0].name == "tool1", "Should return tool from server1"
# Test Case 2: Without specific MCP servers
- with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerManager.list_tools',
- new_callable=AsyncMock, return_value=[mock_tool_1, mock_tool_2]):
-
+ # 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_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:
+ [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):
result = await _get_tools_from_mcp_servers(
user_api_key_auth=mock_user_auth,
mcp_auth_header=mock_auth_header,
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 2739e6f45a4..e0d0992f968 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
@@ -119,19 +119,21 @@ class TestMCPRequestHandler:
mock_find_unique.assert_not_called()
@pytest.mark.parametrize(
- "headers,expected_api_key,expected_mcp_auth_header",
+ "headers,expected_api_key,expected_mcp_auth_header,expected_server_auth_headers",
[
# Test case 1: x-litellm-api-key header present
(
[(b"x-litellm-api-key", b"test-api-key-123")],
"test-api-key-123",
None,
+ {},
),
# Test case 2: Authorization header present (fallback)
(
[(b"authorization", b"Bearer test-auth-token")],
"Bearer test-auth-token",
None,
+ {},
),
# Test case 3: Both headers present (primary should win)
(
@@ -141,22 +143,25 @@ class TestMCPRequestHandler:
],
"primary-key",
None,
+ {},
),
# Test case 4: Case insensitive headers
(
[(b"X-LITELLM-API-KEY", b"case-insensitive-key")],
"case-insensitive-key",
None,
+ {},
),
# Test case 5: No relevant headers
(
[(b"content-type", b"application/json")],
"",
None,
+ {},
),
# Test case 6: Empty headers
- ([], "", None),
- # Test case 7: MCP auth header present
+ ([], "", None, {}),
+ # Test case 7: Legacy MCP auth header present
(
[
(b"x-litellm-api-key", b"test-api-key-123"),
@@ -164,17 +169,62 @@ class TestMCPRequestHandler:
],
"test-api-key-123",
"mcp-auth-token",
+ {},
),
- # Test case 8: Only MCP auth header present (no API key)
+ # Test case 8: Only legacy MCP auth header present (no API key)
(
[(b"x-mcp-auth", b"mcp-auth-token")],
"",
"mcp-auth-token",
+ {},
+ ),
+ # Test case 9: Server-specific auth headers present
+ (
+ [
+ (b"x-litellm-api-key", b"test-api-key-123"),
+ (b"x-mcp-github-authorization", b"Bearer github-token"),
+ (b"x-mcp-zapier_x_api-key", b"zapier-api-key"),
+ ],
+ "test-api-key-123",
+ None,
+ {"github": "Bearer github-token", "zapier_x_api": "zapier-api-key"},
+ ),
+ # Test case 10: Both legacy and server-specific auth headers
+ (
+ [
+ (b"x-litellm-api-key", b"test-api-key-123"),
+ (b"x-mcp-auth", b"legacy-token"),
+ (b"x-mcp-github-authorization", b"Bearer github-token"),
+ ],
+ "test-api-key-123",
+ "legacy-token",
+ {"github": "Bearer github-token"},
+ ),
+ # Test case 11: Server-specific auth headers with different header types
+ (
+ [
+ (b"x-litellm-api-key", b"test-api-key-123"),
+ (b"x-mcp-deepwiki-authorization", b"Basic base64-encoded"),
+ (b"x-mcp-custom_x_custom-header", b"custom-value"),
+ ],
+ "test-api-key-123",
+ None,
+ {"deepwiki": "Basic base64-encoded", "custom_x_custom": "custom-value"},
+ ),
+ # Test case 12: Case insensitive server-specific headers
+ (
+ [
+ (b"x-litellm-api-key", b"test-api-key-123"),
+ (b"X-MCP-GITHUB-AUTHORIZATION", b"Bearer github-token"),
+ ],
+ "test-api-key-123",
+ None,
+ {"github": "Bearer github-token"},
),
],
)
- async def test_process_mcp_request(self, headers, expected_api_key, expected_mcp_auth_header):
- """Test process_mcp_request method with various header scenarios"""
+ async def test_process_mcp_request_with_server_auth_headers(self, headers, expected_api_key, expected_mcp_auth_header, expected_server_auth_headers):
+ """Test process_mcp_request method with server-specific auth headers"""
# Create ASGI scope with headers
scope = {
@@ -200,13 +250,14 @@ class TestMCPRequestHandler:
side_effect=mock_user_api_key_auth,
) as mock_auth:
# Call the method
- auth_result, mcp_auth_header, mcp_servers = await MCPRequestHandler.process_mcp_request(scope)
+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)
# Assert the results
assert auth_result.api_key == expected_api_key
assert auth_result.user_id == ("test-user-id" if expected_api_key else None)
assert auth_result.team_id == ("test-team-id" if expected_api_key else None)
assert mcp_auth_header == expected_mcp_auth_header
+ assert mcp_server_auth_headers == expected_server_auth_headers
# For these tests, mcp_servers should be None
assert mcp_servers is None
@@ -367,10 +418,12 @@ class TestMCPRequestHandler:
mock_user_api_key_auth.return_value = mock_auth_result
# Call the method
- auth_result, mcp_auth_header, mcp_servers_result = await MCPRequestHandler.process_mcp_request(scope)
+ auth_result, mcp_auth_header, mcp_servers_result, mcp_server_auth_headers = 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 == {}
class TestMCPCustomHeaderName:
@@ -497,126 +550,249 @@ class TestMCPCustomHeaderName:
@pytest.mark.asyncio
async def test_process_mcp_request_with_custom_auth_header(self):
- """Test that process_mcp_request works with custom authentication header"""
+ """Test process_mcp_request with custom auth header name"""
- custom_header_name = "x-custom-mcp-auth"
- custom_auth_token = "custom-auth-token-123"
- api_key = "test-api-key"
+ # Mock the custom header name
+ with patch.object(MCPRequestHandler, '_get_mcp_client_side_auth_header_name', return_value="custom-auth-header"):
+
+ # Create ASGI scope with custom header
+ scope = {
+ "type": "http",
+ "method": "POST",
+ "path": "/test",
+ "headers": [
+ (b"x-litellm-api-key", b"test-api-key"),
+ (b"custom-auth-header", b"custom-auth-token"),
+ ],
+ }
+
+ # Create an async mock for user_api_key_auth
+ async def mock_user_api_key_auth(api_key, request):
+ return UserAPIKeyAuth(
+ token="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ api_key=api_key,
+ user_id="test-user-id",
+ team_id="test-team-id",
+ user_role=None,
+ request_route=None
+ )
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth",
+ side_effect=mock_user_api_key_auth,
+ ) as mock_auth:
+ # Call the method
+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)
+
+ # Assert the results
+ assert auth_result.api_key == "test-api-key"
+ assert mcp_auth_header == "custom-auth-token"
+ assert mcp_servers is None
+ assert mcp_server_auth_headers == {}
+
+ # Verify the mock was called
+ mock_auth.assert_called_once()
+ call_args = mock_auth.call_args
+ assert call_args.kwargs["api_key"] == "test-api-key"
+
+ def test_get_mcp_server_auth_headers_from_headers(self):
+ """Test _get_mcp_server_auth_headers_from_headers method"""
+ from starlette.datastructures import Headers
+
+ # Test case 1: No server-specific headers
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "content-type": "application/json"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ assert result == {}
+
+ # Test case 2: Single server-specific header
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github-authorization": "Bearer github-token"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ assert result == {"github": "Bearer github-token"}
+
+ # Test case 3: Multiple server-specific headers
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github-authorization": "Bearer github-token",
+ "x-mcp-zapier_x_api-key": "zapier-api-key",
+ "x-mcp-deepwiki-authorization": "Basic base64-encoded"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ expected = {
+ "github": "Bearer github-token",
+ "zapier_x_api": "zapier-api-key",
+ "deepwiki": "Basic base64-encoded"
+ }
+ assert result == expected
- # Create ASGI scope with custom header
+ # Test case 4: Case insensitive headers
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "X-MCP-GITHUB-AUTHORIZATION": "Bearer github-token",
+ "x-mcp-ZAPIER_x_api-key": "zapier-api-key"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ expected = {
+ "github": "Bearer github-token",
+ "zapier_x_api": "zapier-api-key"
+ }
+ assert result == expected
+
+ # Test case 5: Invalid format headers (should be ignored)
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-invalid": "should-be-ignored",
+ "x-mcp-github": "should-be-ignored",
+ "x-mcp-github-authorization": "Bearer github-token"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ assert result == {"github": "Bearer github-token"}
+
+ # Test case 6: Edge case - header with multiple hyphens in server alias
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github_mcp-authorization": "Bearer github-mcp-token",
+ "x-mcp-gh_mcp2-authorization": "Bearer gh-mcp2-token"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ expected = {
+ "github_mcp": "Bearer github-mcp-token",
+ "gh_mcp2": "Bearer gh-mcp2-token"
+ }
+ assert result == expected
+
+ # Test case 7: Edge case - header with underscore in server alias
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github_mcp-authorization": "Bearer github-mcp-token"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ assert result == {"github_mcp": "Bearer github-mcp-token"}
+
+ # Test case 8: Edge case - empty header value
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github-authorization": ""
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ assert result == {"github": ""}
+
+ # Test case 9: Edge case - very long header value
+ long_token = "Bearer " + "x" * 1000
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github-authorization": long_token
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ assert result == {"github": long_token}
+
+ # Test case 10: Edge case - special characters in server alias
+ headers = Headers({
+ "x-litellm-api-key": "test-key",
+ "x-mcp-github-123-authorization": "Bearer github-123-token",
+ "x-mcp-github_test-authorization": "Bearer github-test-token"
+ })
+ result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
+ expected = {
+ "github-123": "Bearer github-123-token",
+ "github_test": "Bearer github-test-token"
+ }
+ assert result == expected
+
+
+class TestMCPAccessGroupsE2E:
+ """Simple e2e tests for MCP access groups functionality"""
+
+ @pytest.mark.asyncio
+ async def test_mcp_access_group_resolution_e2e(self):
+ """Test that MCP access groups are properly resolved from headers"""
+
+ # Create ASGI scope with access groups header
scope = {
"type": "http",
"method": "POST",
"path": "/test",
"headers": [
- (b"x-litellm-api-key", api_key.encode()),
- (custom_header_name.encode(), custom_auth_token.encode()),
+ (b"x-litellm-api-key", b"test-api-key"),
+ (b"x-mcp-access-groups", b"dev_group,prod_group"),
],
}
-
- # Mock the custom header name method
- with patch.object(
- MCPRequestHandler,
- '_get_mcp_client_side_auth_header_name',
- return_value=custom_header_name
- ):
- # Mock user_api_key_auth
- mock_auth_result = UserAPIKeyAuth(
+
+ # Create an async mock for user_api_key_auth
+ async def mock_user_api_key_auth(api_key, request):
+ return UserAPIKeyAuth(
+ token="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
api_key=api_key,
user_id="test-user-id",
team_id="test-team-id",
+ user_role=None,
+ request_route=None
)
-
- with patch(
- "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth"
- ) as mock_user_api_key_auth:
- mock_user_api_key_auth.return_value = mock_auth_result
-
- # Call the method
- auth_result, mcp_auth_header, mcp_servers = await MCPRequestHandler.process_mcp_request(scope)
-
- # Assert the results
- assert auth_result == mock_auth_result
- assert mcp_auth_header == custom_auth_token
- assert mcp_servers is None
-
- # Verify user_api_key_auth was called with correct API key
- mock_user_api_key_auth.assert_called_once()
- call_args = mock_user_api_key_auth.call_args
- assert call_args.kwargs["api_key"] == api_key
-class TestMCPAccessGroupsE2E:
- """Simple e2e tests for MCP access groups functionality"""
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth",
+ side_effect=mock_user_api_key_auth,
+ ) as mock_auth:
+ # Call the method
+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)
- @pytest.mark.asyncio
- async def test_mcp_access_group_resolution_e2e(self):
- """E2E test: Pass access group in x-mcp-servers header, verify it resolves to server IDs"""
-
- # Mock servers that belong to the access group
- mock_server_1 = MagicMock()
- mock_server_1.server_id = "gmail-server"
- mock_server_2 = MagicMock()
- mock_server_2.server_id = "slack-server"
-
- # Mock prisma client
- mock_prisma_client = MagicMock()
- mock_find_many = AsyncMock(return_value=[mock_server_1, mock_server_2])
- mock_prisma_client.db.litellm_mcpservertable.find_many = mock_find_many
-
- with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
- # Test that when we pass an access group, it calls _get_mcp_servers_from_access_groups
- result = await MCPRequestHandler._get_mcp_servers_from_access_groups(
- access_groups=["dev-group"]
- )
-
- # Verify it unfurls the MCPs from that group
- assert sorted(result) == sorted(["gmail-server", "slack-server"])
-
- # Verify the correct database query was made
- mock_find_many.assert_called_once_with(
- where={
- "mcp_access_groups": {
- "hasSome": ["dev-group"]
- }
- }
- )
+ # Assert the results
+ assert auth_result.api_key == "test-api-key"
+ assert mcp_auth_header is None
+ assert mcp_servers is None
+ # The access groups header should not be parsed as a server auth header
+ # It should be handled separately by the access groups parsing logic
+ assert mcp_server_auth_headers == {}
+
+ # Verify the mock was called
+ mock_auth.assert_called_once()
@pytest.mark.asyncio
async def test_mcp_header_with_mixed_servers_and_groups(self):
- """E2E test: x-mcp-servers header with both server names and access groups"""
+ """Test that MCP headers work with mixed servers and access groups"""
- # Create ASGI scope with mixed servers and access groups
+ # Create ASGI scope with mixed servers and groups
scope = {
- "type": "http",
+ "type": "http",
"method": "POST",
"path": "/test",
"headers": [
(b"x-litellm-api-key", b"test-api-key"),
- (b"x-mcp-servers", b"zapier-server,dev-group"), # Mix of server name and access group
+ (b"x-mcp-servers", b"server1,dev_group,server2"),
],
}
-
- # Mock user authentication
+
+ # Create an async mock for user_api_key_auth
async def mock_user_api_key_auth(api_key, request):
return UserAPIKeyAuth(
- token="test-token",
+ token="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
api_key=api_key,
user_id="test-user-id",
team_id="test-team-id",
user_role=None,
request_route=None
)
-
+
with patch(
"litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth",
side_effect=mock_user_api_key_auth,
- ):
- # Call process_mcp_request
- auth_result, mcp_auth_header, mcp_servers = await MCPRequestHandler.process_mcp_request(scope)
-
- # Verify the header parsing worked correctly
+ ) as mock_auth:
+ # Call the method
+ auth_result, mcp_auth_header, mcp_servers, mcp_server_auth_headers = await MCPRequestHandler.process_mcp_request(scope)
+
+ # Assert the results
assert auth_result.api_key == "test-api-key"
- assert mcp_servers == ["zapier-server", "dev-group"] # Should contain both server name and access group
+ assert mcp_auth_header is None
+ assert mcp_servers == ["server1", "dev_group", "server2"]
+ assert mcp_server_auth_headers == {}
+
+ # Verify the mock was called
+ mock_auth.assert_called_once()
@pytest.mark.asyncio
@@ -628,9 +804,14 @@ def test_mcp_path_based_server_segregation(monkeypatch):
# Patch the session manager to send a dummy response and capture context
async def dummy_handle_request(scope, receive, send):
- from litellm.proxy._experimental.mcp_server.server import get_auth_context
- _, _, mcp_servers = get_auth_context()
- captured_mcp_servers[id(scope)] = mcp_servers
+ """Dummy handler for testing"""
+ # Get auth context
+ user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers = get_auth_context()
+
+ # Capture the MCP servers for testing
+ captured_mcp_servers["servers"] = mcp_servers
+
+ # Send response
await send({
"type": "http.response.start",
"status": 200,
@@ -638,7 +819,7 @@ def test_mcp_path_based_server_segregation(monkeypatch):
})
await send({
"type": "http.response.body",
- "body": b'{"ok": true}',
+ "body": b'{"status": "ok"}',
})
monkeypatch.setattr(
@@ -660,7 +841,7 @@ def test_mcp_path_based_server_segregation(monkeypatch):
client = TestClient(app)
response = client.get("/mcp/zapier,group1/tools", headers={"x-litellm-api-key": "test"})
assert response.status_code == 200
- assert response.json() == {"ok": True}
+ assert response.json() == {"status": "ok"}
# The context should have mcp_servers set to ["zapier", "group1"]
assert list(captured_mcp_servers.values())[0] == ["zapier", "group1"]
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 c1114d14438..7097bd0d283 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
@@ -69,6 +69,150 @@ async def test_mcp_server_tool_call_body_contains_request_data():
assert body["arguments"] == tool_arguments
+async def test_get_tools_from_mcp_servers_continues_when_one_server_fails():
+ """Test that _get_tools_from_mcp_servers continues when one server fails"""
+ try:
+ from litellm.proxy._experimental.mcp_server.server import (
+ _get_tools_from_mcp_servers,
+ set_auth_context,
+ )
+ except ImportError:
+ pytest.skip("MCP server not available")
+
+ # Mock user auth
+ user_api_key_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
+ set_auth_context(user_api_key_auth)
+
+ # Mock servers
+ 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_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):
+ if server.name == "working_server":
+ # Working server returns tools
+ tool1 = MagicMock()
+ tool1.name = "working_tool_1"
+ tool1.description = "Working tool 1"
+ tool1.inputSchema = {}
+ return [tool1]
+ else:
+ # Failing server raises an exception
+ raise Exception("Server connection failed")
+
+ mock_manager._get_tools_from_server = mock_get_tools_from_server
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
+ mock_manager,
+ ):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.verbose_logger",
+ ) as mock_logger:
+ # Test with server-specific auth headers
+ mcp_server_auth_headers = {
+ "working": "Bearer working-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
+ )
+
+ # 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")
+
+ # Verify success logging
+ mock_logger.info.assert_any_call("Successfully fetched 1 tools total from all MCP servers")
+
+
+async def test_get_tools_from_mcp_servers_handles_all_servers_failing():
+ """Test that _get_tools_from_mcp_servers handles all servers failing gracefully"""
+ try:
+ from litellm.proxy._experimental.mcp_server.server import (
+ _get_tools_from_mcp_servers,
+ set_auth_context,
+ )
+ except ImportError:
+ pytest.skip("MCP server not available")
+
+ # Mock user auth
+ user_api_key_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
+ set_auth_context(user_api_key_auth)
+
+ # Mock servers
+ 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_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):
+ # All servers fail
+ raise Exception(f"Server {server.name} connection failed")
+
+ mock_manager._get_tools_from_server = mock_get_tools_from_server
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
+ mock_manager,
+ ):
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.verbose_logger",
+ ) as mock_logger:
+ # Test with server-specific auth headers
+ mcp_server_auth_headers = {
+ "failing1": "Bearer failing1-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
+ )
+
+ # 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")
+
+ # Verify total logging
+ mock_logger.info.assert_any_call("Successfully fetched 0 tools total from all MCP servers")
+
+
@pytest.mark.asyncio
async def test_mcp_server_tool_call_body_with_none_arguments():
"""Test that proxy_server_request body handles None arguments correctly"""
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
index 486ad8fe331..e8c5a7965e2 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
@@ -1,6 +1,6 @@
import sys
from datetime import datetime
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, AsyncMock
import pytest
@@ -89,6 +89,157 @@ class TestMCPServerManager:
assert client.stdio_config["args"] == ["server.js"]
assert client.stdio_config["env"] == {"NODE_ENV": "test"}
+ @pytest.mark.asyncio
+ async def test_list_tools_with_server_specific_auth_headers(self):
+ """Test list_tools method with server-specific auth headers"""
+ manager = MCPServerManager()
+
+ # Mock servers
+ server1 = MagicMock()
+ server1.name = "github"
+ server1.alias = "github"
+ server1.server_name = "github"
+
+ server2 = MagicMock()
+ server2.name = "zapier"
+ server2.alias = "zapier"
+ server2.server_name = "zapier"
+
+ # Mock get_allowed_mcp_servers to return our test servers
+ manager.get_allowed_mcp_servers = AsyncMock(return_value=["github", "zapier"])
+ manager.get_mcp_server_by_id = MagicMock(side_effect=lambda x: server1 if x == "github" else server2)
+
+ # Mock _get_tools_from_server to return different results
+ async def mock_get_tools_from_server(server, mcp_auth_header=None):
+ if server.name == "github":
+ tool1 = MagicMock()
+ tool1.name = "github_tool_1"
+ tool2 = MagicMock()
+ tool2.name = "github_tool_2"
+ return [tool1, tool2]
+ else:
+ tool1 = MagicMock()
+ tool1.name = "zapier_tool_1"
+ return [tool1]
+
+ manager._get_tools_from_server = mock_get_tools_from_server
+
+ # Test with server-specific auth headers
+ mcp_server_auth_headers = {
+ "github": "Bearer github-token",
+ "zapier": "zapier-api-key"
+ }
+
+ result = await manager.list_tools(mcp_server_auth_headers=mcp_server_auth_headers)
+
+ # Verify that both servers were called with their specific auth headers
+ assert len(result) == 3 # 2 from github + 1 from zapier
+
+ # Verify the tools have the expected names
+ tool_names = [tool.name for tool in result]
+ assert "github_tool_1" in tool_names
+ assert "github_tool_2" in tool_names
+ assert "zapier_tool_1" in tool_names
+
+ @pytest.mark.asyncio
+ async def test_list_tools_fallback_to_legacy_auth_header(self):
+ """Test that list_tools falls back to legacy auth header when server-specific not available"""
+ manager = MCPServerManager()
+
+ # Mock server
+ server = MagicMock()
+ server.name = "github"
+ server.alias = "github"
+ server.server_name = "github"
+
+ # Mock get_allowed_mcp_servers
+ manager.get_allowed_mcp_servers = AsyncMock(return_value=["github"])
+ manager.get_mcp_server_by_id = MagicMock(return_value=server)
+
+ # Mock _get_tools_from_server
+ async def mock_get_tools_from_server(server, mcp_auth_header=None):
+ assert mcp_auth_header == "legacy-token" # Should use legacy header
+ tool = MagicMock()
+ tool.name = "github_tool_1"
+ return [tool]
+
+ manager._get_tools_from_server = mock_get_tools_from_server
+
+ # Test with only legacy auth header (no server-specific headers)
+ result = await manager.list_tools(
+ mcp_auth_header="legacy-token",
+ mcp_server_auth_headers={} # Empty server-specific headers
+ )
+
+ assert len(result) == 1
+ assert result[0].name == "github_tool_1"
+
+ @pytest.mark.asyncio
+ async def test_list_tools_prioritizes_server_specific_over_legacy(self):
+ """Test that server-specific auth headers take priority over legacy header"""
+ manager = MCPServerManager()
+
+ # Mock server
+ server = MagicMock()
+ server.name = "github"
+ server.alias = "github"
+ server.server_name = "github"
+
+ # Mock get_allowed_mcp_servers
+ manager.get_allowed_mcp_servers = AsyncMock(return_value=["github"])
+ manager.get_mcp_server_by_id = MagicMock(return_value=server)
+
+ # Mock _get_tools_from_server
+ async def mock_get_tools_from_server(server, mcp_auth_header=None):
+ assert mcp_auth_header == "server-specific-token" # Should use server-specific header
+ tool = MagicMock()
+ tool.name = "github_tool_1"
+ return [tool]
+
+ manager._get_tools_from_server = mock_get_tools_from_server
+
+ # Test with both legacy and server-specific headers
+ result = await manager.list_tools(
+ mcp_auth_header="legacy-token",
+ mcp_server_auth_headers={"github": "server-specific-token"}
+ )
+
+ assert len(result) == 1
+ assert result[0].name == "github_tool_1"
+
+ @pytest.mark.asyncio
+ async def test_list_tools_handles_missing_server_alias(self):
+ """Test that list_tools handles servers without alias gracefully"""
+ manager = MCPServerManager()
+
+ # Mock server without alias
+ server = MagicMock()
+ server.name = "github"
+ server.alias = None # No alias
+ server.server_name = "github"
+
+ # Mock get_allowed_mcp_servers
+ manager.get_allowed_mcp_servers = AsyncMock(return_value=["github"])
+ manager.get_mcp_server_by_id = MagicMock(return_value=server)
+
+ # Mock _get_tools_from_server
+ async def mock_get_tools_from_server(server, mcp_auth_header=None):
+ assert mcp_auth_header == "server-specific-token" # Should use server-specific header via server_name
+ tool = MagicMock()
+ tool.name = "github_tool_1"
+ return [tool]
+
+ manager._get_tools_from_server = mock_get_tools_from_server
+
+ # Test with server-specific headers that match server_name (even without alias)
+ result = await manager.list_tools(
+ mcp_auth_header="legacy-token",
+ mcp_server_auth_headers={"github": "server-specific-token"}
+ )
+
+ assert len(result) == 1
+ assert result[0].name == "github_tool_1"
+
if __name__ == "__main__":
pytest.main([__file__])
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index de1a509c8f0..9724b5ad426 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -5190,6 +5190,7 @@ export const callMCPTool = async (
toolName: string,
toolArguments: Record<string, any>,
authValue: string,
+ serverAlias?: string,
) => {
try {
// Construct base URL
@@ -5204,13 +5205,22 @@ export const callMCPTool = async (
toolArguments
);
+ const headers: Record<string, string> = {
+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ };
+
+ // Use new server-specific auth header format if serverAlias is provided
+ if (serverAlias) {
+ headers[`x-mcp-${serverAlias}-authorization`] = authValue;
+ } else {
+ // Fall back to deprecated x-mcp-auth header for backward compatibility
+ headers[MCP_AUTH_HEADER] = authValue;
+ }
+
const response = await fetch(url, {
method: "POST",
- headers: {
- [globalLitellmHeaderName]: `Bearer ${accessToken}`,
- [MCP_AUTH_HEADER]: authValue,
- "Content-Type": "application/json",
- },
+ headers,
body: JSON.stringify({
name: toolName,
arguments: toolArguments,