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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[MCP Gateway] Ensure we use the same param for specifying groups (#12561)
Ishaan Jaff50b106be1109
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.mdindex 75e3f2d2c54..a0a17ee03df 100644--- a/docs/my-website/docs/mcp.md+++ b/docs/my-website/docs/mcp.md@@ -111,6 +111,7 @@ mcp_servers:<Tabs><TabItem value="openai" label="OpenAI API">+### Quick Start#### Connect via OpenAI Responses APIUse the OpenAI Responses API to connect to your LiteLLM MCP server:@@ -197,7 +198,7 @@ Use tools directly from Cursor IDE with LiteLLM MCP:</TabItem></Tabs>-## Segregating MCP Server Access+### Specific MCP ServersYou can choose to access specific MCP servers and only list their tools using the `x-mcp-servers` header. This header allows you to:- Limit tool access to one or more specific MCP servers@@ -289,6 +290,58 @@ This configuration in Cursor IDE settings will limit tool access to only the spe</TabItem></Tabs>+### Grouping MCPs (Access Groups)++MCP Access Groups allow you to group multiple MCP servers together for easier management.++#### 1. Create an Access Group++To create an access group:+- Go to MCP Servers in the LiteLLM UI+- Click "Add a New MCP Server"+- Under "MCP Access Groups", create a new group (e.g., "dev_group") by typing it+- Add the same group name to other servers to group them together++<Image+ img={require('../img/mcp_create_access_group.png')}+ style={{width: '80%', display: 'block', margin: '0'}}+/>++#### 2. Use Access Group in Cursor++Include the access group name in the `x-mcp-servers` header:++```json title="Cursor Configuration with Access Groups" showLineNumbers+{+ "mcpServers": {+ "LiteLLM": {+ "url": "<your-litellm-proxy-base-url>/mcp",+ "headers": {+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY",+ "x-mcp-servers": "dev_group"+ }+ }+ }+}+```++This gives you access to all servers in the "dev_group" access group.++#### Advanced: Connecting Access Groups to API Keys++When creating API keys, you can assign them to specific access groups for permission management:++- Go to "Keys" in the LiteLLM UI and click "Create Key"+- Select the desired MCP access groups from the dropdown+- The key will have access to all MCP servers in those groups+- This is reflected in the Test Key page++<Image+ img={require('../img/mcp_key_access_group.png')}+ style={{width: '80%', display: 'block', margin: '0'}}+/>++## Using your MCP with client side credentialsUse this if you want to pass a client side authentication token to LiteLLM to then pass to your MCP to auth to your MCP.@@ -644,77 +697,6 @@ When Creating a Key, Team, or Organization, you can select the allowed MCP Servestyle={{width: '80%', display: 'block', margin: '0'}}/>--### MCP Access Groups--MCP Access Groups are managed via the LiteLLM UI. They allow you to group multiple MCP servers together and grant access to these groups when creating API keys. This makes it easy to give a key access to several MCP servers at once, without having to select each server individually.--#### 1. Managing Access Groups in the UI--To create and manage MCP access groups:-- Go to MCP Servers-- Click "Add a New MCP Server"-- Under the "MCP Access Groups" either select an existing group or create a new one by simply typing it-- To add more servers to this Access Group, go to their settings and add the same name Access Group under their dropdown--<Image- img={require('../img/mcp_create_access_group.png')}- style={{width: '80%', display: 'block', margin: '0'}}-/>--#### 2. Assigning Keys to Access Groups via the UI--When creating a key/team in the UI:-- You can select one or more MCP access groups to assign to the key.-- The key will then have access to all MCP servers included in those groups.-- This is reflected in the Test Key page, where only the MCP servers and tools from the assigned access groups will be available for testing.--<Image- img={require('../img/mcp_key_access_group.png')}- style={{width: '80%', display: 'block', margin: '0'}}-/>--*Example UI flow:*-- Go to "Keys" in the LiteLLM UI and click "Create Key".-- In the creation form, select the desired MCP access groups from the dropdown or list.-- Complete the key creation process. The new key will now have access to all MCP servers in the selected groups.--#### 3. Using the Access Group Header for Segregating Access--You can further restrict access at request time using the `x-mcp-access-groups` header. This allows you to dynamically limit which access groups are available for a given request. Note: The access groups referenced in the header must be created and managed in the UI.--**Example:**-```bash-curl --location 'https://api.openai.com/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $OPENAI_API_KEY" \---data '{- "model": "gpt-4.1",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "http://localhost:4000/mcp",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": [- "Zapier_Gmail"- ],- "x-mcp-access-groups": [- "dev"- ]-}- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```-This request will only have access to MCP servers in the specified access groups.--For all access group management, please use the LiteLLM UI.-## LiteLLM Proxy - Walk through MCP GatewayLiteLLM exposes an MCP Gateway for admins to add all their MCP servers to LiteLLM. The key benefits of using LiteLLM Proxy with MCP are:diff --git a/docs/my-website/img/mcp_create_access_group.png b/docs/my-website/img/mcp_create_access_group.pngindex 8476446b344..1ec74fed725 100644Binary files a/docs/my-website/img/mcp_create_access_group.png and b/docs/my-website/img/mcp_create_access_group.png differdiff --git a/docs/my-website/img/mcp_key_access_group.png b/docs/my-website/img/mcp_key_access_group.pngindex 19cf57254af..66e440f0a8d 100644Binary files a/docs/my-website/img/mcp_key_access_group.png and b/docs/my-website/img/mcp_key_access_group.png differdiff --git a/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.py b/litellm/proxy/_experimental/mcp_server/auth/litellm_auth_handler.pyindex 7875371ac9c..fb9519a6551 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 Optional, List+from typing import List, Optionalfrom mcp.server.auth.middleware.bearer_auth import AuthenticatedUser@@ -12,12 +12,10 @@ class MCPAuthenticatedUser(AuthenticatedUser):This class handles:1. User API key authentication information2. MCP authentication header- 3. MCP server configuration- 4. MCP access groups configuration+ 3. MCP server configuration (can include access groups)"""- def __init__(self, user_api_key_auth: UserAPIKeyAuth, mcp_auth_header: Optional[str] = None, mcp_servers: Optional[List[str]] = None, mcp_access_groups: Optional[List[str]] = None):+ def __init__(self, user_api_key_auth: UserAPIKeyAuth, mcp_auth_header: Optional[str] = None, mcp_servers: Optional[List[str]] = None):self.user_api_key_auth = user_api_key_authself.mcp_auth_header = mcp_auth_headerself.mcp_servers = mcp_servers- self.mcp_access_groups = mcp_access_groupsdiff --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.pyindex 30b5affdd3b..54428fafc23 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@@ -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]], Optional[List[str]]]:+ async def process_mcp_request(scope: Scope) -> Tuple[UserAPIKeyAuth, Optional[str], Optional[List[str]]]:"""Process and validate MCP request headers from the ASGI scope.This includes:@@ -44,8 +44,7 @@ class MCPRequestHandler:Returns:UserAPIKeyAuth containing validated authentication informationmcp_auth_header: Optional[str] MCP auth header to be passed to the MCP server- mcp_servers: Optional[List[str]] List of MCP servers to use- mcp_access_groups: Optional[List[str]] List of MCP access groups to use+ mcp_servers: Optional[List[str]] List of MCP servers and access groups to useRaises:HTTPException: If headers are invalid or missing required headers@@ -55,10 +54,8 @@ class MCPRequestHandler:MCPRequestHandler.get_litellm_api_key_from_headers(headers) or "")mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(headers)- # Use helper for access groups- mcp_access_groups = MCPRequestHandler.get_mcp_access_groups_from_headers(headers)- verbose_logger.debug(f"Parsed MCP access groups (helper): {mcp_access_groups}")- # Use existing logic for servers (or add a helper if desired)++ # Parse MCP servers from headermcp_servers_header = headers.get(MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME)verbose_logger.debug(f"Raw MCP servers header: {mcp_servers_header}")mcp_servers = None@@ -79,7 +76,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, mcp_access_groups+ return validated_user_api_key_auth, mcp_auth_header, mcp_servers@staticmethoddiff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex b01834b9b73..e758a4d74e4 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -170,22 +170,18 @@ if MCP_AVAILABLE:List all available tools"""# Get user authentication from context variable- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_access_groups = get_auth_context()+ user_api_key_auth, mcp_auth_header, mcp_servers = 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 access groups from context: {mcp_access_groups}"- )- # Get mcp_servers and mcp_access_groups from context variable+ # Get mcp_servers from context variablereturn await _list_mcp_tools(user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,- mcp_access_groups=mcp_access_groups,)@server.call_tool()@@ -211,7 +207,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, _ = get_auth_context()verbose_logger.debug(f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}"@@ -261,7 +257,6 @@ if MCP_AVAILABLE:user_api_key_auth: Optional[UserAPIKeyAuth],mcp_auth_header: Optional[str],mcp_servers: Optional[List[str]],- mcp_access_groups: Optional[List[str]],) -> List[MCPTool]:"""Helper method to fetch tools from MCP servers based on server filtering criteria.@@ -269,8 +264,7 @@ if MCP_AVAILABLE:Args:user_api_key_auth: User authentication info for access controlmcp_auth_header: Optional auth header for MCP server- mcp_servers: Optional list of server names to filter by- mcp_access_groups: Optional list of access group names to filter by+ mcp_servers: Optional list of server names and access groups to filter byReturns:List[MCPTool]: List of tools from the specified or all allowed MCP servers@@ -280,31 +274,33 @@ if MCP_AVAILABLE:user_api_key_auth)- # If either mcp_servers or mcp_access_groups headers are present, filter servers- if mcp_servers or mcp_access_groups:+ # If mcp_servers header is present, filter servers+ if mcp_servers:tools = []filtered_server_ids = set()- # Filter by server names if mcp_servers header is present- if mcp_servers:+ # 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 = Falsefor server_id in allowed_server_ids:server = global_mcp_server_manager.get_mcp_server_by_id(server_id)- if server and any(- normalize_server_name(server.name) == normalize_server_name(s)- for s in mcp_servers- ):- filtered_server_ids.add(server_id)-- # Filter by access groups if mcp_access_groups header is present- if mcp_access_groups:- # Get servers that match the access groups- access_group_server_ids = await MCPRequestHandler._get_mcp_servers_from_access_groups(- mcp_access_groups- )- # Only include servers that the user has access to- for server_id in access_group_server_ids:- if server_id in allowed_server_ids:+ 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}")# Get tools from filtered serversfor server_id in filtered_server_ids:@@ -329,7 +325,6 @@ if MCP_AVAILABLE:user_api_key_auth: Optional[UserAPIKeyAuth] = None,mcp_auth_header: Optional[str] = None,mcp_servers: Optional[List[str]] = None,- mcp_access_groups: Optional[List[str]] = None,) -> List[MCPTool]:"""List all available tools@@ -337,8 +332,7 @@ if MCP_AVAILABLE:Args:user_api_key_auth: User authentication info for access controlmcp_auth_header: Optional auth header for MCP server- mcp_servers: Optional list of server names to filter by- mcp_access_groups: Optional list of access group names to filter by+ mcp_servers: Optional list of server names and access groups to filter by"""tools = []for tool in global_mcp_tool_registry.list_tools():@@ -358,7 +352,6 @@ if MCP_AVAILABLE:user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,- mcp_access_groups=mcp_access_groups,)verbose_logger.debug("TOOLS FROM MCP SERVERS: %s", tools_from_mcp_servers)@@ -502,17 +495,15 @@ if MCP_AVAILABLE:"""Handle MCP requests through StreamableHTTP."""try:# Validate headers and log request info- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_access_groups = (+ user_api_key_auth, mcp_auth_header, mcp_servers = (await MCPRequestHandler.process_mcp_request(scope))verbose_logger.debug(f"MCP request headers - mcp_servers: {mcp_servers}")- verbose_logger.debug(f"MCP request headers - mcp_access_groups: {mcp_access_groups}")# Set the auth context variable for easy access in MCP functionsset_auth_context(user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,- mcp_access_groups=mcp_access_groups,)# Ensure session managers are initialized@@ -530,17 +521,15 @@ if MCP_AVAILABLE:"""Handle MCP requests through SSE."""try:# Validate headers and log request info- user_api_key_auth, mcp_auth_header, mcp_servers, mcp_access_groups = (+ user_api_key_auth, mcp_auth_header, mcp_servers = (await MCPRequestHandler.process_mcp_request(scope))verbose_logger.debug(f"MCP request headers - mcp_servers: {mcp_servers}")- verbose_logger.debug(f"MCP request headers - mcp_access_groups: {mcp_access_groups}")# Set the auth context variable for easy access in MCP functionsset_auth_context(user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,- mcp_access_groups=mcp_access_groups,)# Ensure session managers are initialized@@ -585,7 +574,6 @@ if MCP_AVAILABLE:user_api_key_auth: UserAPIKeyAuth,mcp_auth_header: Optional[str] = None,mcp_servers: Optional[List[str]] = None,- mcp_access_groups: Optional[List[str]] = None,) -> None:"""Set the UserAPIKeyAuth in the auth context variable.@@ -593,25 +581,23 @@ if MCP_AVAILABLE:Args:user_api_key_auth: UserAPIKeyAuth objectmcp_auth_header: MCP auth header to be passed to the MCP server- mcp_servers: Optional list of server names to filter by- mcp_access_groups: Optional list of access group names to filter by+ mcp_servers: Optional list of server names and access groups to filter by"""auth_user = MCPAuthenticatedUser(user_api_key_auth=user_api_key_auth,mcp_auth_header=mcp_auth_header,mcp_servers=mcp_servers,- mcp_access_groups=mcp_access_groups,)auth_context_var.set(auth_user)def get_auth_context() -> (- Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[List[str]]]+ Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]]]):"""Get the UserAPIKeyAuth from the auth context variable.Returns:- Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]], Optional[List[str]]]: UserAPIKeyAuth object, MCP auth header, MCP servers, and MCP access groups+ Tuple[Optional[UserAPIKeyAuth], Optional[str], Optional[List[str]]]: UserAPIKeyAuth object, MCP auth header, and MCP servers (can include access groups)"""auth_user = auth_context_var.get()if auth_user and isinstance(auth_user, MCPAuthenticatedUser):@@ -619,9 +605,8 @@ if MCP_AVAILABLE:auth_user.user_api_key_auth,auth_user.mcp_auth_header,auth_user.mcp_servers,- auth_user.mcp_access_groups,)- return None, None, None, None+ return 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.pyindex b4e4c4912d6..6021c9c88fe 100644--- a/tests/mcp_tests/test_mcp_server.py+++ b/tests/mcp_tests/test_mcp_server.py@@ -697,7 +697,6 @@ async def test_get_tools_from_mcp_servers():user_api_key_auth=mock_user_auth,mcp_auth_header=mock_auth_header,mcp_servers=["server1"],- mcp_access_groups=None)assert len(result) == 1, "Should only return tools from server1"assert result[0].name == "tool1", "Should return tool from server1"@@ -710,7 +709,6 @@ async def test_get_tools_from_mcp_servers():user_api_key_auth=mock_user_auth,mcp_auth_header=mock_auth_header,mcp_servers=None,- mcp_access_groups=None)assert len(result) == 2, "Should return tools from all servers"assert result[0].name == "tool1" and result[1].name == "tool2", "Should return tools from all servers"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.pyindex 943ad06ec43..05e2b4142c7 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@@ -12,12 +12,13 @@ sys.path.insert(0, os.path.abspath("../../../..")) # Adds the parent directory to the system path+from starlette.datastructures import Headers+from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (MCPRequestHandler,)from litellm.proxy._types import SpecialHeaders, UserAPIKeyAuthfrom litellm.proxy.auth.user_api_key_auth import user_api_key_auth-from starlette.datastructures import Headers@pytest.mark.asyncio@@ -199,16 +200,15 @@ class TestMCPRequestHandler:side_effect=mock_user_api_key_auth,) as mock_auth:# Call the method- auth_result, mcp_auth_header, mcp_servers, mcp_access_groups = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers = await MCPRequestHandler.process_mcp_request(scope)# Assert the resultsassert auth_result.api_key == expected_api_keyassert 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- # For these tests, mcp_servers and mcp_access_groups should be None+ # For these tests, mcp_servers should be Noneassert mcp_servers is None- assert mcp_access_groups is None@pytest.mark.parametrize("headers,expected_result",@@ -367,12 +367,10 @@ class TestMCPRequestHandler:mock_user_api_key_auth.return_value = mock_auth_result# Call the method- auth_result, mcp_auth_header, mcp_servers_result, mcp_access_groups_result = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers_result = await MCPRequestHandler.process_mcp_request(scope)assert auth_result == mock_auth_resultassert mcp_auth_header == expected_result["mcp_auth"]assert mcp_servers_result == expected_result["mcp_servers"]- # For these tests, access groups should be None- assert mcp_access_groups_result is Noneclass TestMCPCustomHeaderName:@@ -535,57 +533,87 @@ class TestMCPCustomHeaderName:mock_user_api_key_auth.return_value = mock_auth_result# Call the method- auth_result, mcp_auth_header, mcp_servers, mcp_access_groups = await MCPRequestHandler.process_mcp_request(scope)+ auth_result, mcp_auth_header, mcp_servers = await MCPRequestHandler.process_mcp_request(scope)# Assert the resultsassert auth_result == mock_auth_resultassert mcp_auth_header == custom_auth_tokenassert mcp_servers is None- assert mcp_access_groups is None# Verify user_api_key_auth was called with correct API keymock_user_api_key_auth.assert_called_once()call_args = mock_user_api_key_auth.call_argsassert call_args.kwargs["api_key"] == api_key- "headers,expected_access_groups",- [- ([(b"x-mcp-access-groups", b"group1,group2")], ["group1", "group2"]),- ([(b"x-mcp-access-groups", b"group1 , group2 , group3")], ["group1", "group2", "group3"]),- ([(b"x-mcp-access-groups", b"")], []),- ([], None),- ([(b"other-header", b"value")], None),- ]-)-def test_get_mcp_access_groups_from_headers(headers, expected_access_groups):- scope = {- "type": "http",- "method": "POST",- "path": "/test",- "headers": headers,- }- extracted_headers = MCPRequestHandler._safe_get_headers_from_scope(scope)- result = MCPRequestHandler.get_mcp_access_groups_from_headers(extracted_headers)- assert result == expected_access_groups+class TestMCPAccessGroupsE2E:+ """Simple e2e tests for MCP access groups functionality"""- "headers,expected_access_groups",- [- ([(b"x-mcp-access-groups", b"group1,group2")], ["group1", "group2"]),- ([(b"x-mcp-access-groups", b"")], []),- ([], None),- ]-)-async def test_process_mcp_request_access_groups(headers, expected_access_groups):- scope = {- "type": "http",- "method": "POST",- "path": "/test",- "headers": headers,- }- with patch("litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.user_api_key_auth") as mock_auth:- mock_auth.return_value = UserAPIKeyAuth(api_key="test", user_id="u", team_id="t")- _, _, _, mcp_access_groups = await MCPRequestHandler.process_mcp_request(scope)- assert mcp_access_groups == expected_access_groups\ No newline at end of file+ @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"]+ }+ }+ )++ @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"""++ # Create ASGI scope with mixed servers and access groups+ scope = {+ "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+ ],+ }++ # Mock user authentication+ async def mock_user_api_key_auth(api_key, request):+ return UserAPIKeyAuth(+ token="test-token",+ 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+ assert auth_result.api_key == "test-api-key"+ assert mcp_servers == ["zapier-server", "dev-group"] # Should contain both server name and access groupdiff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_connect.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_connect.tsxindex ca02cad96f6..833d436dd62 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_connect.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_connect.tsx@@ -72,8 +72,9 @@ const FeatureCard: React.FC<FeatureCardProps> = ({};if (useServerHeader && serverName) {const formattedServerName = serverName.replace(/\s+/g, '_');- headers["x-mcp-servers"] = [formattedServerName];- headers["x-mcp-access-groups"] = [accessGroups.join(",")];+ // Include both server name and access groups in the same header+ const serverAndGroups = [formattedServerName, ...accessGroups].join(',');+ headers["x-mcp-servers"] = [serverAndGroups];}return headers;};@@ -97,26 +98,19 @@ const FeatureCard: React.FC<FeatureCardProps> = ({checked={useServerHeader}onChange={setUseServerHeader}/>- <Text className="text-sm">Segregate tools to just use a specific MCP Server e.g. {serverName} tools</Text>+ <Text className="text-sm">Limit tools to specific MCP servers or MCP groups by passing the <code>x-mcp-servers</code> header</Text></div>{useServerHeader && (<AlertclassName="mt-2"type="info"showIcon- message="MCP Server Header Format"+ message="Two Options"description={<div>- <p>Specify one or more MCP servers using a comma-separated list inside an array:</p>- <ul>- <li><strong>Single server:</strong> ["Server1"]</li>- <li><strong>Multiple servers:</strong> ["Server1,Server2,Server3"]</li>- </ul>- <p>Note: Server names with spaces will be automatically converted to use underscores.</p>- <div className="mt-2">- <b>New:</b> You can also restrict by access group(s) using the <code>x-mcp-access-groups</code> header:<br />- <code>"x-mcp-access-groups": ["{accessGroups.join(",")}"]</code>- </div>+ <p><strong>Option 1:</strong> Get a specific server: <code>["{serverName.replace(/\s+/g, '_')}"]</code></p>+ <p><strong>Option 2:</strong> Get a group of MCPs: <code>["dev-group"]</code></p>+ <p className="mt-2 text-sm text-gray-600">You can also mix both: <code>["Server1,dev-group"]</code></p></div>}/>@@ -180,7 +174,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []// Format server names (replace spaces with underscores)const formattedServers = serverHeaders[type].map(s => s.replace(/\s+/g, '_'));- // Use comma-separated format+ // Use comma-separated format (can include both servers and access groups)headers["x-mcp-servers"] = [formattedServers.join(',')];}@@ -300,8 +294,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []"require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": ["Zapier_MCP"],- "x-mcp-access-groups": ["dev"]+ "x-mcp-servers": ["Zapier_MCP,dev"]}}],@@ -389,8 +382,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []"require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": ["Zapier_MCP"],- "x-mcp-access-groups": ["dev"]+ "x-mcp-servers": ["Zapier_MCP,dev"]}}],@@ -453,8 +445,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []"server_url": "${proxyBaseUrl}/mcp","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": ["Zapier_MCP"],- "x-mcp-access-groups": ["dev"]+ "x-mcp-servers": ["Zapier_MCP,dev"]}}}