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]

[Feat] Add Authentication + Permission Management for MCP List, Call Tool Ops (#11682)

Ishaan Jaff19a8b23644c0
diff --git a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
new file mode 100644
index 00000000000..655b9ad0d86
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py
@@ -0,0 +1,12 @@
+from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
+
+from litellm.proxy._types import UserAPIKeyAuth
+
+
+class LiteLLMAuthenticatedUser(AuthenticatedUser):
+ """
+ Wrapper class to make UserAPIKeyAuth compatible with MCP's AuthenticatedUser
+ """
+
+ def __init__(self, user_api_key_auth: UserAPIKeyAuth):
+ self.user_api_key_auth = user_api_key_auth
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
new file mode 100644
index 00000000000..5e245715a1f
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
@@ -0,0 +1,198 @@
+from typing import List, Optional
+
+from starlette.datastructures import Headers
+from starlette.requests import Request
+from starlette.types import Scope
+
+from litellm._logging import verbose_logger
+from litellm.proxy._types import LiteLLM_TeamTableCachedObj, UserAPIKeyAuth
+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+
+
+class UserAPIKeyAuthMCP:
+ """
+ Class to handle Authentication for MCP requests
+
+ Utilizes the main `user_api_key_auth` function to validate the request
+ """
+
+ LITELLM_API_KEY_HEADER_NAME_PRIMARY = "x-litellm-api-key"
+ LITELLM_API_KEY_HEADER_NAME_SECONDARY = "Authorization"
+
+ @staticmethod
+ async def user_api_key_auth_mcp(scope: Scope) -> UserAPIKeyAuth:
+ """
+ Validate and extract headers from the ASGI scope for MCP requests.
+
+ Args:
+ scope: ASGI scope containing request information
+
+ Returns:
+ UserAPIKeyAuth containing validated authentication information
+
+ Raises:
+ HTTPException: If headers are invalid or missing required headers
+ """
+ headers = UserAPIKeyAuthMCP._safe_get_headers_from_scope(scope)
+ litellm_api_key = (
+ UserAPIKeyAuthMCP.get_litellm_api_key_from_headers(headers) or ""
+ )
+
+ # Create a proper Request object with mock body method to avoid ASGI receive channel issues
+ request = Request(scope=scope)
+
+ # Mock the body method to return empty dict as JSON bytes
+ # This prevents "Receive channel has not been made available" error
+ async def mock_body():
+ return b"{}" # Empty JSON object as bytes
+
+ 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
+
+ @staticmethod
+ def get_litellm_api_key_from_headers(headers: Headers) -> Optional[str]:
+ """
+ Get the Litellm API key from the headers using case-insensitive lookup
+
+ 1. Check if `x-litellm-api-key` is in the headers
+ 2. If not, check if `Authorization` is in the headers
+
+ Args:
+ headers: Starlette Headers object that handles case insensitivity
+ """
+ # Headers object handles case insensitivity automatically
+ api_key = headers.get(UserAPIKeyAuthMCP.LITELLM_API_KEY_HEADER_NAME_PRIMARY)
+ if api_key:
+ return api_key
+
+ auth_header = headers.get(
+ UserAPIKeyAuthMCP.LITELLM_API_KEY_HEADER_NAME_SECONDARY
+ )
+ if auth_header:
+ return auth_header
+
+ return None
+
+ @staticmethod
+ def _safe_get_headers_from_scope(scope: Scope) -> Headers:
+ """
+ Safely extract headers from ASGI scope using Starlette's Headers class
+ which handles case insensitivity and proper header parsing.
+
+ ASGI headers are in format: List[List[bytes, bytes]]
+ We need to convert them to the format Headers expects.
+ """
+ try:
+ # ASGI headers are list of [name: bytes, value: bytes] pairs
+ raw_headers = scope.get("headers", [])
+ # Convert bytes to strings and create dict for Headers constructor
+ headers_dict = {
+ name.decode("latin-1"): value.decode("latin-1")
+ for name, value in raw_headers
+ }
+ return Headers(headers_dict)
+ except Exception as e:
+ verbose_logger.exception(f"Error getting headers from scope: {e}")
+ # Return empty Headers object with empty dict
+ return Headers({})
+
+ @staticmethod
+ async def get_allowed_mcp_servers(
+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,
+ ) -> List[str]:
+ """
+ Apply least privilege
+ """
+ from typing import List
+
+ allowed_mcp_servers: List[str] = []
+ allowed_mcp_servers_for_key = (
+ await UserAPIKeyAuthMCP._get_allowed_mcp_servers_for_key(user_api_key_auth)
+ )
+ allowed_mcp_servers_for_team = (
+ await UserAPIKeyAuthMCP._get_allowed_mcp_servers_for_team(user_api_key_auth)
+ )
+
+ #########################################################
+ # If team has mcp_servers, then key must have a subset of the team's mcp_servers
+ #########################################################
+ if len(allowed_mcp_servers_for_team) > 0:
+ for _mcp_server in allowed_mcp_servers_for_key:
+ if _mcp_server in allowed_mcp_servers_for_team:
+ allowed_mcp_servers.append(_mcp_server)
+ else:
+ allowed_mcp_servers = allowed_mcp_servers_for_key
+
+ return list(set(allowed_mcp_servers))
+
+ @staticmethod
+ async def _get_allowed_mcp_servers_for_key(
+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,
+ ) -> List[str]:
+ from litellm.proxy.proxy_server import prisma_client
+
+ if user_api_key_auth is None:
+ return []
+
+ if user_api_key_auth.object_permission_id is None:
+ return []
+
+ if prisma_client is None:
+ verbose_logger.debug("prisma_client is None")
+ return []
+
+ key_object_permission = (
+ await prisma_client.db.litellm_objectpermissiontable.find_unique(
+ where={"object_permission_id": user_api_key_auth.object_permission_id},
+ )
+ )
+ if key_object_permission is None:
+ return []
+
+ return key_object_permission.mcp_servers or []
+
+ @staticmethod
+ async def _get_allowed_mcp_servers_for_team(
+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,
+ ) -> List[str]:
+ """
+ The `object_permission` for a team is not stored on the user_api_key_auth object
+
+ first we check if the team has a object_permission_id attached
+ - if it does then we look up the object_permission for the team
+ """
+ from litellm.proxy.auth.auth_checks import get_team_object
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+
+ if user_api_key_auth is None:
+ return []
+
+ if user_api_key_auth.team_id is None:
+ return []
+
+ team_obj: LiteLLM_TeamTableCachedObj = await get_team_object(
+ team_id=user_api_key_auth.team_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ check_cache_only=True,
+ )
+ if prisma_client is None:
+ verbose_logger.debug("prisma_client is None")
+ return []
+
+ object_permissions = team_obj.object_permission
+ if object_permissions is None:
+ return []
+
+ return object_permissions.mcp_servers or []
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index e362cb30333..55709d01b8d 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -17,6 +17,9 @@ from mcp.types import CallToolResult
from mcp.types import Tool as MCPTool
from litellm._logging import verbose_logger
+from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ UserAPIKeyAuthMCP,
+)
from litellm.proxy._types import (
LiteLLM_MCPServerTable,
MCPAuthType,
@@ -24,6 +27,7 @@ from litellm.proxy._types import (
MCPSpecVersionType,
MCPTransport,
MCPTransportType,
+ UserAPIKeyAuth,
)
try:
@@ -130,17 +134,45 @@ class MCPServerManager:
f"Added MCP Server: {mcp_server.alias or mcp_server.server_id}"
)
- async def list_tools(self) -> List[MCPTool]:
+ async def get_allowed_mcp_servers(
+ self, user_api_key_auth: Optional[UserAPIKeyAuth] = None
+ ) -> List[str]:
+ """
+ Get the allowed MCP Servers for the user
+ """
+ allowed_mcp_servers = await UserAPIKeyAuthMCP.get_allowed_mcp_servers(
+ user_api_key_auth
+ )
+ verbose_logger.debug(
+ f"Allowed MCP Servers for user api key auth: {allowed_mcp_servers}"
+ )
+ if len(allowed_mcp_servers) > 0:
+ return allowed_mcp_servers
+ else:
+ verbose_logger.debug(
+ "No allowed MCP Servers found for user api key auth, returning default registry servers"
+ )
+ return list(self.get_registry().keys())
+
+ async def list_tools(
+ self, user_api_key_auth: Optional[UserAPIKeyAuth] = None
+ ) -> List[MCPTool]:
"""
List all tools available across all MCP Servers.
Returns:
List[MCPTool]: Combined list of tools from all servers
"""
+ allowed_mcp_servers = await self.get_allowed_mcp_servers(user_api_key_auth)
+
list_tools_result: List[MCPTool] = []
verbose_logger.debug("SERVER MANAGER LISTING TOOLS")
- for _, server in self.get_registry().items():
+ for server_id in allowed_mcp_servers:
+ server = self.get_mcp_server_by_id(server_id)
+ if server is None:
+ verbose_logger.warning(f"MCP Server {server_id} not found")
+ continue
try:
tools = await self._get_tools_from_server(server)
list_tools_result.extend(tools)
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index caceec0658c..9dcb516ef5b 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -13,6 +13,10 @@ from starlette.types import Receive, Scope, Send
from litellm._logging import verbose_logger
from litellm.constants import MCP_TOOL_NAME_PREFIX
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ UserAPIKeyAuthMCP,
+)
+from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.mcp_server.mcp_server_manager import MCPInfo
from litellm.types.utils import StandardLoggingMCPToolCall
from litellm.utils import client
@@ -39,12 +43,21 @@ _SESSION_MANAGER_TASK = None
if MCP_AVAILABLE:
from mcp.server import Server
+
+ # Import auth context variables and middleware
+ from mcp.server.auth.middleware.auth_context import (
+ AuthContextMiddleware,
+ auth_context_var,
+ )
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.types import EmbeddedResource as MCPEmbeddedResource
from mcp.types import ImageContent as MCPImageContent
from mcp.types import TextContent as MCPTextContent
from mcp.types import Tool as MCPTool
+ from litellm.proxy._experimental.mcp_server.auth.litellm_auth_handler import (
+ LiteLLMAuthenticatedUser,
+ )
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
@@ -146,34 +159,18 @@ if MCP_AVAILABLE:
########################################################
############### MCP Server Routes #######################
########################################################
+
@server.list_tools()
async def list_tools() -> list[MCPTool]:
"""
List all available tools
"""
- return await _list_mcp_tools()
-
- async def _list_mcp_tools() -> List[MCPTool]:
- """
- List all available tools
- """
- tools = []
- for tool in global_mcp_tool_registry.list_tools():
- tools.append(
- MCPTool(
- name=tool.name,
- description=tool.description,
- inputSchema=tool.input_schema,
- )
- )
+ # Get user authentication from context variable
+ user_api_key_auth = get_auth_context()
verbose_logger.debug(
- "GLOBAL MCP TOOLS: %s", global_mcp_tool_registry.list_tools()
+ f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}"
)
- sse_tools: List[MCPTool] = await global_mcp_server_manager.list_tools()
- verbose_logger.debug("SSE TOOLS: %s", sse_tools)
- if sse_tools is not None:
- tools.extend(sse_tools)
- return tools
+ return await _list_mcp_tools(user_api_key_auth)
@server.call_tool()
async def mcp_server_tool_call(
@@ -199,6 +196,46 @@ if MCP_AVAILABLE:
)
return response
+ ########################################################
+ ############ End of MCP Server Routes ##################
+ ########################################################
+
+ ########################################################
+ ############ Helper Functions ##########################
+ ########################################################
+
+ async def _list_mcp_tools(
+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,
+ ) -> List[MCPTool]:
+ """
+ List all available tools
+
+ Args:
+ user_api_key_auth: User authentication info for access control
+ """
+ tools = []
+ for tool in global_mcp_tool_registry.list_tools():
+ tools.append(
+ MCPTool(
+ name=tool.name,
+ description=tool.description,
+ inputSchema=tool.input_schema,
+ )
+ )
+ verbose_logger.debug(
+ "GLOBAL MCP TOOLS: %s", global_mcp_tool_registry.list_tools()
+ )
+
+ tools_from_mcp_servers: List[MCPTool] = (
+ await global_mcp_server_manager.list_tools(
+ user_api_key_auth=user_api_key_auth,
+ )
+ )
+ 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
+
@client
async def call_mcp_tool(
name: str, arguments: Optional[Dict[str, Any]] = None, **kwargs: Any
@@ -221,15 +258,15 @@ if MCP_AVAILABLE:
"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[
- "model"
- ] = f"{MCP_TOOL_NAME_PREFIX}: {standard_logging_mcp_tool_call.get('name') or ''}"
- litellm_logging_obj.model_call_details[
- "custom_llm_provider"
- ] = standard_logging_mcp_tool_call.get("mcp_server_name")
+ litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = (
+ standard_logging_mcp_tool_call
+ )
+ litellm_logging_obj.model_call_details["model"] = (
+ f"{MCP_TOOL_NAME_PREFIX}: {standard_logging_mcp_tool_call.get('name') or ''}"
+ )
+ litellm_logging_obj.model_call_details["custom_llm_provider"] = (
+ standard_logging_mcp_tool_call.get("mcp_server_name")
+ )
# Try managed server tool first
if name in global_mcp_server_manager.tool_name_to_mcp_server_name_mapping:
@@ -287,6 +324,13 @@ if MCP_AVAILABLE:
) -> None:
"""Handle MCP requests through StreamableHTTP."""
try:
+ # Validate headers and log request info
+ user_api_key_auth: UserAPIKeyAuth = (
+ await UserAPIKeyAuthMCP.user_api_key_auth_mcp(scope)
+ )
+ # Set the auth context variable for easy access in MCP functions
+ set_auth_context(user_api_key_auth)
+
# Ensure session managers are initialized
if not _SESSION_MANAGERS_INITIALIZED:
await initialize_session_managers()
@@ -301,6 +345,13 @@ if MCP_AVAILABLE:
async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None:
"""Handle MCP requests through SSE."""
try:
+ # Validate headers and log request info
+ user_api_key_auth: UserAPIKeyAuth = (
+ await UserAPIKeyAuthMCP.user_api_key_auth_mcp(scope)
+ )
+ # Set the auth context variable for easy access in MCP functions
+ set_auth_context(user_api_key_auth)
+
# Ensure session managers are initialized
if not _SESSION_MANAGERS_INITIALIZED:
await initialize_session_managers()
@@ -333,6 +384,27 @@ if MCP_AVAILABLE:
# Mount the MCP handlers
app.mount("/", handle_streamable_http_mcp)
app.mount("/sse", handle_sse_mcp)
+ app.add_middleware(AuthContextMiddleware)
+
+ ########################################################
+ ############ Auth Context Functions ####################
+ ########################################################
+
+ def set_auth_context(user_api_key_auth: UserAPIKeyAuth) -> None:
+ """Set the UserAPIKeyAuth in the auth context variable."""
+ auth_user = LiteLLMAuthenticatedUser(user_api_key_auth)
+ auth_context_var.set(auth_user)
+
+ def get_auth_context() -> Optional[UserAPIKeyAuth]:
+ """Get the UserAPIKeyAuth from the auth context variable."""
+ auth_user = auth_context_var.get()
+ if auth_user and isinstance(auth_user, LiteLLMAuthenticatedUser):
+ return auth_user.user_api_key_auth
+ return None
+
+ ########################################################
+ ############ End of Auth Context Functions #############
+ ########################################################
else:
app = FastAPI()
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 2fe494e4060..234ee70b862 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -2779,7 +2779,7 @@ class ProxyConfig:
"""
await self._init_guardrails_in_db(prisma_client=prisma_client)
await self._init_vector_stores_in_db(prisma_client=prisma_client)
- # await self._init_mcp_servers_in_db()
+ await self._init_mcp_servers_in_db()
async def _init_guardrails_in_db(self, prisma_client: PrismaClient):
from litellm.proxy.guardrails.guardrail_registry import (
diff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.py
index b4af1dca28c..29dfa2c0554 100644
--- a/tests/mcp_tests/test_mcp_server.py
+++ b/tests/mcp_tests/test_mcp_server.py
@@ -329,8 +329,16 @@ async def test_streamable_http_mcp_handler_mock():
mock_session_manager = AsyncMock()
mock_session_manager.handle_request = AsyncMock()
- # Mock scope, receive, send
- mock_scope = {"type": "http", "method": "POST", "path": "/mcp"}
+ # Mock scope, receive, send with proper ASGI scope format
+ mock_scope = {
+ "type": "http",
+ "method": "POST",
+ "path": "/mcp",
+ "headers": [(b"content-type", b"application/json")],
+ "query_string": b"",
+ "server": ("localhost", 8000),
+ "scheme": "http"
+ }
mock_receive = AsyncMock()
mock_send = AsyncMock()
@@ -356,8 +364,16 @@ async def test_sse_mcp_handler_mock():
mock_sse_session_manager = AsyncMock()
mock_sse_session_manager.handle_request = AsyncMock()
- # Mock scope, receive, send
- mock_scope = {"type": "http", "method": "GET", "path": "/mcp/sse"}
+ # Mock scope, receive, send with proper ASGI scope format
+ mock_scope = {
+ "type": "http",
+ "method": "GET",
+ "path": "/mcp/sse",
+ "headers": [(b"accept", b"text/event-stream")],
+ "query_string": b"",
+ "server": ("localhost", 8000),
+ "scheme": "http"
+ }
mock_receive = AsyncMock()
mock_send = AsyncMock()
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
new file mode 100644
index 00000000000..f0c5c63a140
--- /dev/null
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
@@ -0,0 +1,194 @@
+import json
+import os
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import orjson
+import pytest
+from fastapi import Request
+from fastapi.testclient import TestClient
+
+sys.path.insert(
+ 0, os.path.abspath("../../../..")
+) # Adds the parent directory to the system path
+
+from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
+ UserAPIKeyAuthMCP,
+)
+from litellm.proxy._types import UserAPIKeyAuth
+
+
+class TestUserAPIKeyAuthMCP:
+
+ @pytest.mark.parametrize(
+ "user_api_key_auth,object_permission_id,prisma_client_available,db_result,expected_result",
+ [
+ # Test case 1: user_api_key_auth is None
+ (None, None, True, None, []),
+ # Test case 2: object_permission_id is None
+ (UserAPIKeyAuth(), None, True, None, []),
+ # Test case 3: prisma_client is None
+ (
+ UserAPIKeyAuth(object_permission_id="test-id"),
+ "test-id",
+ False,
+ None,
+ [],
+ ),
+ # Test case 4: Database query returns None
+ (UserAPIKeyAuth(object_permission_id="test-id"), "test-id", True, None, []),
+ # Test case 5: Database query returns object with mcp_servers
+ (
+ UserAPIKeyAuth(object_permission_id="test-id"),
+ "test-id",
+ True,
+ MagicMock(mcp_servers=["server1", "server2"]),
+ ["server1", "server2"],
+ ),
+ # Test case 6: Database query returns object with None mcp_servers
+ (
+ UserAPIKeyAuth(object_permission_id="test-id"),
+ "test-id",
+ True,
+ MagicMock(mcp_servers=None),
+ [],
+ ),
+ # Test case 7: Database query returns object with empty mcp_servers
+ (
+ UserAPIKeyAuth(object_permission_id="test-id"),
+ "test-id",
+ True,
+ MagicMock(mcp_servers=[]),
+ [],
+ ),
+ ],
+ )
+ async def test_get_allowed_mcp_servers_for_key(
+ self,
+ user_api_key_auth,
+ object_permission_id,
+ prisma_client_available,
+ db_result,
+ expected_result,
+ ):
+ """Test _get_allowed_mcp_servers_for_key with various scenarios"""
+
+ # Setup user_api_key_auth object_permission_id if provided
+ if user_api_key_auth and object_permission_id:
+ user_api_key_auth.object_permission_id = object_permission_id
+
+ # Mock prisma_client
+ mock_prisma_client = MagicMock() if prisma_client_available else None
+ mock_find_unique = None
+
+ if mock_prisma_client:
+ # Mock the database query
+ mock_find_unique = AsyncMock(return_value=db_result)
+ mock_prisma_client.db.litellm_objectpermissiontable.find_unique = (
+ mock_find_unique
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
+ # Call the method
+ result = await UserAPIKeyAuthMCP._get_allowed_mcp_servers_for_key(
+ user_api_key_auth
+ )
+
+ # Assert the result
+ assert result == expected_result
+
+ # Verify database call was made correctly when expected
+ if (
+ user_api_key_auth
+ and user_api_key_auth.object_permission_id
+ and prisma_client_available
+ and mock_find_unique
+ ):
+ mock_find_unique.assert_called_once_with(
+ where={
+ "object_permission_id": user_api_key_auth.object_permission_id
+ }
+ )
+ elif mock_find_unique:
+ # If prisma_client exists but conditions aren't met, no call should be made
+ if not user_api_key_auth or not user_api_key_auth.object_permission_id:
+ mock_find_unique.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "headers,expected_api_key",
+ [
+ # Test case 1: x-litellm-api-key header present
+ (
+ [(b"x-litellm-api-key", b"test-api-key-123")],
+ "test-api-key-123",
+ ),
+ # Test case 2: Authorization header present (fallback)
+ (
+ [(b"authorization", b"Bearer test-auth-token")],
+ "Bearer test-auth-token",
+ ),
+ # Test case 3: Both headers present (primary should win)
+ (
+ [
+ (b"x-litellm-api-key", b"primary-key"),
+ (b"authorization", b"Bearer fallback-token"),
+ ],
+ "primary-key",
+ ),
+ # Test case 4: Case insensitive headers
+ (
+ [(b"X-LITELLM-API-KEY", b"case-insensitive-key")],
+ "case-insensitive-key",
+ ),
+ # Test case 5: No relevant headers
+ (
+ [(b"content-type", b"application/json")],
+ "",
+ ),
+ # Test case 6: Empty headers
+ ([], ""),
+ ],
+ )
+ async def test_user_api_key_auth_mcp(self, headers, expected_api_key):
+ """Test user_api_key_auth_mcp method with various header scenarios"""
+
+ # Create ASGI scope with headers
+ scope = {
+ "type": "http",
+ "method": "POST",
+ "path": "/test",
+ "headers": headers,
+ }
+
+ # Mock the user_api_key_auth function
+ mock_auth_result = UserAPIKeyAuth(
+ api_key=expected_api_key,
+ user_id="test-user-id",
+ team_id="test-team-id",
+ )
+
+ 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
+ result = await UserAPIKeyAuthMCP.user_api_key_auth_mcp(scope)
+
+ # Assert the result
+ assert result == mock_auth_result
+
+ # Verify user_api_key_auth was called with correct parameters
+ mock_user_api_key_auth.assert_called_once()
+ call_args = mock_user_api_key_auth.call_args
+
+ # Check that api_key parameter is correct
+ assert call_args.kwargs["api_key"] == expected_api_key
+
+ # Check that request parameter is a Request object
+ request_param = call_args.kwargs["request"]
+ assert isinstance(request_param, Request)
+
+ # Verify the request has the correct scope
+ assert request_param.scope == scope