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
feat(mcp): add mcp_tool_search virtual tools for large tool catalogs (#31777)
Krrish Dholakiacca71a07c20e
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260626120000_add_mcp_tool_search_enabled/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260626120000_add_mcp_tool_search_enabled/migration.sqlnew file mode 100644index 00000000000..542677426ba--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260626120000_add_mcp_tool_search_enabled/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "LiteLLM_ObjectPermissionTable" ADD COLUMN "mcp_tool_search_enabled" BOOLEAN;diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex e21c0016491..5351e0a1470 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -279,6 +279,7 @@ model LiteLLM_ObjectPermissionTable {blocked_tools String[] @default([]) // Tool names blocked for any key/team/user with this permissionmcp_toolsets String[] @default([]) // Toolset IDs granted to this key/team/usersearch_tools String[] @default([]) // search_tool_name values this key/team/user may call+ mcp_tool_search_enabled Boolean?teams LiteLLM_TeamTable[]projects LiteLLM_ProjectTable[]verification_tokens LiteLLM_VerificationToken[]diff --git a/litellm/models/object_permission.py b/litellm/models/object_permission.pyindex 6c0d100046c..3052a2af459 100644--- a/litellm/models/object_permission.py+++ b/litellm/models/object_permission.py@@ -24,3 +24,4 @@ class LiteLLM_ObjectPermissionTable(LiteLLMPydanticObjectBase):mcp_toolsets: Optional[List[str]] = Noneblocked_tools: Optional[List[str]] = []search_tools: Optional[List[str]] = []+ mcp_tool_search_enabled: Optional[bool] = Nonediff --git a/litellm/proxy/_experimental/mcp_server/AGENTS.md b/litellm/proxy/_experimental/mcp_server/AGENTS.mdindex 8eebc3ea3b3..6e1d121c3be 100644--- a/litellm/proxy/_experimental/mcp_server/AGENTS.md+++ b/litellm/proxy/_experimental/mcp_server/AGENTS.md@@ -41,6 +41,7 @@ litellm/proxy/_experimental/mcp_server/sampling_handler.py # MCP sampling to LiteLLM completion flowelicitation_handler.py # MCP elicitation relay flowsemantic_tool_filter.py # semantic filtering of available MCP tools+ tool_search.py # opt-in virtual tools (mcp_tool_search + mcp_tool_call) for large catalogsguardrail_translation/handler.py # MCP guardrail result translationsse_transport.py # SSE transport implementation@@ -79,6 +80,11 @@ module materially harder to understand.encryption need focused tests for both allowed and rejected paths.- Avoid adding comments to new code unless they explain non-obvious security orprotocol behavior. Prefer clear names and small functions.+- The virtual tool path (`tool_search.py`, gated by `mcp_tool_search_enabled`)+ must mirror the normal tool flow: IP filtering, server allowlist, per-key tool+ permissions, no-accessible-server rejection, per-request auth headers, server+ scope, error to `isError` conversion, and spend logging. Reuse `_list_mcp_tools`+ and `execute_mcp_tool` rather than reimplementing any of these checks.## Testsdiff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.pyindex d30d8af2af2..7ab7eb28147 100644--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py@@ -569,6 +569,21 @@ if MCP_AVAILABLE:include_disabled_tools and user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN)+ if apply_tool_filters and getattr(+ getattr(user_api_key_dict, "object_permission", None),+ "mcp_tool_search_enabled",+ False,+ ):+ from litellm.proxy._experimental.mcp_server.tool_search import (+ get_virtual_tool_definitions,+ )++ return {+ "tools": get_virtual_tool_definitions(),+ "error": None,+ "message": "Successfully retrieved tools",+ }+# Extract auth headers from requestheaders = request.headersraw_headers_from_request = dict(headers)@@ -727,6 +742,74 @@ if MCP_AVAILABLE:try:data = await request.json()+ tool_name = data.get("name")+ tool_arguments = data.get("arguments") or {}++ from litellm.proxy._experimental.mcp_server.tool_search import (+ MCP_TOOL_CALL_TOOL_NAME,+ MCP_TOOL_SEARCH_TOOL_NAME,+ coerce_top_k,+ handle_mcp_tool_call,+ handle_mcp_tool_search,+ )++ if tool_name in (MCP_TOOL_SEARCH_TOOL_NAME, MCP_TOOL_CALL_TOOL_NAME):+ if not getattr(+ getattr(user_api_key_dict, "object_permission", None),+ "mcp_tool_search_enabled",+ False,+ ):+ raise HTTPException(+ status_code=403,+ detail={+ "error": "forbidden",+ "message": f"{tool_name} requires mcp_tool_search_enabled on the key",+ },+ )+ rest_client_ip = IPAddressUtils.get_mcp_client_ip(request)+ (+ virtual_mcp_auth_header,+ virtual_mcp_server_auth_headers,+ virtual_raw_headers,+ ) = _extract_mcp_headers_from_request(request, MCPRequestHandler)+ virtual_oauth2_headers = MCPRequestHandler._get_oauth2_headers_from_headers(request.headers)+ if tool_name == MCP_TOOL_SEARCH_TOOL_NAME:+ return await handle_mcp_tool_search(+ query=tool_arguments.get("query", ""),+ top_k=coerce_top_k(tool_arguments.get("top_k", 5)),+ user_api_key_dict=user_api_key_dict,+ client_ip=rest_client_ip,+ mcp_auth_header=virtual_mcp_auth_header,+ mcp_server_auth_headers=virtual_mcp_server_auth_headers,+ oauth2_headers=virtual_oauth2_headers,+ raw_headers=virtual_raw_headers,+ )+ else: # MCP_TOOL_CALL_TOOL_NAME+ # Run the same pre-call pipeline as the normal call path so the+ # tool execution is spend-logged and guardrail-checked.+ (+ _,+ virtual_logging_obj,+ ) = await ProxyBaseLLMRequestProcessing(data=data).common_processing_pre_call_logic(+ request=request,+ user_api_key_dict=user_api_key_dict,+ proxy_config=proxy_config,+ route_type=CallTypes.call_mcp_tool.value,+ proxy_logging_obj=proxy_logging_obj,+ general_settings=general_settings,+ )+ return await handle_mcp_tool_call(+ tool_name=tool_arguments.get("tool_name", ""),+ arguments=tool_arguments.get("arguments") or {},+ user_api_key_dict=user_api_key_dict,+ client_ip=rest_client_ip,+ mcp_auth_header=virtual_mcp_auth_header,+ mcp_server_auth_headers=virtual_mcp_server_auth_headers,+ oauth2_headers=virtual_oauth2_headers,+ raw_headers=virtual_raw_headers,+ litellm_logging_obj=virtual_logging_obj,+ )+# Validate required parameters earlyserver_id = data.get("server_id")if not server_id:@@ -738,7 +821,6 @@ if MCP_AVAILABLE:},)- tool_name = data.get("name")if not tool_name:raise HTTPException(status_code=400,@@ -748,8 +830,6 @@ if MCP_AVAILABLE:},)- tool_arguments = data.get("arguments") or {}-proxy_base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data)(data,diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex 607e676524e..a65239b296f 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -10,8 +10,8 @@ import contextvarsimport hashlibimport jsonimport time-import typesimport traceback+import typesimport uuidfrom datetime import datetimefrom typing import (@@ -37,13 +37,17 @@ from starlette.types import Message, Receive, Scope, Sendfrom litellm._logging import verbose_loggerfrom litellm.constants import MAXIMUM_TRACEBACK_LINES_TO_LOGfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.custom_httpx.http_handler import (+ get_async_httpx_client,+ httpxSpecialProvider,+)from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (MCPRequestHandler,)-from litellm.proxy._experimental.mcp_server.exceptions import MCPUpstreamAuthErrorfrom litellm.proxy._experimental.mcp_server.discoverable_endpoints import (get_request_base_url,)+from litellm.proxy._experimental.mcp_server.exceptions import MCPUpstreamAuthErrorfrom litellm.proxy._experimental.mcp_server.mcp_context import (_mcp_active_toolset_id,_mcp_gateway_initialize_instructions,@@ -59,10 +63,6 @@ from litellm.proxy._experimental.mcp_server.utils import (get_server_prefix,iter_known_server_prefixes,)-from litellm.llms.custom_httpx.http_handler import (- get_async_httpx_client,- httpxSpecialProvider,-)from litellm.proxy._types import (ProxyException,SpecialMCPServerNames,@@ -122,9 +122,12 @@ def _write_byok_cred_cache(user_id: str, server_id: str, credential: Optional[st# TODO: Make this a util function for litellm client usageMCP_AVAILABLE: bool = Truetry:+ import weakref+from mcp import ReadResourceResult, Resourcefrom mcp.server import Serverfrom mcp.server.lowlevel.helper_types import ReadResourceContents+ from mcp.server.session import ServerSession as _McpServerSessionfrom mcp.types import (BlobResourceContents,GetPromptResult,@@ -132,8 +135,6 @@ try:TextResourceContents,Tool,)- from mcp.server.session import ServerSession as _McpServerSession- import weakref# Robust auth lookup keyed by session_object._session_obj_auth_storage: "weakref.WeakKeyDictionary[Any, MCPAuthenticatedUser]" = weakref.WeakKeyDictionary()@@ -303,14 +304,14 @@ def _proxy_exception_to_http_exception(exc: ProxyException) -> HTTPException:if MCP_AVAILABLE:from mcp.server import Server- from mcp.server.lowlevel.server import NotificationOptions- from mcp.server.models import InitializationOptions# Import auth context variables and middlewarefrom mcp.server.auth.middleware.auth_context import (AuthContextMiddleware,auth_context_var,)+ from mcp.server.lowlevel.server import NotificationOptions+ from mcp.server.models import InitializationOptionstry:from mcp.server.streamable_http_manager import StreamableHTTPSessionManager@@ -664,6 +665,19 @@ if MCP_AVAILABLE:verbose_logger.debug(f"MCP list_tools - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}")+ if getattr(+ getattr(user_api_key_auth, "object_permission", None),+ "mcp_tool_search_enabled",+ False,+ ):+ from mcp.types import Tool++ from litellm.proxy._experimental.mcp_server.tool_search import (+ get_virtual_tool_definitions,+ )++ return [Tool(**d) for d in get_virtual_tool_definitions()]+# Get mcp_servers from context variableverbose_logger.debug("MCP list_tools - Calling _list_mcp_tools")tools = await _list_mcp_tools(@@ -688,6 +702,150 @@ if MCP_AVAILABLE:if _session_reset_token is not None:active_mcp_session_var.reset(_session_reset_token)+ def _capture_host_progress_callback(host_server) -> Optional[Callable]:+ """Return a progress-forwarding callback bound to the host MCP session.++ Returns ``None`` when the host did not supply a progress token.+ """+ try:+ host_ctx = host_server.request_context+ except Exception as e:+ verbose_logger.warning(f"Could not capture host progress context: {e}")+ return None++ if not (host_ctx and hasattr(host_ctx, "meta") and host_ctx.meta):+ return None+ host_token = getattr(host_ctx.meta, "progressToken", None)+ if not (host_token and hasattr(host_ctx, "session") and host_ctx.session):+ return None+ host_session = host_ctx.session++ async def forward_progress(progress: float, total: Optional[float]):+ """Forward progress notifications from external MCP to Host"""+ try:+ await host_session.send_progress_notification(+ progress_token=host_token,+ progress=progress,+ total=total,+ )+ verbose_logger.debug(f"Forwarded progress {progress}/{total} to Host")+ except Exception as e:+ verbose_logger.error(f"Failed to forward progress to Host: {e}")++ verbose_logger.debug(f"Host progressToken captured: {host_token[:8]}...")+ return forward_progress++ async def _build_virtual_call_logging_obj(+ name: str,+ arguments: dict[str, Any],+ user_api_key_auth: UserAPIKeyAuth,+ ) -> Optional[LiteLLMLoggingObj]:+ """Run the pre-call pipeline (guardrails + logging setup) for a virtual+ mcp_tool_call so the SSE path spend-logs like the REST path."""+ from fastapi import Request++ from litellm.proxy.common_request_processing import (+ ProxyBaseLLMRequestProcessing,+ )+ from litellm.proxy.proxy_server import (+ general_settings,+ proxy_config,+ proxy_logging_obj,+ )++ request = Request(+ scope={+ "type": "http",+ "method": "POST",+ "path": "/mcp/tools/call",+ "headers": [(b"content-type", b"application/json")],+ }+ )+ _, virtual_logging_obj = await ProxyBaseLLMRequestProcessing(+ data={"name": name, "arguments": arguments}+ ).common_processing_pre_call_logic(+ request=request,+ user_api_key_dict=user_api_key_auth,+ proxy_config=proxy_config,+ route_type=CallTypes.call_mcp_tool.value,+ proxy_logging_obj=proxy_logging_obj,+ general_settings=general_settings,+ )+ return virtual_logging_obj++ async def _dispatch_virtual_mcp_tool(+ name: str,+ arguments: Optional[dict[str, Any]],+ user_api_key_auth: Optional[UserAPIKeyAuth],+ client_ip: Optional[str],+ mcp_servers: Optional[list[str]] = None,+ mcp_auth_header: Optional[str] = None,+ mcp_server_auth_headers: Optional[dict[str, dict[str, str]]] = None,+ oauth2_headers: Optional[dict[str, str]] = None,+ raw_headers: Optional[dict[str, str]] = None,+ ) -> Optional[CallToolResult]:+ """Handle the mcp_tool_search / mcp_tool_call virtual tools.++ Returns a CallToolResult when ``name`` is a virtual tool, else ``None`` so+ the caller falls through to normal tool routing.+ """+ from litellm.proxy._experimental.mcp_server.tool_search import (+ MCP_TOOL_CALL_TOOL_NAME,+ MCP_TOOL_SEARCH_TOOL_NAME,+ coerce_top_k,+ handle_mcp_tool_call,+ handle_mcp_tool_search,+ )++ if name not in (MCP_TOOL_SEARCH_TOOL_NAME, MCP_TOOL_CALL_TOOL_NAME):+ return None++ if not getattr(+ getattr(user_api_key_auth, "object_permission", None),+ "mcp_tool_search_enabled",+ False,+ ):+ return CallToolResult(+ content=[+ TextContent(+ type="text",+ text=f"Tool {name} requires mcp_tool_search_enabled on the key",+ )+ ],+ isError=True,+ )++ args = arguments or {}+ if name == MCP_TOOL_SEARCH_TOOL_NAME:+ return await handle_mcp_tool_search(+ query=args.get("query", ""),+ top_k=coerce_top_k(args.get("top_k", 5)),+ user_api_key_dict=user_api_key_auth,+ client_ip=client_ip,+ mcp_servers=mcp_servers,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ )++ assert user_api_key_auth is not None # guaranteed by the flag check above+ virtual_logging_obj = await _build_virtual_call_logging_obj(+ name=name, arguments=args, user_api_key_auth=user_api_key_auth+ )+ return await handle_mcp_tool_call(+ tool_name=args.get("tool_name", ""),+ arguments=args.get("arguments") or {},+ user_api_key_dict=user_api_key_auth,+ client_ip=client_ip,+ mcp_servers=mcp_servers,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ litellm_logging_obj=virtual_logging_obj,+ )+@server.call_tool()async def mcp_server_tool_call(name: str, arguments: Dict[str, Any] | None) -> CallToolResult:"""@@ -701,11 +859,12 @@ if MCP_AVAILABLE:HTTPException: If tool not found or arguments missing"""from fastapi import Request+ from mcp.server.lowlevel.server import request_ctx+ from mcp.types import CallToolResult+from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedExceptionfrom litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_requestfrom litellm.proxy.proxy_server import proxy_config- from mcp.types import CallToolResult- from mcp.server.lowlevel.server import request_ctxreq_ctx = request_ctx.get(None)_session_reset_token = None@@ -730,31 +889,25 @@ if MCP_AVAILABLE:)verbose_logger.debug(f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}")- host_progress_callback = None- try:- host_ctx = server.request_context- if host_ctx and hasattr(host_ctx, "meta") and host_ctx.meta:- host_token = getattr(host_ctx.meta, "progressToken", None)- if host_token and hasattr(host_ctx, "session") and host_ctx.session:- host_session = host_ctx.session-- async def forward_progress(progress: float, total: Optional[float]):- """Forward progress notifications from external MCP to Host"""- try:- await host_session.send_progress_notification(- progress_token=host_token,- progress=progress,- total=total,- )- verbose_logger.debug(f"Forwarded progress {progress}/{total} to Host")- except Exception as e:- verbose_logger.error(f"Failed to forward progress to Host: {e}")-- host_progress_callback = forward_progress- verbose_logger.debug(f"Host progressToken captured: {host_token[:8]}...")- except Exception as e:- verbose_logger.warning(f"Could not capture host progress context: {e}")+try:+ # Inside this try so virtual-tool errors convert to isError+ # CallToolResult instead of raising out of the protocol handler.+ virtual_tool_result = await _dispatch_virtual_mcp_tool(+ name=name,+ arguments=arguments,+ user_api_key_auth=user_api_key_auth,+ client_ip=_client_ip,+ mcp_servers=mcp_servers,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ )+ if virtual_tool_result is not None:+ return virtual_tool_result++ host_progress_callback = _capture_host_progress_callback(server)# Create a body date for loggingbody_data = {"name": name, "arguments": arguments}# Set trace/session id from raw_headers so spend logs and logging_obj stay consistent (same as A2A)@@ -1528,6 +1681,7 @@ if MCP_AVAILABLE:log_list_tools_to_spendlogs: bool = False,list_tools_log_source: Optional[str] = None,litellm_trace_id: Optional[str] = None,+ client_ip: Optional[str] = None,) -> List[MCPTool]:"""Helper method to fetch tools from MCP servers based on server filtering criteria.@@ -1615,6 +1769,7 @@ if MCP_AVAILABLE:allowed_mcp_servers = await _get_allowed_mcp_servers(user_api_key_auth=user_api_key_auth,mcp_servers=mcp_servers,+ client_ip=client_ip,)# Pre-fetch OAuth credentials only when at least one server uses OAuth2,@@ -2024,6 +2179,7 @@ if MCP_AVAILABLE:raw_headers: Optional[Dict[str, str]] = None,log_list_tools_to_spendlogs: bool = False,list_tools_log_source: Optional[str] = None,+ client_ip: Optional[str] = None,) -> List[MCPTool]:"""List all available MCP tools.@@ -2033,6 +2189,7 @@ if MCP_AVAILABLE:mcp_auth_header: Optional auth header for MCP server (deprecated)mcp_servers: Optional list of server names/aliases to filter bymcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}+ client_ip: Client IP for IP-based server access controlReturns:List[MCPTool]: Combined list of tools from all accessible servers@@ -2056,6 +2213,7 @@ if MCP_AVAILABLE:raw_headers=raw_headers,log_list_tools_to_spendlogs=log_list_tools_to_spendlogs,list_tools_log_source=list_tools_log_source,+ client_ip=client_ip,)verbose_logger.debug(f"Successfully fetched {len(managed_tools)} tools from managed MCP servers")except Exception as e:diff --git a/litellm/proxy/_experimental/mcp_server/tool_search.py b/litellm/proxy/_experimental/mcp_server/tool_search.pynew file mode 100644index 00000000000..fa57a2b3eb2--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/tool_search.py@@ -0,0 +1,157 @@+from __future__ import annotations++import json+from datetime import datetime+from typing import TYPE_CHECKING, Any, Optional++if TYPE_CHECKING:+ from mcp.types import CallToolResult++ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+ from litellm.proxy._types import UserAPIKeyAuth++MCP_TOOL_SEARCH_TOOL_NAME: str = "mcp_tool_search"+MCP_TOOL_CALL_TOOL_NAME: str = "mcp_tool_call"+++def coerce_top_k(value: Any, default: int = 5) -> int:+ try:+ return int(value)+ except (TypeError, ValueError):+ return default+++def search_tools(query: str, tools: list[dict[str, Any]], top_k: int = 5) -> list[dict[str, Any]]:+ if not query:+ return []+ tokens = query.lower().split()++ def _score(tool: dict[str, Any]) -> int:+ haystack = (tool.get("name", "") + " " + tool.get("description", "")).lower()+ return sum(1 for t in tokens if t in haystack)++ scored = ((s, tool) for tool in tools if (s := _score(tool)) > 0)+ return [tool for _, tool in sorted(scored, key=lambda x: x[0], reverse=True)[:top_k]]+++def get_virtual_tool_definitions() -> list[dict[str, Any]]:+ return [+ {+ "name": MCP_TOOL_SEARCH_TOOL_NAME,+ "description": "Search for MCP tools by keyword. Returns top matching tools with names, descriptions, and input schemas.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "Keywords to search for in tool names and descriptions.",+ },+ "top_k": {+ "type": "integer",+ "description": "Maximum number of results to return.",+ "default": 5,+ },+ },+ "required": ["query"],+ },+ },+ {+ "name": MCP_TOOL_CALL_TOOL_NAME,+ "description": "Call an MCP tool by name with the given arguments.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "tool_name": {+ "type": "string",+ "description": "The exact name of the MCP tool to call.",+ },+ "arguments": {+ "type": "object",+ "description": "Arguments to pass to the tool.",+ },+ },+ "required": ["tool_name"],+ },+ },+ ]+++async def handle_mcp_tool_search(+ query: str,+ top_k: int,+ user_api_key_dict: UserAPIKeyAuth,+ client_ip: Optional[str] = None,+ mcp_servers: Optional[list[str]] = None,+ mcp_auth_header: Optional[str] = None,+ mcp_server_auth_headers: Optional[dict[str, dict[str, str]]] = None,+ oauth2_headers: Optional[dict[str, str]] = None,+ raw_headers: Optional[dict[str, str]] = None,+) -> CallToolResult:+ from mcp.types import CallToolResult, TextContent++ from litellm.proxy._experimental.mcp_server.server import _list_mcp_tools++ mcp_tools = await _list_mcp_tools(+ user_api_key_auth=user_api_key_dict,+ mcp_servers=mcp_servers,+ client_ip=client_ip,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ )+ tools = [+ {+ "name": t.name,+ "description": t.description or "",+ "inputSchema": t.inputSchema,+ }+ for t in mcp_tools+ ]+ results = search_tools(query, tools, top_k)+ return CallToolResult(content=[TextContent(type="text", text=json.dumps(results))], isError=False)+++async def handle_mcp_tool_call(+ tool_name: str,+ arguments: dict[str, Any],+ user_api_key_dict: UserAPIKeyAuth,+ client_ip: Optional[str] = None,+ mcp_servers: Optional[list[str]] = None,+ mcp_auth_header: Optional[str] = None,+ mcp_server_auth_headers: Optional[dict[str, dict[str, str]]] = None,+ oauth2_headers: Optional[dict[str, str]] = None,+ raw_headers: Optional[dict[str, str]] = None,+ litellm_logging_obj: Optional[LiteLLMLoggingObj] = None,+) -> CallToolResult:+ from litellm.proxy._experimental.mcp_server.server import (+ _get_allowed_mcp_servers,+ execute_mcp_tool,+ )++ allowed_mcp_servers = await _get_allowed_mcp_servers(+ user_api_key_auth=user_api_key_dict,+ mcp_servers=mcp_servers,+ client_ip=client_ip,+ )++ # Reject before dispatch when the key has no accessible servers; otherwise an+ # unprefixed local tool name would fall through to the local registry in+ # execute_mcp_tool, which has no server permission check.+ if not allowed_mcp_servers:+ from fastapi import HTTPException++ raise HTTPException(status_code=403, detail="User not allowed to call this tool.")++ return await execute_mcp_tool(+ name=tool_name,+ arguments=arguments,+ allowed_mcp_servers=allowed_mcp_servers,+ start_time=datetime.now(),+ user_api_key_auth=user_api_key_dict,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ litellm_logging_obj=litellm_logging_obj,+ )diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 643f8d69300..12466b525d6 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -1006,6 +1006,7 @@ class LiteLLM_ObjectPermissionBase(LiteLLMPydanticObjectBase):agent_access_groups: Optional[List[str]] = Nonemodels: Optional[List[str]] = Nonesearch_tools: Optional[List[str]] = None+ mcp_tool_search_enabled: Optional[bool] = Nonefrom litellm.types.object_permission import ( # noqa: E402diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex e21c0016491..5351e0a1470 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -279,6 +279,7 @@ model LiteLLM_ObjectPermissionTable {blocked_tools String[] @default([]) // Tool names blocked for any key/team/user with this permissionmcp_toolsets String[] @default([]) // Toolset IDs granted to this key/team/usersearch_tools String[] @default([]) // search_tool_name values this key/team/user may call+ mcp_tool_search_enabled Boolean?teams LiteLLM_TeamTable[]projects LiteLLM_ProjectTable[]verification_tokens LiteLLM_VerificationToken[]diff --git a/litellm/types/object_permission.py b/litellm/types/object_permission.pyindex ff932dccd5d..d0458173fbf 100644--- a/litellm/types/object_permission.py+++ b/litellm/types/object_permission.py@@ -24,3 +24,4 @@ class ObjectPermissionDict(TypedDict, total=False):agent_access_groups: Optional[list[str]]models: Optional[list[str]]search_tools: Optional[list[str]]+ mcp_tool_search_enabled: Optional[bool]diff --git a/schema.prisma b/schema.prismaindex e21c0016491..5351e0a1470 100644--- a/schema.prisma+++ b/schema.prisma@@ -279,6 +279,7 @@ model LiteLLM_ObjectPermissionTable {blocked_tools String[] @default([]) // Tool names blocked for any key/team/user with this permissionmcp_toolsets String[] @default([]) // Toolset IDs granted to this key/team/usersearch_tools String[] @default([]) // search_tool_name values this key/team/user may call+ mcp_tool_search_enabled Boolean?teams LiteLLM_TeamTable[]projects LiteLLM_ProjectTable[]verification_tokens LiteLLM_VerificationToken[]diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.pynew file mode 100644index 00000000000..9c20808df67--- /dev/null+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py@@ -0,0 +1,837 @@+"""+Tests for MCP tool search feature.++Covers:+- search_tools() pure function+- get_virtual_tool_definitions() shape+- list_tool_rest_api returns only virtual tools when mcp_tool_search_enabled=True+- call_tool_rest_api intercepts mcp_tool_search calls+- call_tool_rest_api intercepts mcp_tool_call calls+"""++import json+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from litellm.models.object_permission import LiteLLM_ObjectPermissionTable+from litellm.proxy._experimental.mcp_server.tool_search import (+ MCP_TOOL_CALL_TOOL_NAME,+ MCP_TOOL_SEARCH_TOOL_NAME,+ coerce_top_k,+ get_virtual_tool_definitions,+ search_tools,+)+from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+++def _make_tools(specs: list[tuple[str, str]]) -> list[dict[str, Any]]:+ return [+ {+ "name": name,+ "description": desc,+ "inputSchema": {"type": "object", "properties": {}},+ }+ for name, desc in specs+ ]+++def _make_perm(**kwargs: Any) -> LiteLLM_ObjectPermissionTable:+ return LiteLLM_ObjectPermissionTable(object_permission_id="test", **kwargs)+++SAMPLE_TOOLS = _make_tools(+ [+ ("github-create_issue", "Create a new issue in a GitHub repository"),+ ("github-list_repos", "List all repositories for a GitHub user"),+ ("slack-send_message", "Send a message to a Slack channel"),+ ("slack-list_channels", "List all Slack channels in a workspace"),+ ("notion-create_page", "Create a new page in Notion"),+ ]+)+++class TestCoerceTopK:+ def test_int_passthrough(self) -> None:+ assert coerce_top_k(3) == 3++ def test_numeric_string_coerced(self) -> None:+ assert coerce_top_k("7") == 7++ def test_float_truncated(self) -> None:+ assert coerce_top_k(3.9) == 3++ def test_non_numeric_string_returns_default(self) -> None:+ assert coerce_top_k("abc") == 5++ def test_none_returns_default(self) -> None:+ assert coerce_top_k(None) == 5++ def test_custom_default(self) -> None:+ assert coerce_top_k("nope", default=10) == 10+++class TestSearchTools:+ def test_returns_matching_tools(self) -> None:+ results = search_tools("github issue", SAMPLE_TOOLS)+ names = [t["name"] for t in results]+ assert "github-create_issue" in names++ def test_ranks_by_relevance(self) -> None:+ results = search_tools("github", SAMPLE_TOOLS)+ names = [t["name"] for t in results]+ github_positions = [i for i, n in enumerate(names) if n.startswith("github")]+ other_positions = [i for i, n in enumerate(names) if not n.startswith("github")]+ assert all(g < o for g in github_positions for o in other_positions)++ def test_top_k_limits_results(self) -> None:+ results = search_tools("a", SAMPLE_TOOLS, top_k=2)+ assert len(results) <= 2++ def test_empty_query_returns_empty(self) -> None:+ assert search_tools("", SAMPLE_TOOLS) == []++ def test_no_match_returns_empty(self) -> None:+ assert search_tools("xyzzy_nonexistent_zzz", SAMPLE_TOOLS) == []++ def test_matches_description_not_just_name(self) -> None:+ results = search_tools("channel", SAMPLE_TOOLS)+ names = [t["name"] for t in results]+ assert "slack-list_channels" in names++ def test_case_insensitive(self) -> None:+ lower = [t["name"] for t in search_tools("github", SAMPLE_TOOLS)]+ upper = [t["name"] for t in search_tools("GITHUB", SAMPLE_TOOLS)]+ assert lower == upper++ def test_result_tools_have_full_schema(self) -> None:+ for tool in search_tools("github", SAMPLE_TOOLS):+ assert "name" in tool+ assert "description" in tool+ assert "inputSchema" in tool+++class TestGetVirtualToolDefinitions:+ def test_returns_two_tools(self) -> None:+ assert len(get_virtual_tool_definitions()) == 2++ def test_has_mcp_tool_search(self) -> None:+ names = [t["name"] for t in get_virtual_tool_definitions()]+ assert MCP_TOOL_SEARCH_TOOL_NAME in names++ def test_has_mcp_tool_call(self) -> None:+ names = [t["name"] for t in get_virtual_tool_definitions()]+ assert MCP_TOOL_CALL_TOOL_NAME in names++ def test_mcp_tool_search_schema_has_query(self) -> None:+ tools = get_virtual_tool_definitions()+ search_tool = next(t for t in tools if t["name"] == MCP_TOOL_SEARCH_TOOL_NAME)+ props = search_tool["inputSchema"]["properties"]+ assert "query" in props+ assert search_tool["inputSchema"]["required"] == ["query"]++ def test_mcp_tool_call_schema_has_tool_name_and_arguments(self) -> None:+ tools = get_virtual_tool_definitions()+ call_tool = next(t for t in tools if t["name"] == MCP_TOOL_CALL_TOOL_NAME)+ props = call_tool["inputSchema"]["properties"]+ assert "tool_name" in props+ assert "arguments" in props+ assert "tool_name" in call_tool["inputSchema"]["required"]++ def test_all_tools_have_description(self) -> None:+ for tool in get_virtual_tool_definitions():+ assert tool.get("description"), f"{tool['name']} missing description"++ def test_definitions_construct_mcp_protocol_tool(self) -> None:+ """The MCP protocol list_tools handler builds mcp.types.Tool(**d) from+ each definition, so the dict keys must stay valid Tool fields."""+ from mcp.types import Tool++ built = [Tool(**d) for d in get_virtual_tool_definitions()]+ assert {t.name for t in built} == {+ MCP_TOOL_SEARCH_TOOL_NAME,+ MCP_TOOL_CALL_TOOL_NAME,+ }+++class TestListToolRestApiWithToolSearch:+ @pytest.mark.asyncio+ async def test_returns_only_virtual_tools_when_flag_enabled(self) -> None:+ from litellm.proxy._experimental.mcp_server.rest_endpoints import router++ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(+ mcp_tool_search_enabled=True,+ mcp_servers=["github", "slack"],+ ),+ )++ mock_request = MagicMock()+ mock_request.headers = {}++ list_fn = next(+ r.endpoint+ for r in router.routes+ if hasattr(r, "path") and r.path.endswith("/tools/list") and hasattr(r, "methods") and "GET" in r.methods+ )++ result = await list_fn(+ request=mock_request,+ server_id=None,+ include_disabled_tools=False,+ user_api_key_dict=user_api_key_dict,+ )++ assert result["error"] is None+ tool_names = [t["name"] for t in result["tools"]]+ assert set(tool_names) == {MCP_TOOL_SEARCH_TOOL_NAME, MCP_TOOL_CALL_TOOL_NAME}++ @pytest.mark.asyncio+ async def test_returns_full_catalog_when_flag_disabled(self) -> None:+ from litellm.proxy._experimental.mcp_server.rest_endpoints import router++ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(+ mcp_tool_search_enabled=False,+ mcp_servers=["github"],+ ),+ )++ mock_request = MagicMock()+ mock_request.headers = {}++ fake_tools = [+ {+ "name": "github-create_issue",+ "description": "Create issue",+ "inputSchema": {"type": "object"},+ }+ ]++ list_fn = next(+ r.endpoint+ for r in router.routes+ if hasattr(r, "path") and r.path.endswith("/tools/list") and hasattr(r, "methods") and "GET" in r.methods+ )++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints.build_effective_auth_contexts",+ new_callable=AsyncMock,+ return_value=[user_api_key_dict],+ ),+ patch("litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager") as mock_manager,+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server",+ new_callable=AsyncMock,+ return_value=fake_tools,+ ),+ patch("litellm.proxy._experimental.mcp_server.rest_endpoints.IPAddressUtils"),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._prefetch_user_oauth_creds",+ new_callable=AsyncMock,+ return_value={},+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_oauth2_server_ids",+ return_value=[],+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_server_auth_header",+ return_value=None,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_user_oauth_extra_headers",+ new_callable=AsyncMock,+ return_value=None,+ ),+ ):+ mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["github"])+ mock_manager.filter_server_ids_by_ip_with_info = MagicMock(return_value=(["github"], 0))+ mock_manager.get_mcp_server_by_id = MagicMock(return_value=MagicMock(name="github", server_id="github"))+ result = await list_fn(+ request=mock_request,+ server_id=None,+ include_disabled_tools=False,+ user_api_key_dict=user_api_key_dict,+ )++ tool_names = [t["name"] for t in result["tools"]]+ assert MCP_TOOL_SEARCH_TOOL_NAME not in tool_names+ assert "github-create_issue" in tool_names++ @pytest.mark.asyncio+ async def test_admin_include_disabled_tools_bypasses_virtual_catalog(self) -> None:+ """Regression: an admin listing with include_disabled_tools must see the+ real catalog (to configure allowlists) even when mcp_tool_search_enabled is+ set, instead of the two virtual tools."""+ from litellm.proxy._experimental.mcp_server.rest_endpoints import router++ user_api_key_dict = UserAPIKeyAuth(+ api_key="admin_key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ object_permission=_make_perm(+ mcp_tool_search_enabled=True,+ mcp_servers=["github"],+ ),+ )++ mock_request = MagicMock()+ mock_request.headers = {}++ fake_tools = [+ {+ "name": "github-create_issue",+ "description": "Create issue",+ "inputSchema": {"type": "object"},+ }+ ]++ list_fn = next(+ r.endpoint+ for r in router.routes+ if hasattr(r, "path") and r.path.endswith("/tools/list") and hasattr(r, "methods") and "GET" in r.methods+ )++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints.build_effective_auth_contexts",+ new_callable=AsyncMock,+ return_value=[user_api_key_dict],+ ),+ patch("litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager") as mock_manager,+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server",+ new_callable=AsyncMock,+ return_value=fake_tools,+ ),+ patch("litellm.proxy._experimental.mcp_server.rest_endpoints.IPAddressUtils"),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._prefetch_user_oauth_creds",+ new_callable=AsyncMock,+ return_value={},+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_oauth2_server_ids",+ return_value=[],+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_server_auth_header",+ return_value=None,+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints._get_user_oauth_extra_headers",+ new_callable=AsyncMock,+ return_value=None,+ ),+ ):+ mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["github"])+ mock_manager.filter_server_ids_by_ip_with_info = MagicMock(return_value=(["github"], 0))+ mock_manager.get_mcp_server_by_id = MagicMock(return_value=MagicMock(name="github", server_id="github"))+ result = await list_fn(+ request=mock_request,+ server_id=None,+ include_disabled_tools=True,+ user_api_key_dict=user_api_key_dict,+ )++ tool_names = [t["name"] for t in result["tools"]]+ assert MCP_TOOL_SEARCH_TOOL_NAME not in tool_names+ assert "github-create_issue" in tool_names+++class TestCallToolRestApiVirtualTools:+ def _make_request(self, body: dict[str, Any]) -> MagicMock:+ mock_request = MagicMock()+ mock_request.json = AsyncMock(return_value=body)+ mock_request.headers = {}+ mock_request.url = MagicMock()+ mock_request.url.path = "/mcp-rest/tools/call"+ return mock_request++ def _get_call_fn(self) -> Any:+ from litellm.proxy._experimental.mcp_server.rest_endpoints import router++ return next(+ r.endpoint+ for r in router.routes+ if hasattr(r, "path") and r.path.endswith("/tools/call") and hasattr(r, "methods") and "POST" in r.methods+ )++ @pytest.mark.asyncio+ async def test_mcp_tool_search_call_returns_tool_defs(self) -> None:+ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(+ mcp_tool_search_enabled=True,+ mcp_servers=["github"],+ ),+ )++ request = self._make_request({"name": MCP_TOOL_SEARCH_TOOL_NAME, "arguments": {"query": "create issue"}})++ mock_tool = MagicMock()+ mock_tool.name = "github-create_issue"+ mock_tool.description = "Create a GitHub issue"+ mock_tool.inputSchema = {"type": "object", "properties": {}}++ with patch(+ "litellm.proxy._experimental.mcp_server.server._list_mcp_tools",+ new_callable=AsyncMock,+ return_value=[mock_tool],+ ):+ result = await self._get_call_fn()(+ request=request,+ user_api_key_dict=user_api_key_dict,+ )++ assert result.content+ assert result.content[0].type == "text"+ returned_tools = json.loads(result.content[0].text)+ assert isinstance(returned_tools, list)+ assert any(t["name"] == "github-create_issue" for t in returned_tools)++ @pytest.mark.asyncio+ async def test_mcp_tool_call_executes_discovered_tool(self) -> None:+ from mcp.types import CallToolResult, TextContent++ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(+ mcp_tool_search_enabled=True,+ mcp_servers=["github"],+ ),+ )++ request = self._make_request(+ {+ "name": MCP_TOOL_CALL_TOOL_NAME,+ "arguments": {+ "tool_name": "github-create_issue",+ "arguments": {"title": "bug", "repo": "myrepo"},+ },+ }+ )++ fake_result = CallToolResult(+ content=[TextContent(type="text", text="Issue created")],+ isError=False,+ )++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server._get_allowed_mcp_servers",+ new_callable=AsyncMock,+ return_value=[MagicMock()],+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.execute_mcp_tool",+ new_callable=AsyncMock,+ return_value=fake_result,+ ) as mock_execute,+ ):+ result = await self._get_call_fn()(+ request=request,+ user_api_key_dict=user_api_key_dict,+ )++ mock_execute.assert_awaited_once()+ assert mock_execute.await_args.kwargs["name"] == "github-create_issue"++ assert result.isError is False+ assert result.content[0].text == "Issue created"++ @pytest.mark.asyncio+ async def test_mcp_tool_call_forwards_client_ip_for_ip_filtering(self) -> None:+ """Regression: the virtual call path must resolve allowed servers with the+ request's client IP so IP-restricted servers (available_on_public_internet:+ false) cannot be reached from a public IP."""+ from mcp.types import CallToolResult, TextContent++ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(mcp_tool_search_enabled=True, mcp_servers=["github"]),+ )+ request = self._make_request(+ {+ "name": MCP_TOOL_CALL_TOOL_NAME,+ "arguments": {"tool_name": "github-create_issue", "arguments": {}},+ }+ )++ fake_result = CallToolResult(content=[TextContent(type="text", text="ok")], isError=False)++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints.IPAddressUtils.get_mcp_client_ip",+ return_value="203.0.113.7",+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._get_allowed_mcp_servers",+ new_callable=AsyncMock,+ return_value=[MagicMock()],+ ) as mock_allowed,+ patch(+ "litellm.proxy._experimental.mcp_server.server.execute_mcp_tool",+ new_callable=AsyncMock,+ return_value=fake_result,+ ),+ ):+ await self._get_call_fn()(request=request, user_api_key_dict=user_api_key_dict)++ mock_allowed.assert_awaited_once()+ assert mock_allowed.await_args.kwargs["client_ip"] == "203.0.113.7"++ @pytest.mark.asyncio+ async def test_mcp_tool_search_forwards_client_ip_for_ip_filtering(self) -> None:+ """Search must list tools through the IP-filtered catalog, not the raw one."""+ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(mcp_tool_search_enabled=True, mcp_servers=["github"]),+ )+ request = self._make_request({"name": MCP_TOOL_SEARCH_TOOL_NAME, "arguments": {"query": "issue"}})++ with (+ patch(+ "litellm.proxy._experimental.mcp_server.rest_endpoints.IPAddressUtils.get_mcp_client_ip",+ return_value="203.0.113.7",+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._list_mcp_tools",+ new_callable=AsyncMock,+ return_value=[],+ ) as mock_list,+ ):+ await self._get_call_fn()(request=request, user_api_key_dict=user_api_key_dict)++ mock_list.assert_awaited_once()+ assert mock_list.await_args.kwargs["client_ip"] == "203.0.113.7"++ @pytest.mark.asyncio+ async def test_mcp_tool_search_requires_flag_enabled(self) -> None:+ from fastapi import HTTPException++ user_api_key_dict = UserAPIKeyAuth(+ api_key="test_key",+ object_permission=_make_perm(mcp_tool_search_enabled=False),+ )++ request = self._make_request({"name": MCP_TOOL_SEARCH_TOOL_NAME, "arguments": {"query": "create issue"}})++ with pytest.raises(HTTPException) as exc_info:+ await self._get_call_fn()(+ request=request,+ user_api_key_dict=user_api_key_dict,+ )++ assert exc_info.value.status_code in (400, 403, 404)+++class TestDispatchVirtualMcpTool:+ """Covers the SSE/protocol-path interception helper in server.py."""++ @pytest.mark.asyncio+ async def test_returns_none_for_non_virtual_tool(self) -> None:+ from litellm.proxy._experimental.mcp_server.server import (+ _dispatch_virtual_mcp_tool,+ )++ result = await _dispatch_virtual_mcp_tool(+ name="github-create_issue",+ arguments={},+ user_api_key_auth=UserAPIKeyAuth(api_key="k"),+ client_ip=None,+ )+ assert result is None++ @pytest.mark.asyncio+ async def test_rejects_when_flag_disabled(self) -> None:+ from litellm.proxy._experimental.mcp_server.server import (+ _dispatch_virtual_mcp_tool,+ )++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=False))+ result = await _dispatch_virtual_mcp_tool(+ name=MCP_TOOL_SEARCH_TOOL_NAME,+ arguments={"query": "x"},+ user_api_key_auth=uak,+ client_ip=None,+ )+ assert result is not None+ assert result.isError is True++ @pytest.mark.asyncio+ async def test_routes_search_with_client_ip(self) -> None:+ from litellm.proxy._experimental.mcp_server import server as srv++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ with patch(+ "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_tool_search",+ new_callable=AsyncMock,+ return_value="SEARCH_RESULT",+ ) as mock_search:+ result = await srv._dispatch_virtual_mcp_tool(+ name=MCP_TOOL_SEARCH_TOOL_NAME,+ arguments={"query": "q", "top_k": 3},+ user_api_key_auth=uak,+ client_ip="203.0.113.9",+ )++ assert result == "SEARCH_RESULT"+ assert mock_search.await_args.kwargs["client_ip"] == "203.0.113.9"+ assert mock_search.await_args.kwargs["query"] == "q"+ assert mock_search.await_args.kwargs["top_k"] == 3++ @pytest.mark.asyncio+ async def test_routes_call_with_client_ip(self) -> None:+ from litellm.proxy._experimental.mcp_server import server as srv++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ with patch(+ "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_tool_call",+ new_callable=AsyncMock,+ return_value="CALL_RESULT",+ ) as mock_call:+ result = await srv._dispatch_virtual_mcp_tool(+ name=MCP_TOOL_CALL_TOOL_NAME,+ arguments={"tool_name": "math-add", "arguments": {"a": 1, "b": 2}},+ user_api_key_auth=uak,+ client_ip="203.0.113.9",+ mcp_auth_header="bearer-xyz",+ mcp_server_auth_headers={"github": {"Authorization": "Bearer gh"}},+ oauth2_headers={"Authorization": "Bearer oauth"},+ raw_headers={"x-mcp-auth": "tok"},+ )++ assert result == "CALL_RESULT"+ kw = mock_call.await_args.kwargs+ assert kw["tool_name"] == "math-add"+ assert kw["client_ip"] == "203.0.113.9"+ assert kw["mcp_auth_header"] == "bearer-xyz"+ assert kw["mcp_server_auth_headers"] == {"github": {"Authorization": "Bearer gh"}}+ assert kw["oauth2_headers"] == {"Authorization": "Bearer oauth"}+ assert kw["raw_headers"] == {"x-mcp-auth": "tok"}++ @pytest.mark.asyncio+ async def test_call_builds_and_forwards_logging_obj(self) -> None:+ """Regression: the SSE dispatch must run the pre-call pipeline and forward+ the resulting logging object to handle_mcp_tool_call, otherwise mcp_tool_call+ over /mcp/ skips spend logging and guardrails (unlike the REST path)."""+ from litellm.proxy._experimental.mcp_server import server as srv++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ sentinel_logging_obj = object()+ with (+ patch.object(+ srv,+ "_build_virtual_call_logging_obj",+ new_callable=AsyncMock,+ return_value=sentinel_logging_obj,+ ) as mock_build,+ patch(+ "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_tool_call",+ new_callable=AsyncMock,+ return_value="CALL_RESULT",+ ) as mock_call,+ ):+ await srv._dispatch_virtual_mcp_tool(+ name=MCP_TOOL_CALL_TOOL_NAME,+ arguments={"tool_name": "math-add", "arguments": {"a": 1}},+ user_api_key_auth=uak,+ client_ip=None,+ )++ assert mock_build.await_count == 1+ assert mock_call.await_args.kwargs["litellm_logging_obj"] is sentinel_logging_obj++ @pytest.mark.asyncio+ async def test_search_coerces_non_int_top_k(self) -> None:+ """Regression: a non-integer top_k from an MCP client must not raise; it+ falls back to the default instead of ValueError propagating out."""+ from litellm.proxy._experimental.mcp_server import server as srv++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ with patch(+ "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_tool_search",+ new_callable=AsyncMock,+ return_value="SEARCH_RESULT",+ ) as mock_search:+ await srv._dispatch_virtual_mcp_tool(+ name=MCP_TOOL_SEARCH_TOOL_NAME,+ arguments={"query": "issue", "top_k": "not-a-number"},+ user_api_key_auth=uak,+ client_ip=None,+ )++ assert mock_search.await_args.kwargs["top_k"] == 5++ @pytest.mark.asyncio+ async def test_call_handler_forwards_auth_headers_to_execute(self) -> None:+ """Regression: per-request auth headers must reach execute_mcp_tool so+ upstream MCP servers needing pass-through auth can be called."""+ from mcp.types import CallToolResult, TextContent++ from litellm.proxy._experimental.mcp_server.tool_search import (+ handle_mcp_tool_call,+ )++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ fake = CallToolResult(content=[TextContent(type="text", text="ok")], isError=False)+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server._get_allowed_mcp_servers",+ new_callable=AsyncMock,+ return_value=[MagicMock()],+ ) as mock_allowed,+ patch(+ "litellm.proxy._experimental.mcp_server.server.execute_mcp_tool",+ new_callable=AsyncMock,+ return_value=fake,+ ) as mock_exec,+ ):+ sentinel_logging_obj = object()+ await handle_mcp_tool_call(+ tool_name="github-create_issue",+ arguments={},+ user_api_key_dict=uak,+ mcp_servers=["github"],+ mcp_auth_header="bearer-xyz",+ mcp_server_auth_headers={"github": {"Authorization": "Bearer gh"}},+ oauth2_headers={"Authorization": "Bearer oauth"},+ raw_headers={"x-mcp-auth": "tok"},+ litellm_logging_obj=sentinel_logging_obj,+ )++ kw = mock_exec.await_args.kwargs+ assert kw["mcp_auth_header"] == "bearer-xyz"+ assert kw["mcp_server_auth_headers"] == {"github": {"Authorization": "Bearer gh"}}+ assert kw["oauth2_headers"] == {"Authorization": "Bearer oauth"}+ assert kw["raw_headers"] == {"x-mcp-auth": "tok"}+ # Spend logging: the logging object must reach execute_mcp_tool+ assert kw["litellm_logging_obj"] is sentinel_logging_obj+ # Scoped session: the requested mcp_servers scope must reach server resolution+ assert mock_allowed.await_args.kwargs["mcp_servers"] == ["github"]++ @pytest.mark.asyncio+ async def test_call_rejected_when_no_accessible_servers(self) -> None:+ """Regression: a key with no accessible MCP servers must not reach+ execute_mcp_tool, where an unprefixed local tool name would otherwise+ run via the local registry without a server permission check."""+ from fastapi import HTTPException++ from litellm.proxy._experimental.mcp_server.tool_search import (+ handle_mcp_tool_call,+ )++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server._get_allowed_mcp_servers",+ new_callable=AsyncMock,+ return_value=[],+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server.execute_mcp_tool",+ new_callable=AsyncMock,+ ) as mock_exec,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await handle_mcp_tool_call(+ tool_name="local_secret_tool",+ arguments={},+ user_api_key_dict=uak,+ )++ assert exc_info.value.status_code == 403+ mock_exec.assert_not_awaited()+++class TestCaptureHostProgressCallback:+ """Covers the host progress-forwarding helper extracted from the tool call path."""++ def test_returns_none_when_request_context_unavailable(self) -> None:+ from litellm.proxy._experimental.mcp_server.server import (+ _capture_host_progress_callback,+ )++ class _NoCtx:+ @property+ def request_context(self): # type: ignore[no-untyped-def]+ raise RuntimeError("no context")++ assert _capture_host_progress_callback(_NoCtx()) is None++ def test_returns_none_when_no_progress_token(self) -> None:+ from litellm.proxy._experimental.mcp_server.server import (+ _capture_host_progress_callback,+ )++ host = MagicMock()+ host.request_context.meta.progressToken = None+ assert _capture_host_progress_callback(host) is None++ def test_returns_callable_when_token_present(self) -> None:+ from litellm.proxy._experimental.mcp_server.server import (+ _capture_host_progress_callback,+ )++ host = MagicMock()+ host.request_context.meta.progressToken = "tok12345"+ host.request_context.session = MagicMock()+ assert callable(_capture_host_progress_callback(host))+++class TestHandleListToolsVirtual:+ """Covers the protocol list_tools early-return when the flag is enabled."""++ @pytest.mark.asyncio+ async def test_returns_virtual_tools_when_flag_enabled(self) -> None:+ from litellm.proxy._experimental.mcp_server import server as srv++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ with patch(+ "litellm.proxy._experimental.mcp_server.server.get_or_extract_auth_context",+ new_callable=AsyncMock,+ return_value=(uak, None, None, None, None, None, None),+ ):+ tools = await srv.handle_list_tools()++ assert {t.name for t in tools} == {+ MCP_TOOL_SEARCH_TOOL_NAME,+ MCP_TOOL_CALL_TOOL_NAME,+ }+++class TestMcpServerToolCallErrorHandling:+ """The protocol tool-call handler must convert virtual-tool errors to an+ isError CallToolResult instead of letting them raise out of the handler."""++ @pytest.mark.asyncio+ async def test_virtual_tool_error_returns_iserror_not_raised(self) -> None:+ from fastapi import HTTPException++ from litellm.proxy._experimental.mcp_server import server as srv++ uak = UserAPIKeyAuth(api_key="k", object_permission=_make_perm(mcp_tool_search_enabled=True))+ with (+ patch(+ "litellm.proxy._experimental.mcp_server.server.get_or_extract_auth_context",+ new_callable=AsyncMock,+ return_value=(uak, None, None, None, None, None, None),+ ),+ patch(+ "litellm.proxy._experimental.mcp_server.server._dispatch_virtual_mcp_tool",+ new_callable=AsyncMock,+ side_effect=HTTPException(status_code=403, detail="User not allowed to call this tool"),+ ),+ ):+ result = await srv.mcp_server_tool_call(+ name=MCP_TOOL_CALL_TOOL_NAME,+ arguments={"tool_name": "other-server-tool", "arguments": {}},+ )++ assert result.isError is True+ assert "User not allowed to call this tool" in result.content[0].textdiff --git a/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.pyindex d4089b23e81..5fbc3c4869b 100644--- a/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py@@ -718,6 +718,7 @@ _EXPECTED_CUSTOMER = {"mcp_toolsets": None,"blocked_tools": [],"search_tools": [],+ "mcp_tool_search_enabled": None,},}diff --git a/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py b/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.pyindex 26c8c774812..0981c4239ee 100644--- a/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py+++ b/tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py@@ -87,6 +87,38 @@ async def test_set_object_permission():assert result["models"] == ["gpt-4"]+async def test_set_object_permission_persists_mcp_tool_search_enabled():+ """+ Regression: mcp_tool_search_enabled must be carried into the Prisma create+ payload so it persists to LiteLLM_ObjectPermissionTable. The field was+ present on the Pydantic models but missing from the create path, so keys+ generated with mcp_tool_search_enabled=True silently lost the flag.+ """+ mock_prisma_client = MagicMock()+ mock_created_permission = MagicMock()+ mock_created_permission.object_permission_id = "perm_id"+ mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(+ return_value=mock_created_permission+ )++ data_json = {+ "object_permission": {+ "mcp_servers": ["server_a"],+ "mcp_tool_search_enabled": True,+ },+ }++ await _set_object_permission(data_json=data_json, prisma_client=mock_prisma_client)++ created_data = (+ mock_prisma_client.db.litellm_objectpermissiontable.create.call_args.kwargs[+ "data"+ ]+ )+ assert created_data["mcp_tool_search_enabled"] is True++# ---- Tests for _extract_requested_mcp_server_ids ----diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex f15eaf9ea1f..ddf2040cd04 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -25107,6 +25107,8 @@ export interface components {mcp_tool_permissions?: {[key: string]: string[];} | null;+ /** Mcp Tool Search Enabled */+ mcp_tool_search_enabled?: boolean | null;/** Mcp Toolsets */mcp_toolsets?: string[] | null;/** Models */@@ -25150,6 +25152,8 @@ export interface components {mcp_tool_permissions?: {[key: string]: string[];} | null;+ /** Mcp Tool Search Enabled */+ mcp_tool_search_enabled?: boolean | null;/** Mcp Toolsets */mcp_toolsets?: string[] | null;/**