Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(proxy): allow safe MCP server discovery for virtual keys (#20421)

Seongho Baeeb39582547f6
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index ecefe772247..fedfa011fdd 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -420,6 +420,8 @@ class LiteLLMRoutes(enum.Enum):
"/mcp/tools",
"/mcp/tools/list",
"/mcp/tools/call",
+ # Read-only MCP discovery endpoint (virtual keys may be allowed here)
+ "/v1/mcp/server",
]
agent_routes = [
@@ -845,9 +847,9 @@ class GenerateRequestBase(LiteLLMPydanticObjectBase):
allowed_cache_controls: Optional[list] = []
config: Optional[dict] = {}
permissions: Optional[dict] = {}
- model_max_budget: Optional[
- dict
- ] = {} # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}
+ model_max_budget: Optional[dict] = (
+ {}
+ ) # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}
model_config = ConfigDict(protected_namespaces=())
model_rpm_limit: Optional[dict] = None
@@ -1396,12 +1398,12 @@ class NewCustomerRequest(BudgetNewRequest):
blocked: bool = False # allow/disallow requests for this end-user
budget_id: Optional[str] = None # give either a budget_id or max_budget
spend: Optional[float] = None
- allowed_model_region: Optional[
- AllowedModelRegion
- ] = None # require all user requests to use models in this specific region
- default_model: Optional[
- str
- ] = None # if no equivalent model in allowed region - default all requests to this model
+ allowed_model_region: Optional[AllowedModelRegion] = (
+ None # require all user requests to use models in this specific region
+ )
+ default_model: Optional[str] = (
+ None # if no equivalent model in allowed region - default all requests to this model
+ )
@model_validator(mode="before")
@classmethod
@@ -1423,12 +1425,12 @@ class UpdateCustomerRequest(LiteLLMPydanticObjectBase):
blocked: bool = False # allow/disallow requests for this end-user
max_budget: Optional[float] = None
budget_id: Optional[str] = None # give either a budget_id or max_budget
- allowed_model_region: Optional[
- AllowedModelRegion
- ] = None # require all user requests to use models in this specific region
- default_model: Optional[
- str
- ] = None # if no equivalent model in allowed region - default all requests to this model
+ allowed_model_region: Optional[AllowedModelRegion] = (
+ None # require all user requests to use models in this specific region
+ )
+ default_model: Optional[str] = (
+ None # if no equivalent model in allowed region - default all requests to this model
+ )
class DeleteCustomerRequest(LiteLLMPydanticObjectBase):
@@ -1516,15 +1518,15 @@ class NewTeamRequest(TeamBase):
] = None # raise an error if 'guaranteed_throughput' is set and we're overallocating tpm
model_tpm_limit: Optional[Dict[str, int]] = None
- team_member_budget: Optional[
- float
- ] = None # allow user to set a budget for all team members
- team_member_rpm_limit: Optional[
- int
- ] = None # allow user to set RPM limit for all team members
- team_member_tpm_limit: Optional[
- int
- ] = None # allow user to set TPM limit for all team members
+ team_member_budget: Optional[float] = (
+ None # allow user to set a budget for all team members
+ )
+ team_member_rpm_limit: Optional[int] = (
+ None # allow user to set RPM limit for all team members
+ )
+ team_member_tpm_limit: Optional[int] = (
+ None # allow user to set TPM limit for all team members
+ )
team_member_key_duration: Optional[str] = None # e.g. "1d", "1w", "1m"
allowed_vector_store_indexes: Optional[List[AllowedVectorStoreIndexItem]] = None
@@ -1615,9 +1617,9 @@ class BlockKeyRequest(LiteLLMPydanticObjectBase):
class AddTeamCallback(LiteLLMPydanticObjectBase):
callback_name: str
- callback_type: Optional[
- Literal["success", "failure", "success_and_failure"]
- ] = "success_and_failure"
+ callback_type: Optional[Literal["success", "failure", "success_and_failure"]] = (
+ "success_and_failure"
+ )
callback_vars: Dict[str, str]
@model_validator(mode="before")
@@ -1945,9 +1947,9 @@ class ConfigList(LiteLLMPydanticObjectBase):
stored_in_db: Optional[bool]
field_default_value: Any
premium_field: bool = False
- nested_fields: Optional[
- List[FieldDetail]
- ] = None # For nested dictionary or Pydantic fields
+ nested_fields: Optional[List[FieldDetail]] = (
+ None # For nested dictionary or Pydantic fields
+ )
class UserHeaderMapping(LiteLLMPydanticObjectBase):
@@ -2386,9 +2388,9 @@ class LiteLLM_OrganizationMembershipTable(LiteLLMPydanticObjectBase):
budget_id: Optional[str] = None
created_at: datetime
updated_at: datetime
- user: Optional[
- Any
- ] = None # You might want to replace 'Any' with a more specific type if available
+ user: Optional[Any] = (
+ None # You might want to replace 'Any' with a more specific type if available
+ )
litellm_budget_table: Optional[LiteLLM_BudgetTable] = None
model_config = ConfigDict(protected_namespaces=())
@@ -3364,9 +3366,9 @@ class TeamModelDeleteRequest(BaseModel):
# Organization Member Requests
class OrganizationMemberAddRequest(OrgMemberAddRequest):
organization_id: str
- max_budget_in_organization: Optional[
- float
- ] = None # Users max budget within the organization
+ max_budget_in_organization: Optional[float] = (
+ None # Users max budget within the organization
+ )
class OrganizationMemberDeleteRequest(MemberDeleteRequest):
@@ -3584,9 +3586,9 @@ class ProviderBudgetResponse(LiteLLMPydanticObjectBase):
Maps provider names to their budget configs.
"""
- providers: Dict[
- str, ProviderBudgetResponseObject
- ] = {} # Dictionary mapping provider names to their budget configurations
+ providers: Dict[str, ProviderBudgetResponseObject] = (
+ {}
+ ) # Dictionary mapping provider names to their budget configurations
class ProxyStateVariables(TypedDict):
@@ -3729,9 +3731,9 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):
enforce_rbac: bool = False
roles_jwt_field: Optional[str] = None # v2 on role mappings
role_mappings: Optional[List[RoleMapping]] = None
- object_id_jwt_field: Optional[
- str
- ] = None # can be either user / team, inferred from the role mapping
+ object_id_jwt_field: Optional[str] = (
+ None # can be either user / team, inferred from the role mapping
+ )
scope_mappings: Optional[List[ScopeMapping]] = None
enforce_scope_based_access: bool = False
enforce_team_based_model_access: bool = False
diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
index 90c2f7fdf62..597521ae773 100644
--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
@@ -262,6 +262,67 @@ if MCP_AVAILABLE:
) -> List[LiteLLM_MCPServerTable]:
return [_redact_mcp_credentials(server) for server in mcp_servers]
+ def _is_restricted_virtual_key_request(user_api_key_dict: UserAPIKeyAuth) -> bool:
+ """Best-effort detection for route-restricted virtual keys.
+
+ We treat a requestor as a "restricted" virtual key if `allowed_routes`
+ is a non-empty list. This matches the auth gate that blocks routes with
+ the error: "Virtual key is not allowed to call this route...".
+ """
+
+ allowed_routes = getattr(user_api_key_dict, "allowed_routes", None)
+ return isinstance(allowed_routes, list) and len(allowed_routes) > 0
+
+ def _sanitize_mcp_server_for_virtual_key(
+ mcp_server: LiteLLM_MCPServerTable,
+ ) -> LiteLLM_MCPServerTable:
+ """Return a minimally sufficient MCP server view for virtual keys.
+
+ Security model:
+ - Virtual keys should be able to *discover* accessible servers.
+ - They should NOT receive sensitive configuration details like upstream
+ URLs, env vars, headers, commands/args, access-group names, or
+ credentials.
+ """
+
+ sanitized = _redact_mcp_credentials(mcp_server)
+
+ # Remove potentially sensitive config + identity fields.
+ sanitized.url = None
+ sanitized.static_headers = None
+ sanitized.env = {}
+ sanitized.command = None
+ sanitized.args = []
+ sanitized.extra_headers = []
+ sanitized.allowed_tools = []
+ sanitized.mcp_access_groups = []
+ sanitized.teams = []
+
+ sanitized.authorization_url = None
+ sanitized.token_url = None
+ sanitized.registration_url = None
+
+ sanitized.health_check_error = None
+ sanitized.last_health_check = None
+
+ sanitized.created_by = None
+ sanitized.updated_by = None
+ sanitized.created_at = None
+ sanitized.updated_at = None
+
+ # `mcp_info` is arbitrary metadata; keep only an explicit safe subset.
+ is_public = False
+ if isinstance(sanitized.mcp_info, dict):
+ is_public = bool(sanitized.mcp_info.get("is_public"))
+ sanitized.mcp_info = {"is_public": True} if is_public else None
+
+ return sanitized
+
+ def _sanitize_mcp_server_list_for_virtual_key(
+ mcp_servers: Iterable[LiteLLM_MCPServerTable],
+ ) -> List[LiteLLM_MCPServerTable]:
+ return [_sanitize_mcp_server_for_virtual_key(server) for server in mcp_servers]
+
def _inherit_credentials_from_existing_server(
payload: NewMCPServerRequest,
) -> NewMCPServerRequest:
@@ -504,8 +565,11 @@ if MCP_AVAILABLE:
"""
user_mcp_management_mode = _get_user_mcp_management_mode()
+ is_restricted_virtual_key = _is_restricted_virtual_key_request(
+ user_api_key_dict
+ )
- if user_mcp_management_mode == "view_all":
+ if user_mcp_management_mode == "view_all" and not is_restricted_virtual_key:
servers = await global_mcp_server_manager.get_all_mcp_servers_unfiltered()
redacted_mcp_servers = _redact_mcp_credentials_list(servers)
else:
@@ -531,6 +595,11 @@ if MCP_AVAILABLE:
if server.mcp_info is None:
server.mcp_info = {}
server.mcp_info["is_public"] = True
+
+ # Virtual keys only get a sanitized discovery view.
+ if is_restricted_virtual_key:
+ return _sanitize_mcp_server_list_for_virtual_key(redacted_mcp_servers)
+
return redacted_mcp_servers
@router.get(
@@ -625,6 +694,34 @@ if MCP_AVAILABLE:
detail={"error": f"MCP Server with id {server_id} not found"},
)
+ # Implement authz restriction from requested user
+ is_admin_view = _user_has_admin_view(user_api_key_dict)
+ is_restricted_virtual_key = _is_restricted_virtual_key_request(
+ user_api_key_dict
+ )
+
+ if not is_admin_view:
+ # Perform authz check BEFORE any health check (avoid side-effects for
+ # unauthorized callers).
+ mcp_server_records = await get_all_mcp_servers_for_user(
+ prisma_client, user_api_key_dict
+ )
+ exists = does_mcp_server_exist(mcp_server_records, server_id)
+
+ if not exists:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail={
+ "error": (
+ f"User does not have permission to view mcp server with id {server_id}. "
+ "You can only view mcp servers that you have access to."
+ )
+ },
+ )
+
+ # At this point caller is authorized to view the server.
+ await global_mcp_server_manager.add_server(mcp_server)
+
# Perform health check on the server using server manager
try:
health_result = await global_mcp_server_manager.health_check_server(
@@ -644,26 +741,10 @@ if MCP_AVAILABLE:
mcp_server.last_health_check = datetime.now()
mcp_server.health_check_error = str(e)
- # Implement authz restriction from requested user
- if _user_has_admin_view(user_api_key_dict):
- return _redact_mcp_credentials(mcp_server)
-
- # Perform authz check to filter the mcp servers user has access to
- mcp_server_records = await get_all_mcp_servers_for_user(
- prisma_client, user_api_key_dict
- )
- exists = does_mcp_server_exist(mcp_server_records, server_id)
-
- if exists:
- await global_mcp_server_manager.add_server(mcp_server)
- return _redact_mcp_credentials(mcp_server)
- else:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail={
- "error": f"User does not have permission to view mcp server with id {server_id}. You can only view mcp servers that you have access to."
- },
- )
+ redacted = _redact_mcp_credentials(mcp_server)
+ if is_restricted_virtual_key:
+ return _sanitize_mcp_server_for_virtual_key(redacted)
+ return redacted
@router.post(
"/server",
diff --git a/tests/test_litellm/proxy/auth/test_route_checks.py b/tests/test_litellm/proxy/auth/test_route_checks.py
index a745ac3de13..65bb329e7ea 100644
--- a/tests/test_litellm/proxy/auth/test_route_checks.py
+++ b/tests/test_litellm/proxy/auth/test_route_checks.py
@@ -108,6 +108,22 @@ def test_virtual_key_allowed_routes_with_litellm_routes_member_name_allowed():
assert result is True
+def test_virtual_key_mcp_routes_allows_v1_mcp_server():
+ """Regression test for #20325: allow virtual keys to list MCP servers."""
+
+ valid_token = UserAPIKeyAuth(
+ user_id="test_user",
+ allowed_routes=["mcp_routes"],
+ )
+
+ result = RouteChecks.is_virtual_key_allowed_to_call_route(
+ route="/v1/mcp/server",
+ valid_token=valid_token,
+ )
+
+ assert result is True
+
+
def test_virtual_key_allowed_routes_with_litellm_routes_member_name_denied():
"""Test that virtual key is denied when route is not in the allowed LiteLLMRoutes group"""
@@ -199,14 +215,14 @@ def test_virtual_key_llm_api_routes_allows_google_routes(route):
def test_google_routes_with_dynamic_model_names_recognized_as_llm_api_route(route):
"""
Test that Google routes with dynamic model names (including custom names) are recognized as LLM API routes.
-
+
This test verifies the fix for the issue where routes like:
/v1beta/models/google-gemini-2-5-pro-code-reviewer-k8s:generateContent
were incorrectly classified as "custom admin only route" instead of LLM API routes.
-
+
The fix adds pattern matching for Google routes with placeholders like {model_name}.
"""
-
+
# Test that the route is recognized as an LLM API route
assert RouteChecks.is_llm_api_route(route) is True
@@ -214,28 +230,28 @@ def test_google_routes_with_dynamic_model_names_recognized_as_llm_api_route(rout
def test_google_routes_with_dynamic_model_names_accessible_to_internal_users():
"""
Test that internal users can access Google routes with dynamic model names.
-
+
This ensures that routes like /v1beta/models/{model_name}:generateContent
are properly accessible to internal users and not blocked as admin-only routes.
"""
-
+
# Create an internal user object
user_obj = LiteLLM_UserTable(
user_id="test_user",
user_email="[email protected]",
user_role=LitellmUserRoles.INTERNAL_USER.value,
)
-
+
# Create an internal user API key auth
valid_token = UserAPIKeyAuth(
user_id="test_user",
user_role=LitellmUserRoles.INTERNAL_USER.value,
)
-
+
# Create a mock request
request = MagicMock(spec=Request)
request.query_params = {}
-
+
# Test that calling Google route with dynamic model name does NOT raise an exception
try:
RouteChecks.non_proxy_admin_allowed_routes_check(
@@ -263,11 +279,13 @@ def test_virtual_key_allowed_routes_with_multiple_litellm_routes_member_names():
# Test that routes from both groups are allowed
result1 = RouteChecks.is_virtual_key_allowed_to_call_route(
- route="/chat/completions", valid_token=valid_token # This is in openai_routes
+ route="/chat/completions",
+ valid_token=valid_token, # This is in openai_routes
)
result2 = RouteChecks.is_virtual_key_allowed_to_call_route(
- route="/user/info", valid_token=valid_token # This is in info_routes
+ route="/user/info",
+ valid_token=valid_token, # This is in info_routes
)
assert result1 is True
@@ -288,11 +306,13 @@ def test_virtual_key_allowed_routes_with_mixed_member_names_and_explicit_routes(
# Test that both info routes and explicit custom route are allowed
result1 = RouteChecks.is_virtual_key_allowed_to_call_route(
- route="/user/info", valid_token=valid_token # This is in info_routes
+ route="/user/info",
+ valid_token=valid_token, # This is in info_routes
)
result2 = RouteChecks.is_virtual_key_allowed_to_call_route(
- route="/custom/route", valid_token=valid_token # This is explicitly listed
+ route="/custom/route",
+ valid_token=valid_token, # This is explicitly listed
)
assert result1 is True
@@ -323,7 +343,8 @@ def test_virtual_key_allowed_routes_with_no_member_names_only_explicit():
# Test that non-allowed route raises HTTPException
with pytest.raises(HTTPException) as exc_info:
RouteChecks.is_virtual_key_allowed_to_call_route(
- route="/user/info", valid_token=valid_token # Not in allowed routes
+ route="/user/info",
+ valid_token=valid_token, # Not in allowed routes
)
assert exc_info.value.status_code == 403
@@ -372,12 +393,15 @@ def test_virtual_key_llm_api_routes_allows_registered_pass_through_endpoints():
},
}
- with patch(
- "litellm.proxy.pass_through_endpoints.pass_through_endpoints._registered_pass_through_routes",
- mock_registered_routes,
- ), patch(
- "litellm.proxy.pass_through_endpoints.pass_through_endpoints.get_server_root_path",
- return_value="/",
+ with (
+ patch(
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints._registered_pass_through_routes",
+ mock_registered_routes,
+ ),
+ patch(
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints.get_server_root_path",
+ return_value="/",
+ ),
):
# Create a virtual key with llm_api_routes permission
valid_token = UserAPIKeyAuth(
@@ -421,12 +445,15 @@ def test_virtual_key_without_llm_api_routes_cannot_access_pass_through():
},
}
- with patch(
- "litellm.proxy.pass_through_endpoints.pass_through_endpoints._registered_pass_through_routes",
- mock_registered_routes,
- ), patch(
- "litellm.proxy.pass_through_endpoints.pass_through_endpoints.get_server_root_path",
- return_value="/",
+ with (
+ patch(
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints._registered_pass_through_routes",
+ mock_registered_routes,
+ ),
+ patch(
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints.get_server_root_path",
+ return_value="/",
+ ),
):
# Create a virtual key without llm_api_routes permission
valid_token = UserAPIKeyAuth(
@@ -442,7 +469,9 @@ def test_virtual_key_without_llm_api_routes_cannot_access_pass_through():
)
assert exc_info.value.status_code == 403
- assert "Virtual key is not allowed to call this route" in str(exc_info.value.detail)
+ assert "Virtual key is not allowed to call this route" in str(
+ exc_info.value.detail
+ )
def test_check_passthrough_route_access_key_metadata_exact_match():
@@ -833,6 +862,7 @@ def test_videos_route_with_virtual_key_llm_api_routes():
result is True
), f"Virtual key with llm_api_routes should be able to access {route}"
+
def test_non_proxy_admin_wildcard_allowed_routes():
"""Test that nonproxy admin users can still use wildcard routes"""
@@ -847,7 +877,7 @@ def test_non_proxy_admin_wildcard_allowed_routes():
user_role=LitellmUserRoles.INTERNAL_USER.value,
allowed_routes=["/scim/*"],
)
-
+
request = MagicMock(spec=Request)
request.query_params = {}
@@ -864,14 +894,14 @@ def test_non_proxy_admin_wildcard_allowed_routes():
def test_proxy_admin_viewer_can_access_global_spend_tags():
"""
Test that proxy_admin_viewer can access /global/spend/tags endpoint.
-
+
This test verifies the fix for the issue where proxy_admin_viewer was getting
403 errors when trying to access /global/spend/tags endpoint.
-
+
Related: Slack thread from 10/9/2025 - Erik Kristensen reported this issue.
proxy_admin_viewer role should have access to "view all spend" endpoints.
"""
-
+
# Create a proxy admin viewer user object
user_obj = LiteLLM_UserTable(
user_id="viewer_user",
@@ -912,8 +942,12 @@ def test_route_in_additional_public_routes_wildcard_match():
"""
from litellm.proxy.auth.auth_utils import route_in_additonal_public_routes
- with patch("litellm.proxy.proxy_server.general_settings", {"public_routes": ["/api/*"]}), \
- patch("litellm.proxy.proxy_server.premium_user", True):
+ with (
+ patch(
+ "litellm.proxy.proxy_server.general_settings", {"public_routes": ["/api/*"]}
+ ),
+ patch("litellm.proxy.proxy_server.premium_user", True),
+ ):
# Wildcard should match subpaths
assert route_in_additonal_public_routes("/api/users") is True
assert route_in_additonal_public_routes("/api/users/123") is True
@@ -927,11 +961,15 @@ def test_route_in_additional_public_routes_exact_match():
"""
from litellm.proxy.auth.auth_utils import route_in_additonal_public_routes
- with patch("litellm.proxy.proxy_server.general_settings", {"public_routes": ["/health", "/status"]}), \
- patch("litellm.proxy.proxy_server.premium_user", True):
+ with (
+ patch(
+ "litellm.proxy.proxy_server.general_settings",
+ {"public_routes": ["/health", "/status"]},
+ ),
+ patch("litellm.proxy.proxy_server.premium_user", True),
+ ):
# Exact matches should work
assert route_in_additonal_public_routes("/health") is True
assert route_in_additonal_public_routes("/status") is True
# Non-matching routes should fail
assert route_in_additonal_public_routes("/other") is False
-
diff --git a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
index 83914e30354..b4c8d5f07cc 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
@@ -1,4 +1,3 @@
-import json
import os
import sys
import types
@@ -204,25 +203,28 @@ class TestListMCPServers:
transport="http",
),
]
- mock_manager.get_all_allowed_mcp_servers = AsyncMock(
- return_value=mock_servers
- )
+ mock_manager.get_all_allowed_mcp_servers = AsyncMock(return_value=mock_servers)
for idx, server in enumerate(mock_servers):
server.credentials = {"auth_value": f"secret_{idx}"}
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
- return_value=True,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
- return_value=mock_prisma_client,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
- AsyncMock(return_value=[mock_user_auth]),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
+ return_value=True,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma_client,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
@@ -269,12 +271,73 @@ class TestListMCPServers:
return_value=mock_servers
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._get_user_mcp_management_mode",
- return_value="view_all",
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_user_mcp_management_mode",
+ return_value="view_all",
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ ):
+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (
+ fetch_all_mcp_servers,
+ )
+
+ result = await fetch_all_mcp_servers(user_api_key_dict=mock_user_auth)
+
+ assert len(result) == 2
+ assert {server.server_id for server in result} == {"server-1", "server-2"}
+
+ @pytest.mark.asyncio
+ async def test_list_mcp_servers_view_all_mode_virtual_key_is_sanitized(self):
+ """Issue #20325: virtual keys should get a safe discovery view."""
+
+ mock_user_auth = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ user_id="test_user_id",
+ api_key="test_api_key",
+ allowed_routes=["mcp_routes"],
+ )
+
+ mock_servers = [
+ generate_mock_mcp_server_db_record(server_id="server-1", alias="One"),
+ generate_mock_mcp_server_db_record(server_id="server-2", alias="Two"),
+ ]
+ for idx, server in enumerate(mock_servers):
+ server.credentials = {"auth_value": f"secret_{idx}"}
+ server.env = {"API_KEY": "super-secret"}
+ server.static_headers = {"Authorization": "Bearer super-secret"}
+ server.mcp_access_groups = ["group-a"]
+ server.teams = [{"team_id": "team-1", "team_alias": "Team 1"}]
+ server.command = "bash"
+ server.args = ["-lc", "echo hi"]
+ server.extra_headers = ["Authorization"]
+
+ mock_manager = MagicMock()
+ mock_manager.get_all_mcp_servers_unfiltered = AsyncMock(
+ return_value=mock_servers
+ )
+ mock_manager.get_all_allowed_mcp_servers = AsyncMock(return_value=mock_servers)
+
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_user_mcp_management_mode",
+ return_value="view_all",
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_all_mcp_servers,
@@ -282,9 +345,24 @@ class TestListMCPServers:
result = await fetch_all_mcp_servers(user_api_key_dict=mock_user_auth)
+ # Ensure we did not bypass filtering via view_all for restricted virtual keys.
+ mock_manager.get_all_mcp_servers_unfiltered.assert_not_called()
+
assert len(result) == 2
assert {server.server_id for server in result} == {"server-1", "server-2"}
+ for server in result:
+ assert server.credentials is None
+ assert server.url is None
+ assert server.static_headers is None
+ assert server.env == {}
+ assert server.command is None
+ assert server.args == []
+ assert server.extra_headers == []
+ assert server.allowed_tools == []
+ assert server.mcp_access_groups == []
+ assert server.teams == []
+
@pytest.mark.asyncio
async def test_list_mcp_servers_combined_config_and_db(self):
"""
@@ -374,25 +452,28 @@ class TestListMCPServers:
transport="http",
),
]
- mock_manager.get_all_allowed_mcp_servers = AsyncMock(
- return_value=mock_servers
- )
+ mock_manager.get_all_allowed_mcp_servers = AsyncMock(return_value=mock_servers)
for idx, server in enumerate(mock_servers):
server.credentials = {"auth_value": f"secret_{idx}"}
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
- return_value=True,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
- return_value=mock_prisma_client,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
- AsyncMock(return_value=[mock_user_auth]),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
+ return_value=True,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma_client,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
@@ -494,25 +575,28 @@ class TestListMCPServers:
url="https://actions.zapier.com/mcp/sse",
),
]
- mock_manager.get_all_allowed_mcp_servers = AsyncMock(
- return_value=mock_servers
- )
+ mock_manager.get_all_allowed_mcp_servers = AsyncMock(return_value=mock_servers)
for idx, server in enumerate(mock_servers):
server.credentials = {"auth_value": f"secret_{idx}"}
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
- return_value=False,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
- return_value=mock_prisma_client,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
- AsyncMock(return_value=[mock_user_auth]),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
+ return_value=False,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma_client,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
@@ -540,7 +624,6 @@ class TestListMCPServers:
assert server.alias == "Allowed Zapier MCP"
assert server.url == "https://actions.zapier.com/mcp/sse"
-
@pytest.mark.asyncio
async def test_fetch_single_mcp_server_redacts_credentials(self):
mock_server = generate_mock_mcp_server_db_record(
@@ -562,18 +645,23 @@ class TestListMCPServers:
user_role=LitellmUserRoles.PROXY_ADMIN
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
- return_value=mock_prisma_client,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
- AsyncMock(return_value=mock_server),
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.health_check_server",
- AsyncMock(return_value=mock_health_result),
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
- return_value=True,
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma_client,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
+ AsyncMock(return_value=mock_server),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.health_check_server",
+ AsyncMock(return_value=mock_health_result),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
+ return_value=True,
+ ),
):
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_mcp_server,
@@ -610,18 +698,23 @@ class TestListMCPServers:
user_role=LitellmUserRoles.PROXY_ADMIN
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
- return_value=mock_prisma_client,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
- AsyncMock(return_value=mock_server),
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.health_check_server",
- AsyncMock(return_value=mock_health_result),
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
- return_value=True,
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma_client,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
+ AsyncMock(return_value=mock_server),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.health_check_server",
+ AsyncMock(return_value=mock_health_result),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._user_has_admin_view",
+ return_value=True,
+ ),
):
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
fetch_mcp_server,
@@ -763,16 +856,20 @@ class TestTemporaryMCPSessionEndpoints:
mock_manager.get_mcp_server_by_id.return_value = inherited_server
mock_manager.build_mcp_server_from_table = AsyncMock(return_value=built_server)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.validate_and_normalize_mcp_server_payload",
- MagicMock(),
- ) as validate_mock, patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._cache_temporary_mcp_server",
- MagicMock(),
- ) as cache_mock:
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.validate_and_normalize_mcp_server_payload",
+ MagicMock(),
+ ) as validate_mock,
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._cache_temporary_mcp_server",
+ MagicMock(),
+ ) as cache_mock,
+ ):
response = await add_session_mcp_server(
payload=payload,
user_api_key_dict=user_auth,
@@ -832,13 +929,16 @@ class TestTemporaryMCPSessionEndpoints:
server = generate_mock_mcp_server_config_record(server_id="server-1")
authorize_response = MagicMock()
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",
- return_value=server,
- ) as get_server, patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.authorize_with_server",
- AsyncMock(return_value=authorize_response),
- ) as authorize_mock:
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",
+ return_value=server,
+ ) as get_server,
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.authorize_with_server",
+ AsyncMock(return_value=authorize_response),
+ ) as authorize_mock,
+ ):
result = await mcp_authorize(
request=request,
server_id="server-1",
@@ -875,13 +975,16 @@ class TestTemporaryMCPSessionEndpoints:
server = generate_mock_mcp_server_config_record(server_id="server-1")
exchange_response = {"access_token": "token"}
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",
- return_value=server,
- ) as get_server, patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.exchange_token_with_server",
- AsyncMock(return_value=exchange_response),
- ) as exchange_mock:
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",
+ return_value=server,
+ ) as get_server,
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.exchange_token_with_server",
+ AsyncMock(return_value=exchange_response),
+ ) as exchange_mock,
+ ):
result = await mcp_token(
request=request,
server_id="server-1",
@@ -922,16 +1025,20 @@ class TestTemporaryMCPSessionEndpoints:
"token_endpoint_auth_method": "client_secret_basic",
}
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",
- return_value=server,
- ) as get_server, patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._read_request_body",
- AsyncMock(return_value=request_body),
- ) as read_body, patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.register_client_with_server",
- AsyncMock(return_value=register_response),
- ) as register_mock:
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_cached_temporary_mcp_server_or_404",
+ return_value=server,
+ ) as get_server,
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._read_request_body",
+ AsyncMock(return_value=request_body),
+ ) as read_body,
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.register_client_with_server",
+ AsyncMock(return_value=register_response),
+ ) as register_mock,
+ ):
result = await mcp_register(request=request, server_id="server-1")
assert result is register_response
@@ -947,6 +1054,7 @@ class TestTemporaryMCPSessionEndpoints:
fallback_client_id="server-1",
)
+
class TestUpdateMCPServer:
"""Test suite for update MCP server functionality"""
@@ -954,7 +1062,7 @@ class TestUpdateMCPServer:
async def test_update_mcp_server_respects_extra_headers(self):
"""
Test that updating an MCP server with extra_headers properly saves the field.
-
+
This test ensures that extra_headers field in UpdateMCPServerRequest
is properly handled and persisted when updating an MCP server.
"""
@@ -999,21 +1107,27 @@ class TestUpdateMCPServer:
)
# Mock the update_mcp_server function to capture the call
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
- return_value=mock_prisma_client,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.validate_and_normalize_mcp_server_payload",
- MagicMock(),
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.update_mcp_server",
- AsyncMock(return_value=updated_server),
- ) as update_mock, patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.add_server",
- AsyncMock(),
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.reload_servers_from_database",
- AsyncMock(),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma_client,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.validate_and_normalize_mcp_server_payload",
+ MagicMock(),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.update_mcp_server",
+ AsyncMock(return_value=updated_server),
+ ) as update_mock,
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.add_server",
+ AsyncMock(),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager.reload_servers_from_database",
+ AsyncMock(),
+ ),
):
# Import and call the function
from litellm.proxy.management_endpoints.mcp_management_endpoints import (
@@ -1030,7 +1144,10 @@ class TestUpdateMCPServer:
# First arg is prisma_client, second is the payload (UpdateMCPServerRequest)
called_payload = call_args[0][1]
assert called_payload.server_id == "test-server-1"
- assert called_payload.extra_headers == ["X-Custom-Header", "X-Another-Header"]
+ assert called_payload.extra_headers == [
+ "X-Custom-Header",
+ "X-Another-Header",
+ ]
assert called_payload.alias == "Updated Test Server"
# Verify the result includes extra_headers
@@ -1081,12 +1198,15 @@ class TestHealthCheckServers:
return_value=[mock_health_result_1, mock_health_result_2]
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
- AsyncMock(return_value=[mock_user_auth]),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
result = await health_check_servers(
server_ids=None,
@@ -1133,9 +1253,12 @@ class TestMCPRegistryEndpoint:
# The registry endpoint uses get_filtered_registry (filters by client IP)
mock_manager.get_filtered_registry.return_value = {mock_server.server_id: mock_server}
- with patch_proxy_general_settings({"enable_mcp_registry": True}), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
+ with (
+ patch_proxy_general_settings({"enable_mcp_registry": True}),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
):
response = client.get("/v1/mcp/registry.json")
@@ -1182,12 +1305,15 @@ class TestMCPRegistryEndpoint:
return_value=[mock_health_result]
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
- AsyncMock(return_value=[mock_user_auth]),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
result = await health_check_servers(
server_ids=["server-1"],
@@ -1245,12 +1371,15 @@ class TestManagementPayloadValidation:
return_value=[health_result_one, health_result_two]
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints._get_user_mcp_management_mode",
- return_value="view_all",
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints._get_user_mcp_management_mode",
+ return_value="view_all",
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
):
result = await health_check_servers(
server_ids=None,
@@ -1295,12 +1424,15 @@ class TestManagementPayloadValidation:
return_value=[mock_health_result] # Only server-1 is returned (accessible)
)
- with patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
- mock_manager,
- ), patch(
- "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
- AsyncMock(return_value=[mock_user_auth]),
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.global_mcp_server_manager",
+ mock_manager,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.build_effective_auth_contexts",
+ AsyncMock(return_value=[mock_user_auth]),
+ ),
):
result = await health_check_servers(
server_ids=["server-1", "server-unauthorized"],