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]

[Fixes] Bug fixes to using LiteLLM MCP Gateway (#14392)

Ishaan Jaffa13aa4740ab4
diff --git a/cookbook/litellm_proxy_server/mcp/mcp_with_litellm_proxy.py b/cookbook/litellm_proxy_server/mcp/mcp_with_litellm_proxy.py
new file mode 100644
index 00000000000..351b0920eb8
--- /dev/null
+++ b/cookbook/litellm_proxy_server/mcp/mcp_with_litellm_proxy.py
@@ -0,0 +1,36 @@
+"""
+Use LiteLLM Proxy MCP Gateway to call MCP tools.
+
+When using LiteLLM Proxy, you can use the same MCP tools across all your LLM providers.
+"""
+import openai
+
+client = openai.OpenAI(
+ api_key="sk-1234", # paste your litellm proxy api key here
+ base_url="http://localhost:4000" # paste your litellm proxy base url here
+)
+print("Making API request to Responses API with MCP tools")
+
+response = client.responses.create(
+ model="gpt-5",
+ input=[
+ {
+ "role": "user",
+ "content": "give me TLDR of what BerriAI/litellm repo is about",
+ "type": "message"
+ }
+ ],
+ tools=[
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy",
+ "require_approval": "never"
+ }
+ ],
+ stream=True,
+ tool_choice="required"
+)
+
+for chunk in response:
+ print("response chunk: ", chunk)
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.md
index 1e523600a86..18c99051709 100644
--- a/docs/my-website/docs/mcp.md
+++ b/docs/my-website/docs/mcp.md
@@ -197,10 +197,17 @@ litellm_settings:
### Use on LiteLLM UI
+Follow this walkthrough to use your MCP on LiteLLM UI
+
+<iframe width="840" height="500" src="https://www.loom.com/embed/57e0763267254bc79dbe6658d0b8758c" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
+
### Use with Responses API
Replace `http://localhost:4000` with your LiteLLM Proxy base URL.
+Demo Video Using Responses API with LiteLLM Proxy: [Demo video here](https://www.loom.com/share/34587e618c5c47c0b0d67b4e4d02718f?sid=2caf3d45-ead4-4490-bcc1-8d6dd6041c02)
+
+
<Tabs>
<TabItem value="curl" label="cURL">
@@ -234,12 +241,18 @@ curl --location 'http://localhost:4000/v1/responses' \
<TabItem value="python" label="Python SDK">
```python title="Python SDK Example" showLineNumbers
+"""
+Use LiteLLM Proxy MCP Gateway to call MCP tools.
+
+When using LiteLLM Proxy, you can use the same MCP tools across all your LLM providers.
+"""
import openai
client = openai.OpenAI(
- api_key="sk-1234",
- base_url="http://localhost:4000"
+ api_key="sk-1234", # paste your litellm proxy api key here
+ base_url="http://localhost:4000" # paste your litellm proxy base url here
)
+print("Making API request to Responses API with MCP tools")
response = client.responses.create(
model="gpt-5",
@@ -262,7 +275,8 @@ response = client.responses.create(
tool_choice="required"
)
-print(response)
+for chunk in response:
+ print("response chunk: ", chunk)
```
</TabItem>
diff --git a/litellm/experimental_mcp_client/tools.py b/litellm/experimental_mcp_client/tools.py
index bfbd3f96a5c..b716e3171e7 100644
--- a/litellm/experimental_mcp_client/tools.py
+++ b/litellm/experimental_mcp_client/tools.py
@@ -17,22 +17,60 @@ from litellm.types.utils import ChatCompletionMessageToolCall
########################################################
def transform_mcp_tool_to_openai_tool(mcp_tool: MCPTool) -> ChatCompletionToolParam:
"""Convert an MCP tool to an OpenAI tool."""
+ normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema)
+
return ChatCompletionToolParam(
type="function",
function=FunctionDefinition(
name=mcp_tool.name,
description=mcp_tool.description or "",
- parameters=mcp_tool.inputSchema,
+ parameters=normalized_parameters,
strict=False,
),
)
+def _normalize_mcp_input_schema(input_schema: dict) -> dict:
+ """
+ Normalize MCP input schema to ensure it's valid for OpenAI function calling.
+
+ OpenAI requires that function parameters have:
+ - type: 'object'
+ - properties: dict (can be empty)
+ - additionalProperties: false (recommended)
+ """
+ if not input_schema:
+ return {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": False
+ }
+
+ # Make a copy to avoid modifying the original
+ normalized_schema = dict(input_schema)
+
+ # Ensure type is 'object'
+ if "type" not in normalized_schema:
+ normalized_schema["type"] = "object"
+
+ # Ensure properties exists (can be empty)
+ if "properties" not in normalized_schema:
+ normalized_schema["properties"] = {}
+
+ # Add additionalProperties if not present (recommended by OpenAI)
+ if "additionalProperties" not in normalized_schema:
+ normalized_schema["additionalProperties"] = False
+
+ return normalized_schema
+
+
def transform_mcp_tool_to_openai_responses_api_tool(mcp_tool: MCPTool) -> FunctionToolParam:
"""Convert an MCP tool to an OpenAI Responses API tool."""
+ normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema)
+
return FunctionToolParam(
name=mcp_tool.name,
- parameters=mcp_tool.inputSchema,
+ parameters=normalized_parameters,
strict=False,
type="function",
description=mcp_tool.description or "",
diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py
index 392d47f9822..1d52f74b7b9 100644
--- a/litellm/llms/openai/responses/transformation.py
+++ b/litellm/llms/openai/responses/transformation.py
@@ -272,6 +272,14 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
ResponsesAPIStreamEvents.WEB_SEARCH_CALL_IN_PROGRESS: WebSearchCallInProgressEvent,
ResponsesAPIStreamEvents.WEB_SEARCH_CALL_SEARCHING: WebSearchCallSearchingEvent,
ResponsesAPIStreamEvents.WEB_SEARCH_CALL_COMPLETED: WebSearchCallCompletedEvent,
+ ResponsesAPIStreamEvents.MCP_LIST_TOOLS_IN_PROGRESS: MCPListToolsInProgressEvent,
+ ResponsesAPIStreamEvents.MCP_LIST_TOOLS_COMPLETED: MCPListToolsCompletedEvent,
+ ResponsesAPIStreamEvents.MCP_LIST_TOOLS_FAILED: MCPListToolsFailedEvent,
+ ResponsesAPIStreamEvents.MCP_CALL_IN_PROGRESS: MCPCallInProgressEvent,
+ ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DELTA: MCPCallArgumentsDeltaEvent,
+ ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DONE: MCPCallArgumentsDoneEvent,
+ ResponsesAPIStreamEvents.MCP_CALL_COMPLETED: MCPCallCompletedEvent,
+ ResponsesAPIStreamEvents.MCP_CALL_FAILED: MCPCallFailedEvent,
ResponsesAPIStreamEvents.ERROR: ErrorEvent,
}
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 38619112ccc..d0461f91e9e 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -215,9 +215,9 @@ if MCP_AVAILABLE:
"""
from fastapi import Request
+ from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException
from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
from litellm.proxy.proxy_server import proxy_config
- from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException
# Validate arguments
user_api_key_auth, mcp_auth_header, _, mcp_server_auth_headers, mcp_protocol_version = get_auth_context()
@@ -279,33 +279,15 @@ if MCP_AVAILABLE:
############ Helper Functions ##########################
########################################################
- async def _get_tools_from_mcp_servers(
- user_api_key_auth: Optional[UserAPIKeyAuth],
- mcp_auth_header: Optional[str],
+ async def _get_allowed_mcp_servers_from_mcp_server_names(
mcp_servers: Optional[List[str]],
- mcp_server_auth_headers: Optional[Dict[str, str]] = None,
- mcp_protocol_version: Optional[str] = None,
- ) -> List[MCPTool]:
+ allowed_mcp_servers: List[str],
+ ) -> List[str]:
"""
- Helper method to fetch tools from MCP servers based on server filtering criteria.
-
- Args:
- user_api_key_auth: User authentication info for access control
- mcp_auth_header: Optional auth header for MCP server (deprecated)
- mcp_servers: Optional list of server names/aliases to filter by
- mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
-
- Returns:
- List[MCPTool]: Combined list of tools from filtered servers
+ Get the filtered MCP servers from the MCP server names
"""
- if not MCP_AVAILABLE:
- return []
-
- # Get allowed MCP servers based on user permissions
- allowed_mcp_servers = await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth)
-
- filtered_server_ids = set()
-
+ from typing import Set
+ filtered_server_ids: Set[str] = set()
# Filter servers based on mcp_servers parameter if provided
if mcp_servers is not None:
for server_or_group in mcp_servers:
@@ -336,6 +318,40 @@ if MCP_AVAILABLE:
if filtered_server_ids:
allowed_mcp_servers = list(filtered_server_ids)
+
+ return allowed_mcp_servers
+
+ async def _get_tools_from_mcp_servers(
+ user_api_key_auth: Optional[UserAPIKeyAuth],
+ mcp_auth_header: Optional[str],
+ mcp_servers: Optional[List[str]],
+ mcp_server_auth_headers: Optional[Dict[str, str]] = None,
+ mcp_protocol_version: Optional[str] = None,
+ ) -> List[MCPTool]:
+ """
+ Helper method to fetch tools from MCP servers based on server filtering criteria.
+
+ Args:
+ user_api_key_auth: User authentication info for access control
+ mcp_auth_header: Optional auth header for MCP server (deprecated)
+ mcp_servers: Optional list of server names/aliases to filter by
+ mcp_server_auth_headers: Optional dict of server-specific auth headers {server_alias: auth_value}
+
+ Returns:
+ List[MCPTool]: Combined list of tools from filtered servers
+ """
+ if not MCP_AVAILABLE:
+ return []
+
+ # Get allowed MCP servers based on user permissions
+ allowed_mcp_servers = await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth)
+
+ if mcp_servers is not None:
+ allowed_mcp_servers = await _get_allowed_mcp_servers_from_mcp_server_names(
+ mcp_servers=mcp_servers,
+ allowed_mcp_servers=allowed_mcp_servers,
+ )
+
# Get tools from each allowed server
all_tools = []
@@ -556,20 +572,25 @@ if MCP_AVAILABLE:
except Exception as e:
return [TextContent(text=f"Error: {str(e)}", type="text")]
- async def extract_mcp_auth_context(scope, path):
+ def _get_mcp_servers_in_path(path: str) -> Optional[List[str]]:
"""
- Extracts mcp_servers from the path and processes the MCP request for auth context.
- Returns: (user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers)
+ Get the MCP servers from the path
"""
import re
-
- mcp_servers_from_path = None
+ mcp_servers_from_path: Optional[List[str]] = None
mcp_path_match = re.match(r"^/mcp/([^/]+)(/.*)?$", path)
if mcp_path_match:
mcp_servers_str = mcp_path_match.group(1)
if mcp_servers_str:
mcp_servers_from_path = [s.strip() for s in mcp_servers_str.split(",") if s.strip()]
+ return mcp_servers_from_path
+ async def extract_mcp_auth_context(scope, path):
+ """
+ Extracts mcp_servers from the path and processes the MCP request for auth context.
+ Returns: (user_api_key_auth, mcp_auth_header, mcp_servers, mcp_server_auth_headers)
+ """
+ mcp_servers_from_path = _get_mcp_servers_in_path(path)
if mcp_servers_from_path is not None:
(
user_api_key_auth,
diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
index be265c73bfc..a26ae32229a 100644
--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
@@ -17,8 +17,8 @@ Endpoints here:
"""
import importlib
-from typing import Iterable, List, Optional
from datetime import datetime
+from typing import Iterable, List, Optional
from fastapi import APIRouter, Depends, Header, HTTPException, Response, status
from fastapi.responses import JSONResponse
@@ -26,7 +26,9 @@ from fastapi.responses import JSONResponse
import litellm
from litellm._logging import verbose_logger, verbose_proxy_logger
from litellm.constants import LITELLM_PROXY_ADMIN_NAME
-from litellm.proxy._experimental.mcp_server.utils import validate_and_normalize_mcp_server_payload
+from litellm.proxy._experimental.mcp_server.utils import (
+ validate_and_normalize_mcp_server_payload,
+)
router = APIRouter(prefix="/v1/mcp", tags=["mcp"])
MCP_AVAILABLE: bool = True
@@ -94,34 +96,17 @@ if MCP_AVAILABLE:
"""
Get all MCP tools available for the current key, including those from access groups
"""
- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
- MCPRequestHandler,
- )
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
- global_mcp_server_manager,
+ from litellm.proxy._experimental.mcp_server.server import _list_mcp_tools
+ tools = await _list_mcp_tools(
+ user_api_key_auth=user_api_key_dict,
+ mcp_auth_header=None,
+ mcp_servers=None,
+ mcp_server_auth_headers=None,
+ mcp_protocol_version=None,
)
+ dumped_tools = [dict(tool) for tool in tools]
- # This now includes both direct and access group servers
- server_ids = await MCPRequestHandler._get_allowed_mcp_servers_for_key(user_api_key_dict)
-
- tools = []
- errors = []
- for server_id in server_ids:
- try:
- server_tools = await global_mcp_server_manager.get_tools_for_server(server_id)
- tools.extend(server_tools)
- verbose_proxy_logger.debug(f"Successfully fetched {len(server_tools)} tools from server {server_id}")
- except Exception as e:
- error_msg = f"Failed to get tools from server {server_id}: {str(e)}"
- verbose_proxy_logger.warning(error_msg)
- errors.append(error_msg)
- # Continue with other servers instead of failing completely
-
- verbose_proxy_logger.debug(f"Available tools: {tools}")
- if errors:
- verbose_proxy_logger.warning(f"Some servers failed to respond: {errors}")
-
- return {"tools": tools}
+ return {"tools": dumped_tools}
@router.get(
"/access_groups",
@@ -134,8 +119,10 @@ if MCP_AVAILABLE:
"""
Get all available MCP access groups from the database AND config
"""
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ global_mcp_server_manager,
+ )
from litellm.proxy.proxy_server import prisma_client
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager
access_groups = set()
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index 7ee09105254..54bfdac55f9 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -3,5 +3,16 @@ model_list:
litellm_params:
model: openai/*
api_base: https://exampleopenaiendpoint-production-0ee2.up.railway.app/
+ - model_name: bedrock/*
+ litellm_params:
+ model: bedrock/*
+ - model_name: openai/*
+ litellm_params:
+ model: openai/*
+ - model_name: gemini/*
+ litellm_params:
+ model: gemini/*
+
+
litellm_settings:
callbacks: ["cloudzero"]
\ No newline at end of file
diff --git a/litellm/responses/main.py b/litellm/responses/main.py
index 47ecbcf02c0..04ee2b343f5 100644
--- a/litellm/responses/main.py
+++ b/litellm/responses/main.py
@@ -1,12 +1,24 @@
import asyncio
import contextvars
from functools import partial
-from typing import Any, Coroutine, Dict, Iterable, List, Literal, Optional, Type, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Coroutine,
+ Dict,
+ Iterable,
+ List,
+ Literal,
+ Optional,
+ Type,
+ Union,
+)
import httpx
from pydantic import BaseModel
import litellm
+from litellm._logging import verbose_logger
from litellm.constants import request_timeout
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig
@@ -22,15 +34,27 @@ from litellm.types.llms.openai import (
ResponseInputParam,
ResponsesAPIOptionalRequestParams,
ResponsesAPIResponse,
- ResponseText,
ToolChoice,
ToolParam,
)
+
+# Handle ResponseText import with fallback
+if TYPE_CHECKING:
+ from litellm.types.llms.openai import ResponseText
+else:
+ ResponseText = str # Fallback for ResponseText import
from litellm.types.responses.main import *
from litellm.types.router import GenericLiteLLMParams
from litellm.utils import ProviderConfigManager, client
-from .streaming_iterator import BaseResponsesAPIStreamingIterator
+if TYPE_CHECKING:
+ from mcp.types import Tool as MCPTool
+else:
+ MCPTool = Any
+
+from .streaming_iterator import (
+ BaseResponsesAPIStreamingIterator,
+)
####### ENVIRONMENT VARIABLES ###################
# Initialize any necessary instances or variables here
@@ -141,17 +165,15 @@ async def aresponses_api_with_mcp(
other_tools,
) = LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(tools)
- # Get available tools from MCP manager if we have MCP tools
- openai_tools = []
- mcp_tools_fetched = []
- if mcp_tools_with_litellm_proxy:
- user_api_key_auth = kwargs.get("user_api_key_auth")
- mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(
- user_api_key_auth
- )
- openai_tools = LiteLLM_Proxy_MCP_Handler._transform_mcp_tools_to_openai(
- mcp_tools_fetched
- )
+ # Process MCP tools through the complete pipeline (fetch + filter + deduplicate + transform)
+ user_api_key_auth = kwargs.get("user_api_key_auth")
+
+ # Get original MCP tools (for events) and OpenAI tools (for LLM) by reusing existing methods
+ original_mcp_tools = await LiteLLM_Proxy_MCP_Handler._process_mcp_tools_without_openai_transform(
+ user_api_key_auth=user_api_key_auth,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy
+ )
+ openai_tools = LiteLLM_Proxy_MCP_Handler._transform_mcp_tools_to_openai(original_mcp_tools)
# Combine with other tools
all_tools = openai_tools + other_tools if (openai_tools or other_tools) else None
@@ -182,23 +204,68 @@ async def aresponses_api_with_mcp(
**kwargs,
}
+ # Handle MCP streaming if requested
+ if stream and mcp_tools_with_litellm_proxy:
+ # Generate MCP discovery events using the already processed tools
+ import uuid
+
+ from litellm.responses.mcp.mcp_streaming_iterator import (
+ create_mcp_list_tools_events,
+ )
+
+ base_item_id = f"mcp_{uuid.uuid4().hex[:8]}"
+ mcp_discovery_events = await create_mcp_list_tools_events(
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ user_api_key_auth=user_api_key_auth,
+ base_item_id=base_item_id,
+ pre_processed_mcp_tools=original_mcp_tools
+ )
+
+ return LiteLLM_Proxy_MCP_Handler._create_mcp_streaming_response(
+ input=input,
+ model=model,
+ all_tools=all_tools,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ mcp_discovery_events=mcp_discovery_events,
+ call_params=call_params,
+ previous_response_id=previous_response_id,
+ **kwargs
+ )
+
+ # Determine if we should auto-execute tools
+ should_auto_execute = (
+ bool(mcp_tools_with_litellm_proxy)
+ and LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy
+ )
+ )
+
+ # Prepare parameters for the initial call
+ initial_call_params = LiteLLM_Proxy_MCP_Handler._prepare_initial_call_params(
+ call_params=call_params,
+ should_auto_execute=should_auto_execute
+ )
+
+ #########################################################
# Make initial response API call
- # TODO: if should auto-execute is True, then this first response should not be streamed
+ #########################################################
response = await aresponses(
input=input,
model=model,
tools=all_tools,
previous_response_id=previous_response_id,
- **call_params,
+ **initial_call_params,
)
- # Check if we need to auto-execute tool calls (only for non-streaming responses)
+ verbose_logger.debug("Initial response %s", response)
+
+ #########################################################
+ # Auto-Execute Tools Handling
+ # If auto-execute tools is True, then we need to execute the tool calls
+ #########################################################
if (
- mcp_tools_with_litellm_proxy
+ should_auto_execute
and isinstance(response, ResponsesAPIResponse)
- and LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(
- mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy
- )
): # type: ignore
tool_calls = LiteLLM_Proxy_MCP_Handler._extract_tool_calls_from_response(
response=response
@@ -217,20 +284,49 @@ async def aresponses_api_with_mcp(
response=response, tool_results=tool_results, original_input=input
)
+ # Prepare parameters for follow-up call (restores original stream setting)
+ follow_up_call_params = LiteLLM_Proxy_MCP_Handler._prepare_follow_up_call_params(
+ call_params=call_params,
+ original_stream_setting=stream or False
+ )
+
+ # Create tool execution events for streaming if needed
+ tool_execution_events = []
+ if stream:
+ tool_execution_events = LiteLLM_Proxy_MCP_Handler._create_tool_execution_events(
+ tool_calls=tool_calls,
+ tool_results=tool_results
+ )
+
final_response = await LiteLLM_Proxy_MCP_Handler._make_follow_up_call(
follow_up_input=follow_up_input,
model=model,
all_tools=all_tools,
response_id=response.id,
- **call_params,
+ **follow_up_call_params,
)
- # Add custom output elements to the final response
- if isinstance(final_response, ResponsesAPIResponse):
+ # If streaming and we have tool execution events, wrap the response
+ if stream and tool_execution_events and (hasattr(final_response, '__aiter__') or hasattr(final_response, '__iter__')):
+ from litellm.responses.mcp.mcp_streaming_iterator import (
+ MCPEnhancedStreamingIterator,
+ )
+ final_response = MCPEnhancedStreamingIterator(
+ base_iterator=final_response,
+ mcp_events=tool_execution_events
+ )
+
+ # Add custom output elements to the final response (for non-streaming)
+ elif isinstance(final_response, ResponsesAPIResponse):
+ # Fetch MCP tools again for output elements (without OpenAI transformation)
+ mcp_tools_for_output = await LiteLLM_Proxy_MCP_Handler._process_mcp_tools_without_openai_transform(
+ user_api_key_auth=user_api_key_auth,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy
+ )
final_response = (
LiteLLM_Proxy_MCP_Handler._add_mcp_output_elements_to_response(
response=final_response,
- mcp_tools_fetched=mcp_tools_fetched,
+ mcp_tools_fetched=mcp_tools_for_output,
tool_results=tool_results,
)
)
@@ -401,13 +497,13 @@ def responses(
Synchronous version of the Responses API.
Uses the synchronous HTTP handler to make requests.
"""
+ local_vars = locals()
from litellm.responses.mcp.litellm_proxy_mcp_handler import (
LiteLLM_Proxy_MCP_Handler,
)
- local_vars = locals()
try:
- litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.pop("litellm_logging_obj") # type: ignore
litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)
_is_async = kwargs.pop("aresponses", False) is True
@@ -448,7 +544,32 @@ def responses(
#########################################################
if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(tools=tools):
return aresponses_api_with_mcp(
- **local_vars,
+ input=input,
+ model=model,
+ include=include,
+ instructions=instructions,
+ max_output_tokens=max_output_tokens,
+ prompt=prompt,
+ metadata=metadata,
+ parallel_tool_calls=parallel_tool_calls,
+ previous_response_id=previous_response_id,
+ reasoning=reasoning,
+ store=store,
+ background=background,
+ stream=stream,
+ temperature=temperature,
+ text=text,
+ tool_choice=tool_choice,
+ tools=tools,
+ top_p=top_p,
+ truncation=truncation,
+ user=user,
+ extra_headers=extra_headers,
+ extra_query=extra_query,
+ extra_body=extra_body,
+ timeout=timeout,
+ custom_llm_provider=custom_llm_provider,
+ **kwargs,
)
# get provider config
diff --git a/litellm/responses/mcp/litellm_proxy_mcp_handler.py b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
index 5c72b9b6521..7a9a21a9690 100644
--- a/litellm/responses/mcp/litellm_proxy_mcp_handler.py
+++ b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
@@ -1,10 +1,17 @@
-from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union
from litellm._logging import verbose_logger
from litellm.responses.main import aresponses
from litellm.responses.streaming_iterator import BaseResponsesAPIStreamingIterator
from litellm.types.llms.openai import ResponsesAPIResponse, ToolParam
+if TYPE_CHECKING:
+ from mcp.types import Tool as MCPTool
+else:
+ MCPTool = Any
+
+LITELLM_PROXY_MCP_SERVER_URL = "litellm_proxy"
+LITELLM_PROXY_MCP_SERVER_URL_PREFIX = f"{LITELLM_PROXY_MCP_SERVER_URL}/mcp/"
class LiteLLM_Proxy_MCP_Handler:
"""
@@ -22,7 +29,7 @@ class LiteLLM_Proxy_MCP_Handler:
for tool in tools:
if (isinstance(tool, dict) and
tool.get("type") == "mcp" and
- tool.get("server_url") == "litellm_proxy"):
+ tool.get("server_url", "").startswith(LITELLM_PROXY_MCP_SERVER_URL)):
return True
return False
@@ -41,7 +48,7 @@ class LiteLLM_Proxy_MCP_Handler:
for tool in tools:
if (isinstance(tool, dict) and
tool.get("type") == "mcp" and
- tool.get("server_url") == "litellm_proxy"):
+ tool.get("server_url", "").startswith(LITELLM_PROXY_MCP_SERVER_URL)):
mcp_tools_with_litellm_proxy.append(tool)
else:
other_tools.append(tool)
@@ -49,13 +56,167 @@ class LiteLLM_Proxy_MCP_Handler:
return mcp_tools_with_litellm_proxy, other_tools
@staticmethod
- async def _get_mcp_tools_from_manager(user_api_key_auth: Any) -> List[Any]:
- """Get available tools from the MCP server manager."""
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
- global_mcp_server_manager,
+ async def _get_mcp_tools_from_manager(
+ user_api_key_auth: Any,
+ mcp_tools_with_litellm_proxy: Optional[Iterable[ToolParam]],
+ ) -> List[MCPTool]:
+ """
+ Get available tools from the MCP server manager.
+
+ Args:
+ user_api_key_auth: User authentication info for access control
+ mcp_tools_with_litellm_proxy: ToolParam objects with server_url starting with "litellm_proxy"
+ """
+ from litellm.proxy._experimental.mcp_server.server import (
+ _get_tools_from_mcp_servers,
+ )
+ mcp_servers: List[str] = []
+ if mcp_tools_with_litellm_proxy:
+ for _tool in mcp_tools_with_litellm_proxy:
+ # if user specifies servers as server_url: litellm_proxy/mcp/zapier,github then return zapier,github
+ if _tool.get("server_url", "").startswith(LITELLM_PROXY_MCP_SERVER_URL_PREFIX):
+ mcp_servers.append(_tool.get("server_url", "").split("/")[-1])
+
+ return await _get_tools_from_mcp_servers(
+ user_api_key_auth=user_api_key_auth,
+ mcp_auth_header=None,
+ mcp_servers=mcp_servers,
+ mcp_server_auth_headers=None,
+ mcp_protocol_version=None,
)
+
+ @staticmethod
+ def _deduplicate_mcp_tools(mcp_tools: List[Any]) -> List[Any]:
+ """
+ Deduplicate MCP tools by name, keeping the first occurrence of each tool.
+
+ Args:
+ mcp_tools: List of MCP tools that may contain duplicates
+
+ Returns:
+ List of deduplicated MCP tools
+ """
+ seen_names = set()
+ deduplicated_tools = []
- return await global_mcp_server_manager.list_tools(user_api_key_auth=user_api_key_auth)
+ for tool in mcp_tools:
+ tool_name = getattr(tool, 'name', None) if hasattr(tool, 'name') else tool.get('name') if isinstance(tool, dict) else None
+ if tool_name and tool_name not in seen_names:
+ seen_names.add(tool_name)
+ deduplicated_tools.append(tool)
+
+ return deduplicated_tools
+
+ @staticmethod
+ def _filter_mcp_tools_by_allowed_tools(
+ mcp_tools: List[Any],
+ mcp_tools_with_litellm_proxy: List[ToolParam]
+ ) -> List[Any]:
+ """Filter MCP tools based on allowed_tools parameter from the original tool configs."""
+ # Collect all allowed tool names from all MCP tool configs
+ allowed_tool_names = set()
+ for tool_config in mcp_tools_with_litellm_proxy:
+ if isinstance(tool_config, dict) and "allowed_tools" in tool_config:
+ allowed_tools = tool_config.get("allowed_tools", [])
+ if isinstance(allowed_tools, list):
+ allowed_tool_names.update(allowed_tools)
+
+ # If no allowed_tools specified, return all tools
+ if not allowed_tool_names:
+ return mcp_tools
+
+ # Filter tools based on allowed names
+ filtered_tools = []
+ for mcp_tool in mcp_tools:
+ tool_name = getattr(mcp_tool, 'name', None) if hasattr(mcp_tool, 'name') else mcp_tool.get('name') if isinstance(mcp_tool, dict) else None
+ if tool_name and tool_name in allowed_tool_names:
+ filtered_tools.append(mcp_tool)
+
+ return filtered_tools
+
+ @staticmethod
+ async def _process_mcp_tools_to_openai_format(
+ user_api_key_auth: Any,
+ mcp_tools_with_litellm_proxy: List[ToolParam]
+ ) -> List[Any]:
+ """
+ Centralized method to process MCP tools through the complete pipeline:
+ 1. Fetch tools from MCP manager
+ 2. Filter based on allowed_tools parameter
+ 3. Deduplicate tools by name
+ 4. Transform to OpenAI format
+
+ Args:
+ user_api_key_auth: User authentication info for access control
+ mcp_tools_with_litellm_proxy: ToolParam objects with server_url starting with "litellm_proxy"
+
+ Returns:
+ List of tools in OpenAI format ready to be sent to the LLM
+ """
+ if not mcp_tools_with_litellm_proxy:
+ return []
+
+ # Step 1: Fetch MCP tools from manager
+ mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(
+ user_api_key_auth=user_api_key_auth,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ )
+
+ # Step 2: Filter tools based on allowed_tools parameter
+ filtered_mcp_tools = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mcp_tools_fetched,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ )
+
+ # Step 3: Deduplicate tools after filtering
+ deduplicated_mcp_tools = LiteLLM_Proxy_MCP_Handler._deduplicate_mcp_tools(
+ filtered_mcp_tools
+ )
+
+ # Step 4: Transform to OpenAI format
+ openai_tools = LiteLLM_Proxy_MCP_Handler._transform_mcp_tools_to_openai(
+ deduplicated_mcp_tools
+ )
+
+ return openai_tools
+
+ @staticmethod
+ async def _process_mcp_tools_without_openai_transform(
+ user_api_key_auth: Any,
+ mcp_tools_with_litellm_proxy: List[ToolParam]
+ ) -> List[Any]:
+ """
+ Process MCP tools through filtering and deduplication pipeline without OpenAI transformation.
+ This is useful for cases where we need the original MCP tool objects (e.g., for events).
+
+ Args:
+ user_api_key_auth: User authentication info for access control
+ mcp_tools_with_litellm_proxy: ToolParam objects with server_url starting with "litellm_proxy"
+
+ Returns:
+ List of filtered and deduplicated MCP tools in their original format
+ """
+ if not mcp_tools_with_litellm_proxy:
+ return []
+
+ # Step 1: Fetch MCP tools from manager
+ mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(
+ user_api_key_auth=user_api_key_auth,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ )
+
+ # Step 2: Filter tools based on allowed_tools parameter
+ filtered_mcp_tools = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mcp_tools_fetched,
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ )
+
+ # Step 3: Deduplicate tools after filtering
+ deduplicated_mcp_tools = LiteLLM_Proxy_MCP_Handler._deduplicate_mcp_tools(
+ filtered_mcp_tools
+ )
+
+ return deduplicated_mcp_tools
@staticmethod
def _transform_mcp_tools_to_openai(mcp_tools: List[Any]) -> List[Any]:
@@ -178,11 +339,12 @@ class LiteLLM_Proxy_MCP_Handler:
user_api_key_auth: Any
) -> List[Dict[str, Any]]:
"""Execute tool calls and return results."""
+ from fastapi import HTTPException
+
+ from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
- from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException
- from fastapi import HTTPException
tool_results = []
tool_call_id: Optional[str] = None
@@ -331,6 +493,170 @@ class LiteLLM_Proxy_MCP_Handler:
**call_params
)
+ @staticmethod
+ def _create_mcp_streaming_response(
+ input: Union[str, Any],
+ model: str,
+ all_tools: Optional[List[Any]],
+ mcp_tools_with_litellm_proxy: List[Any],
+ mcp_discovery_events: List[Any],
+ call_params: Dict[str, Any],
+ previous_response_id: Optional[str],
+ **kwargs
+ ) -> Any:
+ """
+ Create MCP enhanced streaming response that handles the full MCP workflow.
+
+ This creates a streaming iterator that:
+ 1. Immediately emits MCP discovery events
+ 2. Makes the LLM call and streams the response
+ 3. Handles tool execution and follow-up calls
+ """
+ from litellm.responses.mcp.mcp_streaming_iterator import (
+ MCPEnhancedStreamingIterator,
+ )
+
+ # Build the complete request parameters by merging all sources
+ request_params = LiteLLM_Proxy_MCP_Handler._build_request_params(
+ input=input,
+ model=model,
+ all_tools=all_tools,
+ call_params=call_params,
+ previous_response_id=previous_response_id,
+ **kwargs
+ )
+
+ # Create the enhanced streaming iterator that will handle everything
+ return MCPEnhancedStreamingIterator(
+ base_iterator=None, # Will be created internally
+ mcp_events=mcp_discovery_events, # Pre-generated MCP discovery events
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,
+ user_api_key_auth=kwargs.get("user_api_key_auth"),
+ original_request_params=request_params
+ )
+
+ @staticmethod
+ def _build_request_params(
+ input: Union[str, Any],
+ model: str,
+ all_tools: Optional[List[Any]],
+ call_params: Dict[str, Any],
+ previous_response_id: Optional[str],
+ **kwargs
+ ) -> Dict[str, Any]:
+ """
+ Build a clean request parameters dictionary for MCP streaming.
+
+ Combines input, model, tools with call_params and additional kwargs
+ in a clean, maintainable way.
+ """
+ # Start with the core required parameters
+ request_params = {
+ 'input': input,
+ 'model': model,
+ 'tools': all_tools,
+ }
+
+ # Add previous_response_id if provided
+ if previous_response_id is not None:
+ request_params['previous_response_id'] = previous_response_id
+
+ # Merge in all call_params (which contains most of the API parameters)
+ request_params.update(call_params)
+
+ # Merge in any additional kwargs
+ request_params.update(kwargs)
+
+ return request_params
+
+ @staticmethod
+ def _create_tool_execution_events(
+ tool_calls: List[Any],
+ tool_results: List[Dict[str, Any]]
+ ) -> List[Any]:
+ """
+ Create MCP tool execution events for streaming.
+
+ Args:
+ tool_calls: List of tool calls from the LLM response
+ tool_results: List of tool execution results
+
+ Returns:
+ List of MCP tool execution events for streaming
+ """
+ import uuid
+
+ from litellm.responses.mcp.mcp_streaming_iterator import create_mcp_call_events
+
+ tool_execution_events = []
+
+ # Create events for each tool execution
+ for tool_result in tool_results:
+ tool_call_id = tool_result.get("tool_call_id", "unknown")
+ result_text = tool_result.get("result", "")
+
+ # Extract tool name and arguments from tool calls
+ tool_name = "unknown"
+ tool_arguments = "{}"
+ for tool_call in tool_calls:
+ name, args, call_id = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
+ if call_id == tool_call_id:
+ tool_name = name or "unknown"
+ tool_arguments = args or "{}"
+ break
+
+ execution_events = create_mcp_call_events(
+ tool_name=tool_name,
+ tool_call_id=tool_call_id,
+ arguments=tool_arguments, # Use actual arguments
+ result=result_text,
+ base_item_id=f"mcp_{uuid.uuid4().hex[:8]}", # Unique ID for each tool call
+ sequence_start=len(tool_execution_events) + 1
+ )
+ tool_execution_events.extend(execution_events)
+
+ return tool_execution_events
+
+ @staticmethod
+ def _prepare_initial_call_params(
+ call_params: Dict[str, Any],
+ should_auto_execute: bool
+ ) -> Dict[str, Any]:
+ """
+ Prepare call parameters for the initial LLM call.
+
+ For auto-execute scenarios, we need to disable streaming for the initial call
+ so we can process the tool calls before streaming the final response.
+ """
+ initial_params = call_params.copy()
+
+ if should_auto_execute:
+ # Disable streaming for initial call when auto-executing tools
+ initial_params["stream"] = False
+
+ return initial_params
+
+ @staticmethod
+ def _prepare_follow_up_call_params(
+ call_params: Dict[str, Any],
+ original_stream_setting: bool
+ ) -> Dict[str, Any]:
+ """
+ Prepare call parameters for the follow-up LLM call after tool execution.
+
+ Restores the original streaming setting and removes tool_choice since
+ we're now providing tool results, not requesting tool calls.
+ """
+ follow_up_params = call_params.copy()
+
+ # Restore original streaming setting for follow-up call
+ follow_up_params["stream"] = original_stream_setting
+
+ # Remove tool_choice since we're providing results, not requesting tool calls
+ follow_up_params.pop("tool_choice", None)
+
+ return follow_up_params
+
@staticmethod
def _add_mcp_output_elements_to_response(
response: ResponsesAPIResponse,
diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.py
new file mode 100644
index 00000000000..bf6a9182522
--- /dev/null
+++ b/litellm/responses/mcp/mcp_streaming_iterator.py
@@ -0,0 +1,604 @@
+import uuid
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ List,
+ Optional,
+ Union,
+ cast,
+)
+
+from litellm._logging import verbose_logger
+from litellm.responses.streaming_iterator import (
+ BaseResponsesAPIStreamingIterator,
+)
+from litellm.types.llms.openai import (
+ MCPCallArgumentsDeltaEvent,
+ MCPCallArgumentsDoneEvent,
+ MCPCallCompletedEvent,
+ MCPCallFailedEvent,
+ MCPCallInProgressEvent,
+ MCPListToolsCompletedEvent,
+ MCPListToolsFailedEvent,
+ MCPListToolsInProgressEvent,
+ ResponsesAPIResponse,
+ ResponsesAPIStreamEvents,
+ ResponsesAPIStreamingResponse,
+ ToolParam,
+)
+
+if TYPE_CHECKING:
+ from mcp.types import Tool as MCPTool
+else:
+ MCPTool = Any
+
+
+async def create_mcp_list_tools_events(
+ mcp_tools_with_litellm_proxy: List[ToolParam],
+ user_api_key_auth: Any,
+ base_item_id: str,
+ pre_processed_mcp_tools: List[Any]
+) -> List[ResponsesAPIStreamingResponse]:
+ """Create MCP discovery events using pre-processed tools from the parent"""
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import (
+ LiteLLM_Proxy_MCP_Handler,
+ )
+
+ events = []
+
+ try:
+ # Extract MCP server names
+ mcp_servers = []
+ for tool in mcp_tools_with_litellm_proxy:
+ if isinstance(tool, dict) and "server_url" in tool:
+ server_url = tool["server_url"]
+ if server_url.startswith("litellm_proxy/mcp/"):
+ server_name = server_url.split("/")[-1]
+ mcp_servers.append(server_name)
+
+ # Emit list tools in progress event
+ in_progress_event = MCPListToolsInProgressEvent(
+ type=ResponsesAPIStreamEvents.MCP_LIST_TOOLS_IN_PROGRESS,
+ sequence_number=1,
+ output_index=0,
+ item_id=base_item_id,
+ )
+ events.append(in_progress_event)
+
+ # Use the pre-processed MCP tools that were already fetched, filtered, and deduplicated by the parent
+ filtered_mcp_tools = pre_processed_mcp_tools
+
+ # Convert tools to dict format for the event
+ mcp_tools_dict = []
+ for tool in filtered_mcp_tools:
+ if hasattr(tool, 'model_dump'):
+ mcp_tools_dict.append(tool.model_dump())
+ elif hasattr(tool, '__dict__'):
+ mcp_tools_dict.append(tool.__dict__)
+ else:
+ mcp_tools_dict.append({"name": getattr(tool, 'name', str(tool))})
+
+ # Emit list tools completed event
+ completed_event = MCPListToolsCompletedEvent(
+ type=ResponsesAPIStreamEvents.MCP_LIST_TOOLS_COMPLETED,
+ sequence_number=2,
+ output_index=0,
+ item_id=base_item_id,
+ )
+ events.append(completed_event)
+
+ # Add output_item.done event with the actual tools list (matching OpenAI format)
+ from litellm.types.llms.openai import OutputItemDoneEvent
+
+ # Extract server label from the first MCP tool config
+ server_label = ""
+ if mcp_tools_with_litellm_proxy:
+ first_tool = mcp_tools_with_litellm_proxy[0]
+ if isinstance(first_tool, dict):
+ server_label = first_tool.get("server_label", "")
+
+ # Format tools for OpenAI output_item.done format
+ formatted_tools = []
+ for tool in filtered_mcp_tools:
+ tool_dict = {
+ "name": getattr(tool, 'name', 'unknown'),
+ "description": getattr(tool, 'description', ''),
+ "annotations": {"read_only": False},
+ }
+
+ # Add input_schema if available
+ if hasattr(tool, 'inputSchema'):
+ tool_dict["input_schema"] = tool.inputSchema
+ elif hasattr(tool, 'input_schema'):
+ tool_dict["input_schema"] = tool.input_schema
+
+ formatted_tools.append(tool_dict)
+
+ # Create the output_item.done event with MCP tools list
+ output_item_done_event = OutputItemDoneEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
+ output_index=0,
+ item={
+ "id": base_item_id,
+ "type": "mcp_list_tools",
+ "server_label": server_label,
+ "tools": formatted_tools
+ }
+ )
+ events.append(output_item_done_event)
+
+ verbose_logger.debug(f"Created {len(events)} MCP discovery events")
+
+ except Exception as e:
+ verbose_logger.error(f"Error creating MCP list tools events: {e}")
+ import traceback
+ traceback.print_exc()
+
+ # Emit failed event on error
+ failed_event = MCPListToolsFailedEvent(
+ type=ResponsesAPIStreamEvents.MCP_LIST_TOOLS_FAILED,
+ sequence_number=2,
+ output_index=0,
+ item_id=base_item_id,
+ )
+ events.append(failed_event)
+
+ # Still emit output_item.done event even on failure (with empty tools list)
+ from litellm.types.llms.openai import OutputItemDoneEvent
+
+ output_item_done_event = OutputItemDoneEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
+ output_index=0,
+ item={
+ "id": base_item_id,
+ "type": "mcp_list_tools",
+ "server_label": "",
+ "tools": []
+ }
+ )
+ events.append(output_item_done_event)
+
+ return events
+
+
+def create_mcp_call_events(
+ tool_name: str,
+ tool_call_id: str,
+ arguments: str,
+ result: Optional[str] = None,
+ base_item_id: Optional[str] = None,
+ sequence_start: int = 1
+) -> List[ResponsesAPIStreamingResponse]:
+ """Create MCP call events following OpenAI's specification"""
+ events = []
+ item_id = base_item_id or f"mcp_{uuid.uuid4().hex[:8]}"
+
+ # MCP call in progress event
+ in_progress_event = MCPCallInProgressEvent(
+ type=ResponsesAPIStreamEvents.MCP_CALL_IN_PROGRESS,
+ sequence_number=sequence_start,
+ output_index=0,
+ item_id=item_id,
+ )
+ events.append(in_progress_event)
+
+ # MCP call arguments delta event (streaming the arguments)
+ arguments_delta_event = MCPCallArgumentsDeltaEvent(
+ type=ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DELTA,
+ output_index=0,
+ item_id=item_id,
+ delta=arguments, # JSON string with arguments
+ sequence_number=sequence_start + 1,
+ )
+ events.append(arguments_delta_event)
+
+ # MCP call arguments done event
+ arguments_done_event = MCPCallArgumentsDoneEvent(
+ type=ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DONE,
+ output_index=0,
+ item_id=item_id,
+ arguments=arguments, # Complete JSON string with finalized arguments
+ sequence_number=sequence_start + 2,
+ )
+ events.append(arguments_done_event)
+
+ # MCP call completed event (or failed if result indicates failure)
+ if result is not None:
+ completed_event = MCPCallCompletedEvent(
+ type=ResponsesAPIStreamEvents.MCP_CALL_COMPLETED,
+ sequence_number=sequence_start + 3,
+ item_id=item_id,
+ output_index=0,
+ )
+ events.append(completed_event)
+
+ # Add output_item.done event with the tool call result
+ from litellm.types.llms.openai import OutputItemDoneEvent
+
+ output_item_done_event = OutputItemDoneEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
+ output_index=0,
+ item={
+ "id": item_id,
+ "type": "mcp_call",
+ "approval_request_id": f"mcpr_{uuid.uuid4().hex[:8]}",
+ "arguments": arguments,
+ "error": None,
+ "name": tool_name,
+ "output": result,
+ "server_label": "litellm"
+ },
+ )
+ events.append(output_item_done_event)
+ else:
+ failed_event = MCPCallFailedEvent(
+ type=ResponsesAPIStreamEvents.MCP_CALL_FAILED,
+ sequence_number=sequence_start + 3,
+ item_id=item_id,
+ output_index=0,
+ )
+ events.append(failed_event)
+
+ return events
+
+
+class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):
+ """
+ A complete MCP streaming iterator that handles the entire flow:
+ 1. Immediately emits MCP discovery events
+ 2. Makes the first LLM call and streams its response
+ 3. Handles tool execution and follow-up calls for auto-execute tools
+ 4. Emits tool execution events in the stream
+ """
+
+ def __init__(
+ self,
+ base_iterator: Any, # Can be None - will be created internally
+ mcp_events: List[ResponsesAPIStreamingResponse],
+ mcp_tools_with_litellm_proxy: Optional[List[Any]] = None,
+ user_api_key_auth: Any = None,
+ original_request_params: Optional[Dict[str, Any]] = None
+ ):
+ # MCP setup
+ self.mcp_tools_with_litellm_proxy = mcp_tools_with_litellm_proxy or []
+ self.user_api_key_auth = user_api_key_auth
+ self.original_request_params = original_request_params or {}
+ self.should_auto_execute = self._should_auto_execute_tools()
+
+ # Streaming state management
+ self.phase = "mcp_discovery" # mcp_discovery -> initial_response -> tool_execution -> follow_up_response -> finished
+ self.finished = False
+
+ # Event queues and generation flags
+ self.mcp_discovery_events: List[ResponsesAPIStreamingResponse] = mcp_events # Pre-generated MCP discovery events
+ self.tool_execution_events: List[ResponsesAPIStreamingResponse] = []
+ self.mcp_discovery_generated = True # Events are already generated
+ self.mcp_events = mcp_events # Store the initial MCP events for backward compatibility
+
+ # Iterator references
+ self.base_iterator: Optional[Union[Any, ResponsesAPIResponse]] = base_iterator # Will be created when needed
+ self.follow_up_iterator: Optional[Any] = None
+
+ # Response collection for tool execution
+ self.collected_response: Optional[ResponsesAPIResponse] = None
+
+ # Set up model metadata (will be updated when we get the real iterator)
+ self.model = self.original_request_params.get('model', 'unknown')
+ self.litellm_metadata = {}
+ self.custom_llm_provider = self.original_request_params.get('custom_llm_provider', None)
+
+ # Mark as async iterator
+ self.is_async = True
+
+ def _should_auto_execute_tools(self) -> bool:
+ """Check if tools should be auto-executed"""
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import (
+ LiteLLM_Proxy_MCP_Handler,
+ )
+ return LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(
+ self.mcp_tools_with_litellm_proxy
+ )
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self) -> ResponsesAPIStreamingResponse:
+ """
+ Phase-based streaming:
+ 1. mcp_discovery - Emit MCP discovery events
+ 2. initial_response - Stream the first LLM response
+ 3. tool_execution - Emit tool execution events
+ 4. follow_up_response - Stream the follow-up response
+ 5. finished - End iteration
+ """
+
+ # Phase 1: MCP Discovery Events
+ if self.phase == "mcp_discovery":
+ # Generate MCP discovery events if not already done
+ # MCP discovery events are already generated and available
+
+ # Emit MCP discovery events
+ if self.mcp_discovery_events:
+ return self.mcp_discovery_events.pop(0)
+
+ # All MCP discovery events emitted, move to next phase
+ verbose_logger.debug("MCP discovery phase complete, transitioning to initial_response")
+ self.phase = "initial_response"
+ await self._create_initial_response_iterator()
+ # Fall through to process the initial response immediately
+
+ # Phase 2: Initial Response Stream
+ if self.phase == "initial_response":
+ if self.base_iterator:
+ # Check if base_iterator is actually iterable
+ if hasattr(self.base_iterator, '__anext__'):
+ try:
+ chunk = await cast(Any, self.base_iterator).__anext__() # type: ignore[attr-defined]
+
+ # If auto-execution is enabled, check for completed responses
+ if self.should_auto_execute and self._is_response_completed(chunk):
+ # Collect the response for tool execution
+ response_obj = getattr(chunk, 'response', None)
+ if isinstance(response_obj, ResponsesAPIResponse):
+ self.collected_response = response_obj
+ # Move to tool execution phase after emitting this chunk
+ self.phase = "tool_execution"
+ await self._generate_tool_execution_events()
+
+ return chunk
+ except StopAsyncIteration:
+ # Initial response ended, move to next phase
+ if self.should_auto_execute and self.collected_response:
+ self.phase = "tool_execution"
+ await self._generate_tool_execution_events()
+ else:
+ self.phase = "finished"
+ raise
+ else:
+ # base_iterator is not async iterable (likely a ResponsesAPIResponse)
+ # Collect it for tool execution if needed
+ if self.should_auto_execute and isinstance(self.base_iterator, ResponsesAPIResponse):
+ self.collected_response = self.base_iterator
+ self.phase = "tool_execution"
+ await self._generate_tool_execution_events()
+ else:
+ self.phase = "finished"
+ raise StopAsyncIteration
+
+ # Phase 3: Tool Execution Events
+ if self.phase == "tool_execution":
+ # Emit any queued tool execution events
+ if self.tool_execution_events:
+ return self.tool_execution_events.pop(0)
+
+ # Move to follow-up response phase
+ self.phase = "follow_up_response"
+ await self._create_follow_up_iterator()
+
+ # Phase 4: Follow-up Response Stream
+ if self.phase == "follow_up_response":
+ if self.follow_up_iterator:
+ try:
+ return await cast(Any, self.follow_up_iterator).__anext__() # type: ignore[attr-defined]
+ except StopAsyncIteration:
+ self.phase = "finished"
+ raise
+ else:
+ self.phase = "finished"
+ raise StopAsyncIteration
+
+ # Phase 5: Finished
+ if self.phase == "finished":
+ raise StopAsyncIteration
+
+ # Should not reach here
+ raise StopAsyncIteration
+
+ def _is_response_completed(self, chunk: ResponsesAPIStreamingResponse) -> bool:
+ """Check if this chunk indicates the response is completed"""
+ from litellm.types.llms.openai import ResponsesAPIStreamEvents
+ return getattr(chunk, 'type', None) == ResponsesAPIStreamEvents.RESPONSE_COMPLETED
+
+
+ async def _create_initial_response_iterator(self) -> None:
+ """Create the initial response iterator by making the first LLM call"""
+ try:
+ # Import the core aresponses function that doesn't have MCP logic
+ from litellm.responses.main import aresponses
+
+ # Make the initial response API call - but avoid the MCP wrapper
+ params = self.original_request_params.copy()
+ params['stream'] = True # Ensure streaming
+
+ # Use the pre-fetched all_tools from original_request_params (no re-processing needed)
+ params_for_llm = {}
+ for key, value in params.items():
+ params_for_llm[key] = value # Copy all params as-is since tools are already processed
+
+ tools_count = len(params_for_llm.get('tools', []))
+ verbose_logger.debug(f"Making LLM call with {tools_count} tools")
+ response = await aresponses(**params_for_llm)
+
+ # Set the base iterator
+ if hasattr(response, '__aiter__') or hasattr(response, '__iter__'):
+ self.base_iterator = response
+ # Copy metadata from the real iterator
+ self.model = getattr(response, 'model', self.model)
+ self.litellm_metadata = getattr(response, 'litellm_metadata', {})
+ self.custom_llm_provider = getattr(response, 'custom_llm_provider', self.custom_llm_provider)
+ verbose_logger.debug(f"Created base iterator: {type(self.base_iterator)}")
+ else:
+ # Non-streaming response - this shouldn't happen but handle it
+ verbose_logger.warning(f"Got non-streaming response: {type(response)}")
+ self.base_iterator = None
+ self.phase = "finished"
+
+ except Exception as e:
+ verbose_logger.error(f"Error creating initial response iterator: {e}")
+ import traceback
+ traceback.print_exc()
+ self.base_iterator = None
+ self.phase = "finished"
+
+ async def _generate_tool_execution_events(self) -> None:
+ """Generate tool execution events and execute tools"""
+ if not self.collected_response:
+ return
+
+ import uuid
+
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import (
+ LiteLLM_Proxy_MCP_Handler,
+ )
+
+ try:
+ # Extract tool calls from the response
+ if self.collected_response is not None:
+ tool_calls = LiteLLM_Proxy_MCP_Handler._extract_tool_calls_from_response(self.collected_response) # type: ignore[arg-type]
+ else:
+ tool_calls = []
+ if not tool_calls:
+ return
+
+ # Create tool execution events
+ base_item_id = f"mcp_{uuid.uuid4().hex[:8]}"
+ for tool_call in tool_calls:
+ tool_name, tool_arguments, tool_call_id = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
+ if tool_name and tool_call_id:
+ # Create MCP call events for this tool execution
+ call_events = create_mcp_call_events(
+ tool_name=tool_name,
+ tool_call_id=tool_call_id,
+ arguments=tool_arguments or "{}", # JSON string with arguments
+ result=None, # Will be set after execution
+ base_item_id=f"mcp_{uuid.uuid4().hex[:8]}",
+ sequence_start=len(self.tool_execution_events) + 1
+ )
+ # Add the in_progress and arguments events (not the completed event yet)
+ self.tool_execution_events.extend(call_events[:-1])
+
+ # Execute the tools
+ tool_results = await LiteLLM_Proxy_MCP_Handler._execute_tool_calls(
+ tool_calls=tool_calls,
+ user_api_key_auth=self.user_api_key_auth
+ )
+
+ # Create completion events and output_item.done events for tool execution
+ for tool_result in tool_results:
+ tool_call_id = tool_result.get("tool_call_id", "unknown")
+ result_text = tool_result.get("result", "")
+
+ # Find matching tool name and arguments
+ tool_name = "unknown"
+ tool_arguments = "{}"
+ for tool_call in tool_calls:
+ name, args, call_id = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)
+ if call_id == tool_call_id:
+ tool_name = name or "unknown"
+ tool_arguments = args or "{}"
+ break
+
+ item_id = f"mcp_{uuid.uuid4().hex[:8]}"
+
+ # Create the completion event
+ completed_event = MCPCallCompletedEvent(
+ type=ResponsesAPIStreamEvents.MCP_CALL_COMPLETED,
+ sequence_number=len(self.tool_execution_events) + 1,
+ item_id=item_id,
+ output_index=0,
+ )
+ self.tool_execution_events.append(completed_event)
+
+ # Create output_item.done event with the tool call result
+ from litellm.types.llms.openai import OutputItemDoneEvent
+
+ output_item_done_event = OutputItemDoneEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
+ output_index=0,
+ item={
+ "id": item_id,
+ "type": "mcp_call",
+ "approval_request_id": f"mcpr_{uuid.uuid4().hex[:8]}",
+ "arguments": tool_arguments,
+ "error": None,
+ "name": tool_name,
+ "output": result_text,
+ "server_label": "litellm" # or extract from tool config
+ },
+ )
+ self.tool_execution_events.append(output_item_done_event)
+
+ # Store tool results for follow-up call
+ self.tool_results = tool_results
+
+ except Exception as e:
+ verbose_logger.error(f"Error in tool execution: {e}")
+ import traceback
+ traceback.print_exc()
+ self.tool_results = []
+
+ async def _create_follow_up_iterator(self) -> None:
+ """Create the follow-up response iterator with tool results"""
+ if not self.collected_response or not hasattr(self, 'tool_results'):
+ return
+
+ from litellm.responses.main import aresponses
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import (
+ LiteLLM_Proxy_MCP_Handler,
+ )
+
+ try:
+ # Create follow-up input
+ if self.collected_response is not None:
+ follow_up_input = LiteLLM_Proxy_MCP_Handler._create_follow_up_input(
+ response=self.collected_response, # type: ignore[arg-type]
+ tool_results=self.tool_results,
+ original_input=self.original_request_params.get('input')
+ )
+
+ # Make follow-up call with streaming
+ follow_up_params = self.original_request_params.copy()
+ follow_up_params.update({
+ 'input': follow_up_input,
+ 'previous_response_id': self.collected_response.id, # type: ignore[attr-defined]
+ 'stream': True
+ })
+ else:
+ return
+ # Remove tool_choice to avoid forcing more tool calls
+ follow_up_params.pop('tool_choice', None)
+
+ follow_up_response = await aresponses(**follow_up_params)
+
+ # Set up the follow-up iterator
+ if hasattr(follow_up_response, '__aiter__'):
+ self.follow_up_iterator = follow_up_response
+
+ except Exception as e:
+ verbose_logger.error(f"Error creating follow-up iterator: {e}")
+ import traceback
+ traceback.print_exc()
+ self.follow_up_iterator = None
+
+
+ def __iter__(self):
+ return self
+
+ def __next__(self) -> ResponsesAPIStreamingResponse:
+ # First, emit any queued MCP events
+ if self.mcp_events: # type: ignore[attr-defined]
+ return self.mcp_events.pop(0) # type: ignore[attr-defined]
+
+ # Then delegate to the base iterator
+ if not self.is_async:
+ try:
+ if self.base_iterator and hasattr(self.base_iterator, '__next__'):
+ return next(cast(Any, self.base_iterator)) # type: ignore[arg-type]
+ else:
+ raise StopIteration
+ except StopIteration:
+ self.finished = True
+ raise
+ else:
+ raise RuntimeError("Cannot use sync iteration on async iterator")
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index c6d126be681..79e3c73dbc1 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -1112,6 +1112,16 @@ class ResponsesAPIStreamEvents(str, Enum):
WEB_SEARCH_CALL_SEARCHING = "response.web_search_call.searching"
WEB_SEARCH_CALL_COMPLETED = "response.web_search_call.completed"
+ # MCP events - matching OpenAI's official specification
+ MCP_LIST_TOOLS_IN_PROGRESS = "response.mcp_list_tools.in_progress"
+ MCP_LIST_TOOLS_COMPLETED = "response.mcp_list_tools.completed"
+ MCP_LIST_TOOLS_FAILED = "response.mcp_list_tools.failed"
+ MCP_CALL_IN_PROGRESS = "response.mcp_call.in_progress"
+ MCP_CALL_ARGUMENTS_DELTA = "response.mcp_call_arguments.delta"
+ MCP_CALL_ARGUMENTS_DONE = "response.mcp_call_arguments.done"
+ MCP_CALL_COMPLETED = "response.mcp_call.completed"
+ MCP_CALL_FAILED = "response.mcp_call.failed"
+
# Error event
ERROR = "error"
@@ -1275,6 +1285,66 @@ class WebSearchCallCompletedEvent(BaseLiteLLMOpenAIResponseObject):
item_id: str
+# MCP List Tools Events
+class MCPListToolsInProgressEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_LIST_TOOLS_IN_PROGRESS]
+ sequence_number: int
+ output_index: int
+ item_id: str
+
+
+class MCPListToolsCompletedEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_LIST_TOOLS_COMPLETED]
+ sequence_number: int
+ output_index: int
+ item_id: str
+
+
+class MCPListToolsFailedEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_LIST_TOOLS_FAILED]
+ sequence_number: int
+ output_index: int
+ item_id: str
+
+
+# MCP Call Events
+class MCPCallInProgressEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_CALL_IN_PROGRESS]
+ sequence_number: int
+ output_index: int
+ item_id: str
+
+
+class MCPCallArgumentsDeltaEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DELTA]
+ output_index: int
+ item_id: str
+ delta: str # JSON string containing partial update to arguments
+ sequence_number: int
+
+
+class MCPCallArgumentsDoneEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DONE]
+ output_index: int
+ item_id: str
+ arguments: str # JSON string containing finalized arguments
+ sequence_number: int
+
+
+class MCPCallCompletedEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_CALL_COMPLETED]
+ sequence_number: int
+ item_id: str
+ output_index: int
+
+
+class MCPCallFailedEvent(BaseLiteLLMOpenAIResponseObject):
+ type: Literal[ResponsesAPIStreamEvents.MCP_CALL_FAILED]
+ sequence_number: int
+ item_id: str
+ output_index: int
+
+
class ErrorEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.ERROR]
code: Optional[str]
@@ -1315,6 +1385,14 @@ ResponsesAPIStreamingResponse = Annotated[
WebSearchCallInProgressEvent,
WebSearchCallSearchingEvent,
WebSearchCallCompletedEvent,
+ MCPListToolsInProgressEvent,
+ MCPListToolsCompletedEvent,
+ MCPListToolsFailedEvent,
+ MCPCallInProgressEvent,
+ MCPCallArgumentsDeltaEvent,
+ MCPCallArgumentsDoneEvent,
+ MCPCallCompletedEvent,
+ MCPCallFailedEvent,
ErrorEvent,
GenericEvent,
],
diff --git a/tests/mcp_tests/test_aresponses_api_with_mcp.py b/tests/mcp_tests/test_aresponses_api_with_mcp.py
index 500bd8bcc06..64bc58eb40c 100644
--- a/tests/mcp_tests/test_aresponses_api_with_mcp.py
+++ b/tests/mcp_tests/test_aresponses_api_with_mcp.py
@@ -6,8 +6,9 @@ from typing import List, Any, cast
sys.path.insert(0, os.path.abspath("../../.."))
# Import required modules
+import litellm
from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler
-from litellm.types.llms.openai import ResponsesAPIResponse, OpenAIMcpServerTool
+from litellm.types.llms.openai import ResponsesAPIResponse, OpenAIMcpServerTool, ToolParam
class MockUserAPIKeyAuth:
@@ -251,3 +252,887 @@ async def test_aresponses_api_with_mcp_mock_integration():
print(f"MCP tools parsed: {len(mcp_parsed)}")
print(f"Other tools parsed: {len(other_parsed)}")
+
+async def test_mcp_allowed_tools_filtering():
+ """
+ Test the allowed_tools filtering functionality for MCP tools.
+ This test verifies that when allowed_tools is specified in MCP tool config,
+ only the allowed tools are passed to the LLM.
+ """
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler
+
+ # Mock MCP tools returned from the server (simulating all available tools)
+ mock_mcp_tools_from_server = [
+ # Mock MCP tool object with name attribute
+ type('MCPTool', (), {
+ 'name': 'search_tiktoken_documentation',
+ 'description': 'Search tiktoken documentation',
+ 'inputSchema': {'type': 'object', 'properties': {'query': {'type': 'string'}}}
+ })(),
+ type('MCPTool', (), {
+ 'name': 'fetch_tiktoken_documentation',
+ 'description': 'Fetch tiktoken documentation',
+ 'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string'}}}
+ })(),
+ type('MCPTool', (), {
+ 'name': 'list_tiktoken_functions',
+ 'description': 'List tiktoken functions',
+ 'inputSchema': {'type': 'object', 'properties': {}}
+ })(),
+ type('MCPTool', (), {
+ 'name': 'get_tiktoken_examples',
+ 'description': 'Get tiktoken examples',
+ 'inputSchema': {'type': 'object', 'properties': {}}
+ })()
+ ]
+
+ # Test Case 1: MCP tool config with allowed_tools specified
+ mcp_tool_config_with_allowed_tools = [
+ {
+ "type": "mcp",
+ "server_label": "gitmcp",
+ "server_url": "https://gitmcp.io/openai/tiktoken",
+ "allowed_tools": ["search_tiktoken_documentation", "fetch_tiktoken_documentation"],
+ "require_approval": "never"
+ }
+ ]
+
+ # Filter tools using the helper function
+ filtered_tools = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mock_mcp_tools_from_server,
+ mcp_tools_with_litellm_proxy=cast(List[ToolParam], mcp_tool_config_with_allowed_tools)
+ )
+
+ # Should only return the 2 allowed tools
+ assert len(filtered_tools) == 2, f"Expected 2 filtered tools, got {len(filtered_tools)}"
+
+ # Check that only allowed tools are included
+ filtered_tool_names = [tool.name for tool in filtered_tools]
+ expected_allowed_tools = ["search_tiktoken_documentation", "fetch_tiktoken_documentation"]
+
+ assert set(filtered_tool_names) == set(expected_allowed_tools), \
+ f"Expected tools {expected_allowed_tools}, got {filtered_tool_names}"
+
+ # Verify excluded tools are not present
+ excluded_tools = ["list_tiktoken_functions", "get_tiktoken_examples"]
+ for excluded_tool in excluded_tools:
+ assert excluded_tool not in filtered_tool_names, \
+ f"Tool {excluded_tool} should have been filtered out"
+
+ print("✓ Test Case 1: allowed_tools filtering works correctly")
+
+ # Test Case 2: MCP tool config without allowed_tools (should return all tools)
+ mcp_tool_config_without_allowed_tools = [
+ {
+ "type": "mcp",
+ "server_label": "gitmcp",
+ "server_url": "https://gitmcp.io/openai/tiktoken",
+ "require_approval": "never"
+ }
+ ]
+
+ filtered_tools_all = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mock_mcp_tools_from_server,
+ mcp_tools_with_litellm_proxy=cast(List[ToolParam], mcp_tool_config_without_allowed_tools)
+ )
+
+ # Should return all 4 tools when no allowed_tools specified
+ assert len(filtered_tools_all) == 4, f"Expected 4 tools when no allowed_tools specified, got {len(filtered_tools_all)}"
+
+ print("✓ Test Case 2: no allowed_tools returns all tools")
+
+ # Test Case 3: Test deduplication of duplicate tools
+ mock_mcp_tools_with_duplicates = [
+ # First instance of duplicate tool
+ type('MCPTool', (), {
+ 'name': 'GitMCP-fetch_litellm_documentation',
+ 'description': 'Fetch entire documentation file from GitHub repository: BerriAI/litellm. Useful for general questions. Always call this tool first if asked about BerriAI/litellm.',
+ 'inputSchema': {'type': 'object', 'properties': {}, 'additionalProperties': False}
+ })(),
+ # Second instance of duplicate tool (should be filtered out)
+ type('MCPTool', (), {
+ 'name': 'GitMCP-fetch_litellm_documentation',
+ 'description': 'Fetch entire documentation file from GitHub repository: BerriAI/litellm. Useful for general questions. Always call this tool first if asked about BerriAI/litellm.',
+ 'inputSchema': {'type': 'object', 'properties': {}, 'additionalProperties': False}
+ })(),
+ # Other unique tools
+ type('MCPTool', (), {
+ 'name': 'GitMCP-search_litellm_documentation',
+ 'description': 'Semantically search within the fetched documentation from GitHub repository: BerriAI/litellm. Useful for specific queries.',
+ 'inputSchema': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query'], 'additionalProperties': False}
+ })(),
+ ]
+
+ mcp_tool_config_with_duplicates = [
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy/mcp",
+ "require_approval": "never",
+ "allowed_tools": ["GitMCP-fetch_litellm_documentation"]
+ }
+ ]
+
+ # First filter by allowed tools
+ filtered_tools_with_duplicates = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mock_mcp_tools_with_duplicates,
+ mcp_tools_with_litellm_proxy=cast(List[ToolParam], mcp_tool_config_with_duplicates)
+ )
+
+ # Then deduplicate the filtered tools
+ filtered_tools_deduplicated = LiteLLM_Proxy_MCP_Handler._deduplicate_mcp_tools(
+ filtered_tools_with_duplicates
+ )
+
+ # Should only return 1 tool (the duplicate should be removed)
+ assert len(filtered_tools_deduplicated) == 1, f"Expected 1 tool after deduplication, got {len(filtered_tools_deduplicated)}"
+
+ # Check that the correct tool is present
+ assert filtered_tools_deduplicated[0].name == "GitMCP-fetch_litellm_documentation", \
+ f"Expected GitMCP-fetch_litellm_documentation, got {filtered_tools_deduplicated[0].name}"
+
+ print("✓ Test Case 3: duplicate tools are properly deduplicated")
+
+ # Test Case 3b: Test standalone deduplication method
+ standalone_deduplicated = LiteLLM_Proxy_MCP_Handler._deduplicate_mcp_tools(mock_mcp_tools_with_duplicates)
+
+ # Should return 2 unique tools (GitMCP-fetch_litellm_documentation and GitMCP-search_litellm_documentation)
+ assert len(standalone_deduplicated) == 2, f"Expected 2 unique tools after standalone deduplication, got {len(standalone_deduplicated)}"
+
+ unique_tool_names = [tool.name for tool in standalone_deduplicated]
+ expected_unique_names = ["GitMCP-fetch_litellm_documentation", "GitMCP-search_litellm_documentation"]
+ assert set(unique_tool_names) == set(expected_unique_names), \
+ f"Expected {expected_unique_names}, got {unique_tool_names}"
+
+ print("✓ Test Case 3b: standalone deduplication method works correctly")
+
+ # Test Case 4: Multiple MCP tool configs with different allowed_tools
+ multiple_mcp_configs = [
+ {
+ "type": "mcp",
+ "server_label": "gitmcp1",
+ "server_url": "https://gitmcp.io/openai/tiktoken",
+ "allowed_tools": ["search_tiktoken_documentation"],
+ "require_approval": "never"
+ },
+ {
+ "type": "mcp",
+ "server_label": "gitmcp2",
+ "server_url": "https://gitmcp.io/openai/tiktoken",
+ "allowed_tools": ["fetch_tiktoken_documentation", "get_tiktoken_examples"],
+ "require_approval": "never"
+ }
+ ]
+
+ filtered_tools_multiple = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mock_mcp_tools_from_server,
+ mcp_tools_with_litellm_proxy=cast(List[ToolParam], multiple_mcp_configs)
+ )
+
+ # Should return union of all allowed tools (3 unique tools)
+ assert len(filtered_tools_multiple) == 3, f"Expected 3 tools from multiple configs, got {len(filtered_tools_multiple)}"
+
+ filtered_multiple_names = [tool.name for tool in filtered_tools_multiple]
+ expected_multiple_tools = ["search_tiktoken_documentation", "fetch_tiktoken_documentation", "get_tiktoken_examples"]
+
+ assert set(filtered_multiple_names) == set(expected_multiple_tools), \
+ f"Expected tools {expected_multiple_tools}, got {filtered_multiple_names}"
+
+ print("✓ Test Case 3: multiple MCP configs with different allowed_tools works correctly")
+
+ # Test Case 4: Empty allowed_tools list (should return no tools)
+ mcp_config_empty_allowed = [
+ {
+ "type": "mcp",
+ "server_label": "gitmcp",
+ "server_url": "https://gitmcp.io/openai/tiktoken",
+ "allowed_tools": [],
+ "require_approval": "never"
+ }
+ ]
+
+ filtered_tools_empty = LiteLLM_Proxy_MCP_Handler._filter_mcp_tools_by_allowed_tools(
+ mcp_tools=mock_mcp_tools_from_server,
+ mcp_tools_with_litellm_proxy=cast(List[ToolParam], mcp_config_empty_allowed)
+ )
+
+ # Should return all tools when allowed_tools is empty list (no filtering)
+ assert len(filtered_tools_empty) == 4, f"Expected 4 tools when allowed_tools is empty list, got {len(filtered_tools_empty)}"
+
+ print("✓ Test Case 4: empty allowed_tools list returns all tools")
+
+ print("✓ MCP allowed_tools filtering test completed successfully!")
+
+async def test_streaming_mcp_events_validation():
+ """
+ Test that MCP streaming events are properly emitted when using streaming with MCP tools.
+
+ This test validates:
+ 1. MCP discovery events are emitted first
+ 2. Regular streaming response events follow
+ 3. Tool execution events are emitted when tools are auto-executed
+ """
+ from unittest.mock import AsyncMock, patch
+ from litellm.types.llms.openai import ResponsesAPIStreamEvents
+
+ print("🧪 Testing MCP streaming events...")
+
+ # Mock MCP tools that would be returned from the manager
+ mock_mcp_tools = [
+ type('MCPTool', (), {
+ 'name': 'search_repo',
+ 'description': 'Search BerriAI/litellm repository for information',
+ 'inputSchema': {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query"}
+ },
+ "required": ["query"]
+ }
+ })(),
+ type('MCPTool', (), {
+ 'name': 'get_repo_info',
+ 'description': 'Get repository information',
+ 'inputSchema': {
+ "type": "object",
+ "properties": {
+ "repo_name": {"type": "string", "description": "Repository name"}
+ },
+ "required": ["repo_name"]
+ }
+ })()
+ ]
+
+ # Mock the MCP operations
+ with patch.object(LiteLLM_Proxy_MCP_Handler, '_get_mcp_tools_from_manager', new_callable=AsyncMock) as mock_get_tools, \
+ patch.object(LiteLLM_Proxy_MCP_Handler, '_execute_tool_calls', new_callable=AsyncMock) as mock_execute_tools:
+
+ # Setup MCP mocks
+ mock_get_tools.return_value = mock_mcp_tools
+
+ def mock_execute_tool_calls_side_effect(tool_calls, user_api_key_auth):
+ """Mock tool execution with realistic results"""
+ results = []
+ for tool_call in tool_calls:
+ call_id = None
+ if isinstance(tool_call, dict):
+ call_id = tool_call.get("call_id") or tool_call.get("id")
+ elif hasattr(tool_call, 'call_id'):
+ call_id = tool_call.call_id
+ elif hasattr(tool_call, 'id'):
+ call_id = tool_call.id
+
+ if call_id:
+ results.append({
+ "tool_call_id": call_id,
+ "result": "LiteLLM is a unified interface for 100+ LLMs that provides consistent OpenAI-format output and includes proxy server capabilities."
+ })
+ return results
+
+ mock_execute_tools.side_effect = mock_execute_tool_calls_side_effect
+
+ # Configure MCP tool with streaming and auto-execution
+ mcp_tool_config = {
+ "type": "mcp",
+ "server_url": "litellm_proxy/mcp/test_server",
+ "require_approval": "never" # This enables auto-execution
+ }
+
+ print("📞 Making streaming request with MCP tools...")
+
+ # Make streaming request with MCP tools
+ response = await litellm.aresponses(
+ model="gpt-4o-mini", # Use cheaper model for testing
+ tools=[mcp_tool_config],
+ tool_choice="required",
+ input=[{
+ "role": "user",
+ "type": "message",
+ "content": "What is LiteLLM? Give me a brief overview."
+ }],
+ stream=True
+ )
+
+ print(f"📋 Response type: {type(response)}")
+ assert hasattr(response, '__aiter__'), "Response should be async iterable for streaming"
+
+ # Collect all streaming events
+ events = []
+ event_types = []
+ mcp_discovery_events = []
+ mcp_execution_events = []
+ regular_events = []
+
+ print("🔄 Collecting streaming events...")
+
+ try:
+ async for chunk in response:
+ events.append(chunk)
+ event_type = getattr(chunk, 'type', 'unknown')
+ event_types.append(event_type)
+
+ # Categorize events
+ if event_type in [
+ ResponsesAPIStreamEvents.MCP_TOOLS_DISCOVERY_STARTED,
+ ResponsesAPIStreamEvents.MCP_TOOLS_DISCOVERY_COMPLETED
+ ]:
+ mcp_discovery_events.append(chunk)
+ elif event_type in [
+ ResponsesAPIStreamEvents.MCP_TOOL_EXECUTION_STARTED,
+ ResponsesAPIStreamEvents.MCP_TOOL_EXECUTION_COMPLETED
+ ]:
+ mcp_execution_events.append(chunk)
+ else:
+ regular_events.append(chunk)
+
+ print(f"📦 Event: {event_type}")
+
+ # Print MCP-specific event details
+ if hasattr(chunk, 'mcp_servers'):
+ print(f" 🔧 MCP Servers: {chunk.mcp_servers}")
+ elif hasattr(chunk, 'mcp_tools'):
+ print(f" 🛠️ MCP Tools: {len(chunk.mcp_tools)} tools discovered")
+ elif hasattr(chunk, 'tool_name'):
+ print(f" ⚙️ Tool: {chunk.tool_name}")
+ if hasattr(chunk, 'result'):
+ print(f" ✅ Result: {chunk.result[:100]}...")
+
+ except Exception as e:
+ print(f"❌ Error during streaming: {e}")
+ # Continue with validation of events collected so far
+
+ print(f"\n📊 Event Summary:")
+ print(f" Total events: {len(events)}")
+ print(f" MCP discovery events: {len(mcp_discovery_events)}")
+ print(f" MCP execution events: {len(mcp_execution_events)}")
+ print(f" Regular streaming events: {len(regular_events)}")
+ print(f" Event types: {set(event_types)}")
+
+ # Validate MCP discovery events
+ if mcp_discovery_events:
+ print("✅ MCP discovery events found!")
+
+ # Check for discovery started event
+ started_events = [e for e in mcp_discovery_events if e.type == ResponsesAPIStreamEvents.MCP_TOOLS_DISCOVERY_STARTED]
+ if started_events:
+ print(f" 🚀 Discovery started events: {len(started_events)}")
+ started_event = started_events[0]
+ if hasattr(started_event, 'mcp_servers'):
+ print(f" 📡 MCP servers: {started_event.mcp_servers}")
+
+ # Check for discovery completed event
+ completed_events = [e for e in mcp_discovery_events if e.type == ResponsesAPIStreamEvents.MCP_TOOLS_DISCOVERY_COMPLETED]
+ if completed_events:
+ print(f" 🏁 Discovery completed events: {len(completed_events)}")
+ completed_event = completed_events[0]
+ if hasattr(completed_event, 'mcp_tools'):
+ print(f" 🔧 Tools discovered: {len(completed_event.mcp_tools)}")
+ else:
+ print("⚠️ No MCP discovery events found")
+
+ # Validate MCP execution events (if auto-execution occurred)
+ if mcp_execution_events:
+ print("✅ MCP tool execution events found!")
+ execution_started = [e for e in mcp_execution_events if e.type == ResponsesAPIStreamEvents.MCP_TOOL_EXECUTION_STARTED]
+ execution_completed = [e for e in mcp_execution_events if e.type == ResponsesAPIStreamEvents.MCP_TOOL_EXECUTION_COMPLETED]
+ print(f" 🚀 Execution started events: {len(execution_started)}")
+ print(f" 🏁 Execution completed events: {len(execution_completed)}")
+
+ # Validate that we got some form of streaming response
+ assert len(events) > 0, "Should have received at least some streaming events"
+
+ # Verify MCP mocks were called
+ assert mock_get_tools.called, "MCP tools should have been fetched"
+ print("✅ MCP tool fetching was called")
+
+ print("🎉 MCP streaming events validation completed!")
+ return {
+ 'total_events': len(events),
+ 'mcp_discovery_events': len(mcp_discovery_events),
+ 'mcp_execution_events': len(mcp_execution_events),
+ 'regular_events': len(regular_events),
+ 'event_types': list(set(event_types))
+ }
+
+
+async def test_streaming_responses_api_with_mcp_tools():
+ """
+ Test the streaming responses API with MCP tools when using server_url="litellm_proxy"
+
+ Under the hood the follow occurs
+
+ - MCP: responses called litellm MCP manager.list_tools (MOCKED)
+ - Request 1: Made to gpt-4o with fetched tools (REAL LLM CALL)
+ - MCP: Execute tool call from request 1 and returns result (MOCKED)
+ - Request 2: Made to gpt-4o with fetched tools and tool results (REAL LLM CALL)
+
+ Return the user the result of request 2
+ """
+ from unittest.mock import AsyncMock, patch
+
+ print("🧪 Testing basic streaming with MCP tools...")
+
+ # Mock MCP tools that would be returned from the manager
+ mock_mcp_tools = [
+ type('MCPTool', (), {
+ 'name': 'search_repo',
+ 'description': 'Search BerriAI/litellm repository for information',
+ 'inputSchema': {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query"}
+ },
+ "required": ["query"]
+ }
+ })()
+ ]
+
+ # Only mock the MCP-specific operations, let LLM responses be real
+ with patch.object(LiteLLM_Proxy_MCP_Handler, '_get_mcp_tools_from_manager', new_callable=AsyncMock) as mock_get_tools, \
+ patch.object(LiteLLM_Proxy_MCP_Handler, '_execute_tool_calls', new_callable=AsyncMock) as mock_execute_tools:
+
+ # Setup MCP mocks only
+ mock_get_tools.return_value = mock_mcp_tools
+
+ # Create a dynamic mock that will match the actual tool call ID from the LLM response
+ def mock_execute_tool_calls_side_effect(tool_calls, user_api_key_auth):
+ """Mock function that returns results matching the actual tool call IDs from the LLM"""
+ results = []
+ for tool_call in tool_calls:
+ # Extract call_id from the tool call
+ call_id = None
+ if isinstance(tool_call, dict):
+ call_id = tool_call.get("call_id") or tool_call.get("id")
+ elif hasattr(tool_call, 'call_id'):
+ call_id = tool_call.call_id
+ elif hasattr(tool_call, 'id'):
+ call_id = tool_call.id
+
+ if call_id:
+ results.append({
+ "tool_call_id": call_id,
+ "result": "LiteLLM is a unified interface for 100+ LLMs that translates inputs to provider-specific completion endpoints and provides consistent OpenAI-format output."
+ })
+ return results
+
+ mock_execute_tools.side_effect = mock_execute_tool_calls_side_effect
+
+ # Make the actual call - LLM responses will be real
+ mcp_tool_config = cast(Any, {
+ "type": "mcp",
+ "server_url": "litellm_proxy",
+ "require_approval": "never"
+ })
+ response = await litellm.aresponses(
+ model="gpt-4o-mini",
+ tools=[mcp_tool_config],
+ tool_choice="required",
+ input=[
+ {
+ "role": "user",
+ "type": "message",
+ "content": "give me a TLDR of what BerriAI/litellm is about"
+ }
+ ],
+ stream=True
+ )
+
+ print(f"📋 Response type: {type(response)}")
+ assert hasattr(response, '__aiter__'), "Response should be an async streaming response"
+
+ # Collect streaming chunks
+ chunks = []
+ async for chunk in response:
+ chunks.append(chunk)
+ print(f"📦 Chunk type: {getattr(chunk, 'type', 'unknown')}")
+
+ print(f"📊 Total chunks received: {len(chunks)}")
+
+ # Verify MCP mocks were called (may be called multiple times in streaming)
+ assert mock_get_tools.call_count >= 1, f"Expected MCP tools to be fetched at least once, got {mock_get_tools.call_count}"
+ print(f"MCP tools fetched: {len(mock_mcp_tools)}")
+
+ # Verify we got a response
+ assert response is not None
+ assert len(chunks) > 0, "Should have received streaming chunks"
+
+ print("Basic streaming responses API with MCP tools test passed!")
+
+
+async def test_mcp_parameter_preparation_helpers():
+ """
+ Test the new parameter preparation helper methods for clean MCP handling.
+
+ Tests:
+ 1. _prepare_initial_call_params - handles stream disabling for auto-execute
+ 2. _prepare_follow_up_call_params - restores stream and removes tool_choice
+ 3. _build_request_params - clean parameter merging
+ """
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler
+
+ print("🧪 Testing MCP parameter preparation helpers...")
+
+ # Test _prepare_initial_call_params
+ base_call_params = {
+ "stream": True,
+ "temperature": 0.7,
+ "tool_choice": "required",
+ "max_output_tokens": 1000
+ }
+
+ # Test Case 1: Auto-execute scenario (should disable streaming)
+ initial_params_auto = LiteLLM_Proxy_MCP_Handler._prepare_initial_call_params(
+ call_params=base_call_params,
+ should_auto_execute=True
+ )
+
+ assert initial_params_auto["stream"] == False, "Stream should be disabled for auto-execute"
+ assert initial_params_auto["temperature"] == 0.7, "Other params should be preserved"
+ assert initial_params_auto["tool_choice"] == "required", "tool_choice should be preserved for initial call"
+ assert base_call_params["stream"] == True, "Original params should not be mutated"
+
+ print("✅ _prepare_initial_call_params (auto-execute) works correctly")
+
+ # Test Case 2: No auto-execute scenario (should preserve streaming)
+ initial_params_no_auto = LiteLLM_Proxy_MCP_Handler._prepare_initial_call_params(
+ call_params=base_call_params,
+ should_auto_execute=False
+ )
+
+ assert initial_params_no_auto["stream"] == True, "Stream should be preserved when not auto-executing"
+ assert initial_params_no_auto["temperature"] == 0.7, "Other params should be preserved"
+
+ print("✅ _prepare_initial_call_params (no auto-execute) works correctly")
+
+ # Test _prepare_follow_up_call_params
+ follow_up_params = LiteLLM_Proxy_MCP_Handler._prepare_follow_up_call_params(
+ call_params=base_call_params,
+ original_stream_setting=True
+ )
+
+ assert follow_up_params["stream"] == True, "Stream should be restored to original setting"
+ assert "tool_choice" not in follow_up_params, "tool_choice should be removed for follow-up call"
+ assert follow_up_params["temperature"] == 0.7, "Other params should be preserved"
+ assert base_call_params["tool_choice"] == "required", "Original params should not be mutated"
+
+ print("✅ _prepare_follow_up_call_params works correctly")
+
+ # Test _build_request_params
+ input_data = [{"role": "user", "content": "test", "type": "message"}]
+ model = "gpt-4o-mini"
+ tools = [{"type": "function", "name": "test_tool"}]
+ call_params = {"stream": True, "temperature": 0.8}
+ previous_response_id = "resp_123"
+ extra_kwargs = {"custom_param": "test_value"}
+
+ request_params = LiteLLM_Proxy_MCP_Handler._build_request_params(
+ input=input_data,
+ model=model,
+ all_tools=tools,
+ call_params=call_params,
+ previous_response_id=previous_response_id,
+ **extra_kwargs
+ )
+
+ # Verify core parameters
+ assert request_params["input"] == input_data, "Input should be included"
+ assert request_params["model"] == model, "Model should be included"
+ assert request_params["tools"] == tools, "Tools should be included"
+ assert request_params["previous_response_id"] == previous_response_id, "Previous response ID should be included"
+
+ # Verify call_params are merged
+ assert request_params["stream"] == True, "call_params should be merged"
+ assert request_params["temperature"] == 0.8, "call_params should be merged"
+
+ # Verify extra kwargs are merged
+ assert request_params["custom_param"] == "test_value", "Extra kwargs should be merged"
+
+ print("✅ _build_request_params works correctly")
+
+ # Test _build_request_params with None previous_response_id
+ request_params_no_prev = LiteLLM_Proxy_MCP_Handler._build_request_params(
+ input=input_data,
+ model=model,
+ all_tools=tools,
+ call_params=call_params,
+ previous_response_id=None
+ )
+
+ assert "previous_response_id" not in request_params_no_prev, "None previous_response_id should not be included"
+
+ print("✅ _build_request_params handles None previous_response_id correctly")
+
+ print("🎉 All MCP parameter preparation helper tests passed!")
+
+
+async def test_mcp_tool_execution_events_creation():
+ """
+ Test the _create_tool_execution_events helper method for generating streaming events.
+ """
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler
+
+ print("Testing MCP tool execution events creation...")
+
+ # Mock tool calls (simulating what comes from LLM response in function_call format)
+ mock_tool_calls = [
+ {
+ "id": "call_abc123",
+ "name": "search_repo",
+ "arguments": '{"query": "LiteLLM overview"}',
+ "type": "function_call"
+ },
+ {
+ "id": "call_def456",
+ "name": "get_repo_info",
+ "arguments": '{"repo_name": "BerriAI/litellm"}',
+ "type": "function_call"
+ }
+ ]
+
+ # Mock tool results (simulating what comes from tool execution)
+ mock_tool_results = [
+ {
+ "tool_call_id": "call_abc123",
+ "result": "LiteLLM is a unified interface for 100+ LLMs"
+ },
+ {
+ "tool_call_id": "call_def456",
+ "result": "Repository: BerriAI/litellm - Python library for LLM integration"
+ }
+ ]
+
+ # Create tool execution events
+ execution_events = LiteLLM_Proxy_MCP_Handler._create_tool_execution_events(
+ tool_calls=mock_tool_calls,
+ tool_results=mock_tool_results
+ )
+
+ # Verify events were created
+ assert len(execution_events) > 0, "Should create tool execution events"
+ print(f"Created {len(execution_events)} tool execution events")
+
+ # Verify events have proper structure
+ for event in execution_events:
+ assert hasattr(event, 'type'), "Event should have type attribute"
+ event_type = str(event.type)
+ assert 'mcp_call' in event_type.lower() or 'output_item' in event_type.lower(), f"Event should be MCP-related: {event_type}"
+
+ # Check for sequence numbers
+ if hasattr(event, 'sequence_number'):
+ assert isinstance(event.sequence_number, int), "Sequence number should be integer"
+ assert event.sequence_number > 0, "Sequence number should be positive"
+
+ print("Tool execution events have proper structure")
+
+ # Test with empty inputs
+ empty_events = LiteLLM_Proxy_MCP_Handler._create_tool_execution_events(
+ tool_calls=[],
+ tool_results=[]
+ )
+
+ assert len(empty_events) == 0, "Should create no events for empty inputs"
+ print("Handles empty inputs correctly")
+
+ print("MCP tool execution events creation test passed!")
+
+
+async def test_no_duplicate_mcp_tools_in_streaming_e2e():
+ """
+ End-to-end test to validate that MCP tools are not duplicated when using streaming.
+
+ This test protects against the bug where:
+ 1. Parent function (aresponses_api_with_mcp) processed MCP tools once
+ 2. Streaming iterator processed MCP tools again, causing duplicates
+
+ The test mocks the MCP manager response but validates the actual tools
+ sent to the LLM to ensure no duplication occurs.
+ """
+ from unittest.mock import AsyncMock, patch, call
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler
+
+ print("Testing no duplicate MCP tools in streaming E2E...")
+
+ # Mock MCP tools that would be returned from the manager
+ mock_mcp_tools = [
+ type('MCPTool', (), {
+ 'name': 'search_docs',
+ 'description': 'Search documentation for information',
+ 'inputSchema': {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query"}
+ },
+ "required": ["query"]
+ }
+ })(),
+ type('MCPTool', (), {
+ 'name': 'get_file_content',
+ 'description': 'Get content of a specific file',
+ 'inputSchema': {
+ "type": "object",
+ "properties": {
+ "file_path": {"type": "string", "description": "Path to file"}
+ },
+ "required": ["file_path"]
+ }
+ })()
+ ]
+
+ # Track all calls to the underlying LLM to detect duplicates
+ llm_call_tools = []
+
+ async def capture_llm_tools(**kwargs):
+ """Capture the tools parameter from LLM calls"""
+ tools = kwargs.get('tools', [])
+ llm_call_tools.append(tools)
+
+ # Return a minimal mock async streaming response
+ class MockStreamingResponse:
+ async def __aiter__(self):
+ yield type('MockChunk', (), {
+ 'type': 'response.completed',
+ 'output': []
+ })()
+
+ return MockStreamingResponse()
+
+ # Mock both the MCP manager and the underlying LLM call
+ with patch.object(LiteLLM_Proxy_MCP_Handler, '_get_mcp_tools_from_manager', new_callable=AsyncMock) as mock_get_tools, \
+ patch('litellm.aresponses', side_effect=capture_llm_tools) as mock_aresponses:
+
+ # Setup MCP mock to return our test tools
+ mock_get_tools.return_value = mock_mcp_tools
+
+ # Configure MCP tool for streaming
+ mcp_tool_config = {
+ "type": "mcp",
+ "server_url": "litellm_proxy/mcp/test_server",
+ "require_approval": "always" # Disable auto-execution to focus on tool duplication
+ }
+
+ print("Making streaming request with MCP tools...")
+
+ # Make streaming request with MCP tools
+ try:
+ response = await litellm.aresponses(
+ model="gpt-4o-mini",
+ tools=[mcp_tool_config],
+ input=[{
+ "role": "user",
+ "type": "message",
+ "content": "Search the documentation for information about authentication."
+ }],
+ stream=True
+ )
+
+ # Consume the streaming response
+ chunks = []
+ async for chunk in response:
+ chunks.append(chunk)
+
+ except Exception as e:
+ print(f"Request failed (expected for test): {e}")
+ # Continue with validation even if request fails
+
+ # Validate underlying LLM was called (this proves our mocking works)
+ assert len(llm_call_tools) > 0, "LLM should have been called at least once"
+ print(f"LLM called {len(llm_call_tools)} time(s)")
+
+ # If MCP tools were processed, validate they were fetched exactly once
+ # (This protects against duplicate fetching)
+ if mock_get_tools.call_count > 0:
+ assert mock_get_tools.call_count == 1, f"MCP tools should be fetched exactly once, got {mock_get_tools.call_count} calls"
+ print(f"MCP tools fetched exactly once: {mock_get_tools.call_count}")
+ else:
+ print("MCP tools not fetched (likely due to test mocking - this is OK for validation)")
+
+ # Analyze tools sent to LLM for duplicates
+ for call_idx, tools_in_call in enumerate(llm_call_tools):
+ print(f"LLM Call {call_idx + 1}: {len(tools_in_call)} tools")
+
+ if tools_in_call:
+ # Extract tool names to check for duplicates
+ tool_names = []
+ for tool in tools_in_call:
+ if isinstance(tool, dict):
+ tool_name = tool.get('function', {}).get('name') or tool.get('name')
+ else:
+ tool_name = getattr(tool, 'name', str(tool))
+
+ if tool_name:
+ tool_names.append(tool_name)
+
+ print(f" Tool names: {tool_names}")
+
+ # Check for duplicate tool names
+ unique_tool_names = set(tool_names)
+ duplicates = [name for name in tool_names if tool_names.count(name) > 1]
+
+ assert len(duplicates) == 0, f"Found duplicate tools in LLM call {call_idx + 1}: {duplicates}"
+ assert len(tool_names) == len(unique_tool_names), f"Tool names should be unique in call {call_idx + 1}"
+
+ print(f" No duplicate tools found in call {call_idx + 1}")
+
+ # Validate that MCP tools were properly transformed to OpenAI format
+ openai_format_tools = [tool for tool in tools_in_call if isinstance(tool, dict) and 'function' in tool]
+ if openai_format_tools:
+ print(f" Found {len(openai_format_tools)} OpenAI-format tools")
+
+ # Verify tools have proper OpenAI structure
+ for tool in openai_format_tools:
+ assert 'type' in tool, "Tool should have 'type' field"
+ assert tool['type'] == 'function', "Tool type should be 'function'"
+ assert 'function' in tool, "Tool should have 'function' field"
+ assert 'name' in tool['function'], "Function should have 'name'"
+ assert 'description' in tool['function'], "Function should have 'description'"
+ assert 'parameters' in tool['function'], "Function should have 'parameters'"
+
+ print(f" All tools have proper OpenAI format")
+
+ # The key validation: ensure no duplicate fetching occurred
+ # This is the main protection against the bug we fixed
+ if mock_get_tools.call_count > 1:
+ print(f"ERROR: Duplicate MCP fetching detected! Called {mock_get_tools.call_count} times")
+ assert False, f"MCP tools should be fetched exactly once, but were fetched {mock_get_tools.call_count} times"
+
+ # Additional validation: ensure no duplicate tools in any LLM call
+ total_duplicates_found = 0
+ for call_idx, tools_in_call in enumerate(llm_call_tools):
+ if tools_in_call:
+ tool_names = []
+ for tool in tools_in_call:
+ if isinstance(tool, dict):
+ tool_name = tool.get('function', {}).get('name') or tool.get('name')
+ if tool_name:
+ tool_names.append(tool_name)
+
+ duplicates = [name for name in tool_names if tool_names.count(name) > 1]
+ if duplicates:
+ total_duplicates_found += len(set(duplicates))
+ print(f"ERROR: Duplicate tools in call {call_idx + 1}: {set(duplicates)}")
+
+ if total_duplicates_found > 0:
+ assert False, f"Found {total_duplicates_found} duplicate tools across all LLM calls"
+
+ print("No duplicate MCP tools E2E test passed!")
+ print(f"Summary:")
+ print(f" - MCP manager called: {mock_get_tools.call_count} time(s)")
+ print(f" - LLM called: {len(llm_call_tools)} time(s)")
+ print(f" - Unique tools per call: {[len(set(getattr(t.get('function', {}), 'name', 'unknown') if isinstance(t, dict) else str(t) for t in tools)) for tools in llm_call_tools]}")
+ print(f" - No duplicate tools detected")
+
+ return {
+ 'mcp_manager_calls': mock_get_tools.call_count,
+ 'llm_calls': len(llm_call_tools),
+ 'tools_per_call': [len(tools) for tools in llm_call_tools],
+ 'duplicate_tools_found': False
+ }
+
+
+
\ No newline at end of file
diff --git a/tests/test_litellm/experimental_mcp_client/test_tools.py b/tests/test_litellm/experimental_mcp_client/test_tools.py
index ec430ecc9bf..254d8e517c2 100644
--- a/tests/test_litellm/experimental_mcp_client/test_tools.py
+++ b/tests/test_litellm/experimental_mcp_client/test_tools.py
@@ -19,9 +19,11 @@ from mcp.types import Tool as MCPTool
from litellm.experimental_mcp_client.tools import (
_get_function_arguments,
+ _normalize_mcp_input_schema,
call_mcp_tool,
call_openai_tool,
load_mcp_tools,
+ transform_mcp_tool_to_openai_responses_api_tool,
transform_mcp_tool_to_openai_tool,
transform_openai_tool_call_request_to_mcp_tool_call_request,
)
@@ -73,6 +75,7 @@ def test_transform_mcp_tool_to_openai_tool(mock_mcp_tool):
assert openai_tool["function"]["parameters"] == {
"type": "object",
"properties": {"test": {"type": "string"}},
+ "additionalProperties": False,
}
@@ -155,3 +158,95 @@ async def test_call_mcp_tool(mock_session, mock_mcp_tool_call_result):
mock_session.call_tool.assert_called_once_with(
name="test_tool", arguments={"test": "value"}
)
+
+
+def test_normalize_mcp_input_schema():
+ """Test MCP input schema normalization for OpenAI compatibility."""
+ # Test case 1: Empty/None schema should get default structure
+ assert _normalize_mcp_input_schema(None) == {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": False
+ }
+
+ assert _normalize_mcp_input_schema({}) == {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": False
+ }
+
+ # Test case 2: Schema with only type should get properties added
+ schema_with_type_only = {"type": "object"}
+ normalized = _normalize_mcp_input_schema(schema_with_type_only)
+ assert normalized == {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": False
+ }
+
+ # Test case 3: Schema missing type should get type added
+ schema_missing_type = {"properties": {"param": {"type": "string"}}}
+ normalized = _normalize_mcp_input_schema(schema_missing_type)
+ assert normalized == {
+ "type": "object",
+ "properties": {"param": {"type": "string"}},
+ "additionalProperties": False
+ }
+
+ # Test case 4: Complete schema should be preserved with additionalProperties added
+ complete_schema = {
+ "type": "object",
+ "properties": {"param": {"type": "string"}},
+ "required": ["param"]
+ }
+ normalized = _normalize_mcp_input_schema(complete_schema)
+ assert normalized == {
+ "type": "object",
+ "properties": {"param": {"type": "string"}},
+ "required": ["param"],
+ "additionalProperties": False
+ }
+
+ # Test case 5: Schema with existing additionalProperties should be preserved
+ schema_with_additional = {
+ "type": "object",
+ "properties": {"param": {"type": "string"}},
+ "additionalProperties": True
+ }
+ normalized = _normalize_mcp_input_schema(schema_with_additional)
+ assert normalized["additionalProperties"] == True
+
+
+def test_transform_mcp_tool_to_openai_responses_api_tool():
+ """Test transformation to OpenAI Responses API tool format with schema normalization."""
+ # Test case 1: Tool with minimal schema (the problematic case from the error)
+ minimal_tool = MCPTool(
+ name="GitMCP-fetch_litellm_documentation",
+ description="Fetch entire documentation file from GitHub repository",
+ inputSchema={"type": "object"} # This was causing the error
+ )
+
+ openai_tool = transform_mcp_tool_to_openai_responses_api_tool(minimal_tool)
+ assert openai_tool["name"] == "GitMCP-fetch_litellm_documentation"
+ assert openai_tool["type"] == "function"
+ assert openai_tool["strict"] == False
+ assert openai_tool["parameters"]["type"] == "object"
+ assert openai_tool["parameters"]["properties"] == {}
+ assert openai_tool["parameters"]["additionalProperties"] == False
+
+ # Test case 2: Tool with complete schema
+ complete_tool = MCPTool(
+ name="test_tool_complete",
+ description="A test tool with complete schema",
+ inputSchema={
+ "type": "object",
+ "properties": {"query": {"type": "string", "description": "Search query"}},
+ "required": ["query"]
+ }
+ )
+
+ openai_tool = transform_mcp_tool_to_openai_responses_api_tool(complete_tool)
+ assert openai_tool["parameters"]["type"] == "object"
+ assert "query" in openai_tool["parameters"]["properties"]
+ assert openai_tool["parameters"]["required"] == ["query"]
+ assert openai_tool["parameters"]["additionalProperties"] == False
diff --git a/ui/litellm-dashboard/src/components/chat_ui.tsx b/ui/litellm-dashboard/src/components/chat_ui.tsx
index beccef260f9..6504576578e 100644
--- a/ui/litellm-dashboard/src/components/chat_ui.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui.tsx
@@ -52,6 +52,7 @@ import ChatImageUpload from "./chat_ui/ChatImageUpload";
import ChatImageRenderer from "./chat_ui/ChatImageRenderer";
import { createChatMultimodalMessage, createChatDisplayMessage } from "./chat_ui/ChatImageUtils";
import SessionManagement from "./chat_ui/SessionManagement";
+import MCPEventsDisplay, { MCPEvent } from "./chat_ui/MCPEventsDisplay";
import {
SendOutlined,
ApiOutlined,
@@ -94,15 +95,15 @@ const ChatUI: React.FC<ChatUIProps> = ({
}) => {
const [isMCPToolsModalVisible, setIsMCPToolsModalVisible] = useState(false);
const [mcpTools, setMCPTools] = useState<MCPTool[]>([]);
- const [selectedMCPTools, setSelectedMCPTools] = useState<string>(() => {
+ const [selectedMCPTools, setSelectedMCPTools] = useState<string[]>(() => {
const saved = sessionStorage.getItem('selectedMCPTools');
try {
const parsed = saved ? JSON.parse(saved) : [];
- // Convert from array to single string if needed
- return Array.isArray(parsed) ? (parsed[0] || '') : parsed;
+ // Convert from single string to array if needed for backward compatibility
+ return Array.isArray(parsed) ? parsed : (parsed ? [parsed] : []);
} catch (error) {
console.error("Error parsing selectedMCPTools from sessionStorage", error);
- return '';
+ return [];
}
});
const [isLoadingMCPTools, setIsLoadingMCPTools] = useState(false);
@@ -179,6 +180,7 @@ const ChatUI: React.FC<ChatUIProps> = ({
const [isGetCodeModalVisible, setIsGetCodeModalVisible] = useState(false);
const [generatedCode, setGeneratedCode] = useState("");
const [selectedSdk, setSelectedSdk] = useState<'openai' | 'azure'>('openai');
+ const [mcpEvents, setMCPEvents] = useState<MCPEvent[]>([]);
const chatEndRef = useRef<HTMLDivElement>(null);
@@ -215,13 +217,14 @@ const ChatUI: React.FC<ChatUIProps> = ({
selectedTags,
selectedVectorStores,
selectedGuardrails,
+ selectedMCPTools,
endpointType,
selectedModel,
selectedSdk,
});
setGeneratedCode(code);
}
- }, [isGetCodeModalVisible, selectedSdk, apiKeySource, accessToken, apiKey, inputMessage, chatHistory, selectedTags, selectedVectorStores, selectedGuardrails, endpointType, selectedModel]);
+ }, [isGetCodeModalVisible, selectedSdk, apiKeySource, accessToken, apiKey, inputMessage, chatHistory, selectedTags, selectedVectorStores, selectedGuardrails, selectedMCPTools, endpointType, selectedModel]);
useEffect(() => {
const handler = setTimeout(() => {
@@ -443,6 +446,27 @@ const ChatUI: React.FC<ChatUIProps> = ({
}
};
+ const handleMCPEvent = (event: MCPEvent) => {
+ console.log("ChatUI: Received MCP event:", event);
+ setMCPEvents(prev => {
+ // Check if this is a duplicate event (same item_id and type)
+ const isDuplicate = prev.some(existingEvent =>
+ existingEvent.item_id === event.item_id &&
+ existingEvent.type === event.type &&
+ existingEvent.sequence_number === event.sequence_number
+ );
+
+ if (isDuplicate) {
+ console.log("ChatUI: Duplicate MCP event, skipping");
+ return prev;
+ }
+
+ const newEvents = [...prev, event];
+ console.log("ChatUI: Updated MCP events:", newEvents);
+ return newEvents;
+ });
+ };
+
const updateImageUI = (imageUrl: string, model: string) => {
setChatHistory((prevHistory) => [
...prevHistory,
@@ -617,6 +641,7 @@ const ChatUI: React.FC<ChatUIProps> = ({
}
setChatHistory([...chatHistory, displayMessage]);
+ setMCPEvents([]); // Clear previous MCP events for new conversation turn
setIsLoading(true);
try {
@@ -643,7 +668,7 @@ const ChatUI: React.FC<ChatUIProps> = ({
traceId,
selectedVectorStores.length > 0 ? selectedVectorStores : undefined,
selectedGuardrails.length > 0 ? selectedGuardrails : undefined,
- selectedMCPTools, // Pass the selected tool directly
+ selectedMCPTools, // Pass the selected tools array
updateChatImageUI // Pass the image callback
);
} else if (endpointType === EndpointType.IMAGE) {
@@ -694,9 +719,10 @@ const ChatUI: React.FC<ChatUIProps> = ({
traceId,
selectedVectorStores.length > 0 ? selectedVectorStores : undefined,
selectedGuardrails.length > 0 ? selectedGuardrails : undefined,
- selectedMCPTools, // Pass the selected tool directly
+ selectedMCPTools, // Pass the selected tools array
useApiSessionManagement ? responsesSessionId : null, // Only pass session ID if API mode is enabled
- handleResponseId // Pass callback to capture new response ID
+ handleResponseId, // Pass callback to capture new response ID
+ handleMCPEvent // Pass MCP event handler
);
} else if (endpointType === EndpointType.ANTHROPIC_MESSAGES) {
const apiChatHistory = [...chatHistory.filter(msg => !msg.isImage).map(({ role, content }) => ({ role, content })), newUserMessage];
@@ -714,7 +740,7 @@ const ChatUI: React.FC<ChatUIProps> = ({
traceId,
selectedVectorStores.length > 0 ? selectedVectorStores : undefined,
selectedGuardrails.length > 0 ? selectedGuardrails : undefined,
- selectedMCPTools // Pass the selected tool directly
+ selectedMCPTools // Pass the selected tools array
);
}
}
@@ -749,6 +775,7 @@ const ChatUI: React.FC<ChatUIProps> = ({
setChatHistory([]);
setMessageTraceId(null);
setResponsesSessionId(null); // Clear responses session ID
+ setMCPEvents([]); // Clear MCP events
handleRemoveAllImages(); // Clear any uploaded images for image edits
handleRemoveResponsesImage(); // Clear any uploaded images for responses
handleRemoveChatImage(); // Clear any uploaded images for chat completions
@@ -797,8 +824,6 @@ const ChatUI: React.FC<ChatUIProps> = ({
style={{ width: "100%" }}
onChange={(value) => {
setApiKeySource(value as "session" | "custom");
- // Clear MCP tool selection when switching API key source
- setSelectedMCPTools('');
}}
options={[
{ value: 'session', label: 'Current UI Session' },
@@ -865,10 +890,6 @@ const ChatUI: React.FC<ChatUIProps> = ({
endpointType={endpointType}
onEndpointChange={(value) => {
setEndpointType(value);
- // Clear MCP tools if switching away from responses endpoint
- if (value !== EndpointType.RESPONSES) {
- setSelectedMCPTools('');
- }
}}
className="mb-4"
/>
@@ -900,20 +921,22 @@ const ChatUI: React.FC<ChatUIProps> = ({
<ToolOutlined className="mr-2" /> MCP Tool
<Tooltip
className="ml-1"
- title="Select an MCP tool to use in your conversation, only available for virtual keys and /v1/responses endpoint">
+ title="Select MCP tools to use in your conversation, only available for /v1/responses endpoint">
<InfoCircleOutlined />
</Tooltip>
</Text>
<Select
+ mode="multiple"
style={{ width: '100%' }}
- placeholder="Select MCP tool"
+ placeholder="Select MCP tools"
value={selectedMCPTools}
onChange={(value) => setSelectedMCPTools(value)}
loading={isLoadingMCPTools}
className="mb-4"
allowClear
optionLabelProp="label"
- disabled={!(apiKeySource === 'custom' && endpointType === EndpointType.RESPONSES)}
+ disabled={!(endpointType === EndpointType.RESPONSES)}
+ maxTagCount="responsive"
>
{Array.isArray(mcpTools) && mcpTools.map((tool) => (
<Select.Option
@@ -1006,116 +1029,152 @@ const ChatUI: React.FC<ChatUIProps> = ({
)}
{chatHistory.map((message, index) => (
- <div
- key={index}
- className={`mb-4 ${message.role === "user" ? "text-right" : "text-left"}`}
- >
+ <div key={index}>
+ <div
+ className={`mb-4 ${message.role === "user" ? "text-right" : "text-left"}`}
+ >
+ <div className="inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4" style={{
+ backgroundColor: message.role === "user" ? '#f0f8ff' : '#ffffff',
+ border: message.role === "user" ? '1px solid #e6f0fa' : '1px solid #f0f0f0',
+ textAlign: 'left'
+ }}>
+ <div className="flex items-center gap-2 mb-1.5">
+ <div className="flex items-center justify-center w-6 h-6 rounded-full mr-1" style={{
+ backgroundColor: message.role === "user" ? '#e6f0fa' : '#f5f5f5',
+ }}>
+ {message.role === "user" ?
+ <UserOutlined style={{ fontSize: '12px', color: '#2563eb' }} /> :
+ <RobotOutlined style={{ fontSize: '12px', color: '#4b5563' }} />
+ }
+ </div>
+ <strong className="text-sm capitalize">{message.role}</strong>
+ {message.role === "assistant" && message.model && (
+ <span className="text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-normal">
+ {message.model}
+ </span>
+ )}
+ </div>
+ {message.reasoningContent && (
+ <ReasoningContent reasoningContent={message.reasoningContent} />
+ )}
+
+ {/* Show MCP events at the start of assistant messages */}
+ {message.role === "assistant" &&
+ index === chatHistory.length - 1 &&
+ mcpEvents.length > 0 &&
+ endpointType === EndpointType.RESPONSES && (
+ <div className="mb-3">
+ <MCPEventsDisplay events={mcpEvents} />
+ </div>
+ )}
+
+ <div className="whitespace-pre-wrap break-words max-w-full message-content"
+ style={{
+ wordWrap: 'break-word',
+ overflowWrap: 'break-word',
+ wordBreak: 'break-word',
+ hyphens: 'auto'
+ }}>
+ {message.isImage ? (
+ <img
+ src={typeof message.content === "string" ? message.content : ""}
+ alt="Generated image"
+ className="max-w-full rounded-md border border-gray-200 shadow-sm"
+ style={{ maxHeight: '500px' }}
+ />
+ ) : (
+ <>
+ {/* Show attached image for user messages based on current endpoint */}
+ {endpointType === EndpointType.RESPONSES && (
+ <ResponsesImageRenderer message={message} />
+ )}
+ {endpointType === EndpointType.CHAT && (
+ <ChatImageRenderer message={message} />
+ )}
+
+ <ReactMarkdown
+ components={{
+ code({node, inline, className, children, ...props}: React.ComponentPropsWithoutRef<'code'> & {
+ inline?: boolean;
+ node?: any;
+ }) {
+ const match = /language-(\w+)/.exec(className || '');
+ return !inline && match ? (
+ <SyntaxHighlighter
+ style={coy as any}
+ language={match[1]}
+ PreTag="div"
+ className="rounded-md my-2"
+ wrapLines={true}
+ wrapLongLines={true}
+ {...props}
+ >
+ {String(children).replace(/\n$/, '')}
+ </SyntaxHighlighter>
+ ) : (
+ <code className={`${className} px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono`} style={{ wordBreak: 'break-word' }} {...props}>
+ {children}
+ </code>
+ );
+ },
+ pre: ({ node, ...props }) => (
+ <pre style={{ overflowX: 'auto', maxWidth: '100%' }} {...props} />
+ )
+ }}
+ >
+ {typeof message.content === "string" ? message.content : ""}
+ </ReactMarkdown>
+
+ {/* Show generated image from chat completions */}
+ {message.image && (
+ <div className="mt-3">
+ <img
+ src={message.image.url}
+ alt="Generated image"
+ className="max-w-full rounded-md border border-gray-200 shadow-sm"
+ style={{ maxHeight: '500px' }}
+ />
+ </div>
+ )}
+ </>
+ )}
+
+ {message.role === "assistant" && (message.timeToFirstToken || message.usage) && (
+ <ResponseMetrics
+ timeToFirstToken={message.timeToFirstToken}
+ usage={message.usage}
+ toolName={message.toolName}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ </div>
+ ))}
+
+ {/* Show MCP events during loading if no assistant message exists yet */}
+ {isLoading && mcpEvents.length > 0 && endpointType === EndpointType.RESPONSES &&
+ chatHistory.length > 0 && chatHistory[chatHistory.length - 1].role === "user" && (
+ <div className="text-left mb-4">
<div className="inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4" style={{
- backgroundColor: message.role === "user" ? '#f0f8ff' : '#ffffff',
- border: message.role === "user" ? '1px solid #e6f0fa' : '1px solid #f0f0f0',
+ backgroundColor: '#ffffff',
+ border: '1px solid #f0f0f0',
textAlign: 'left'
}}>
<div className="flex items-center gap-2 mb-1.5">
<div className="flex items-center justify-center w-6 h-6 rounded-full mr-1" style={{
- backgroundColor: message.role === "user" ? '#e6f0fa' : '#f5f5f5',
+ backgroundColor: '#f5f5f5',
}}>
- {message.role === "user" ?
- <UserOutlined style={{ fontSize: '12px', color: '#2563eb' }} /> :
- <RobotOutlined style={{ fontSize: '12px', color: '#4b5563' }} />
- }
+ <RobotOutlined style={{ fontSize: '12px', color: '#4b5563' }} />
</div>
- <strong className="text-sm capitalize">{message.role}</strong>
- {message.role === "assistant" && message.model && (
- <span className="text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-normal">
- {message.model}
- </span>
- )}
- </div>
- {message.reasoningContent && (
- <ReasoningContent reasoningContent={message.reasoningContent} />
- )}
- <div className="whitespace-pre-wrap break-words max-w-full message-content"
- style={{
- wordWrap: 'break-word',
- overflowWrap: 'break-word',
- wordBreak: 'break-word',
- hyphens: 'auto'
- }}>
- {message.isImage ? (
- <img
- src={typeof message.content === "string" ? message.content : ""}
- alt="Generated image"
- className="max-w-full rounded-md border border-gray-200 shadow-sm"
- style={{ maxHeight: '500px' }}
- />
- ) : (
- <>
- {/* Show attached image for user messages based on current endpoint */}
- {endpointType === EndpointType.RESPONSES && (
- <ResponsesImageRenderer message={message} />
- )}
- {endpointType === EndpointType.CHAT && (
- <ChatImageRenderer message={message} />
- )}
-
- <ReactMarkdown
- components={{
- code({node, inline, className, children, ...props}: React.ComponentPropsWithoutRef<'code'> & {
- inline?: boolean;
- node?: any;
- }) {
- const match = /language-(\w+)/.exec(className || '');
- return !inline && match ? (
- <SyntaxHighlighter
- style={coy as any}
- language={match[1]}
- PreTag="div"
- className="rounded-md my-2"
- wrapLines={true}
- wrapLongLines={true}
- {...props}
- >
- {String(children).replace(/\n$/, '')}
- </SyntaxHighlighter>
- ) : (
- <code className={`${className} px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono`} style={{ wordBreak: 'break-word' }} {...props}>
- {children}
- </code>
- );
- },
- pre: ({ node, ...props }) => (
- <pre style={{ overflowX: 'auto', maxWidth: '100%' }} {...props} />
- )
- }}
- >
- {typeof message.content === "string" ? message.content : ""}
- </ReactMarkdown>
-
- {/* Show generated image from chat completions */}
- {message.image && (
- <div className="mt-3">
- <img
- src={message.image.url}
- alt="Generated image"
- className="max-w-full rounded-md border border-gray-200 shadow-sm"
- style={{ maxHeight: '500px' }}
- />
- </div>
- )}
- </>
- )}
-
- {message.role === "assistant" && (message.timeToFirstToken || message.usage) && (
- <ResponseMetrics
- timeToFirstToken={message.timeToFirstToken}
- usage={message.usage}
- toolName={message.toolName}
- />
- )}
+ <strong className="text-sm capitalize">Assistant</strong>
</div>
+ <MCPEventsDisplay events={mcpEvents} />
</div>
</div>
- ))}
+ )}
+
{isLoading && (
<div className="flex justify-center items-center my-4">
<Spin indicator={antIcon} />
@@ -1387,15 +1446,17 @@ const ChatUI: React.FC<ChatUIProps> = ({
) : (
<div className="space-y-4">
<Text className="text-gray-600 block mb-4">
- Select the MCP tool you want to use in your conversation.
+ Select the MCP tools you want to use in your conversation.
</Text>
<Select
+ mode="multiple"
style={{ width: '100%' }}
- placeholder="Select MCP tool"
+ placeholder="Select MCP tools"
value={selectedMCPTools}
onChange={(value) => setSelectedMCPTools(value)}
optionLabelProp="label"
allowClear
+ maxTagCount="responsive"
>
{mcpTools.map((tool) => (
<Select.Option
diff --git a/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx b/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx
index f6bdb5f9380..903a35e61a2 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx
@@ -17,6 +17,7 @@ interface GenerateCodeParams {
selectedTags: string[];
selectedVectorStores: string[];
selectedGuardrails: string[];
+ selectedMCPTools: string[];
endpointType: string;
selectedModel: string | undefined;
selectedSdk: 'openai' | 'azure';
@@ -32,6 +33,7 @@ export const generateCodeSnippet = (params: GenerateCodeParams): string => {
selectedTags,
selectedVectorStores,
selectedGuardrails,
+ selectedMCPTools,
endpointType,
selectedModel,
selectedSdk,
diff --git a/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsx b/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsx
new file mode 100644
index 00000000000..e931b80e531
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsx
@@ -0,0 +1,263 @@
+import React from 'react';
+import { Typography, Collapse } from 'antd';
+
+const { Text } = Typography;
+const { Panel } = Collapse;
+
+export interface MCPEvent {
+ type: string;
+ sequence_number?: number;
+ output_index?: number;
+ item_id?: string;
+ item?: {
+ id?: string;
+ type?: string;
+ server_label?: string;
+ tools?: Array<{
+ name: string;
+ description: string;
+ annotations?: {
+ read_only?: boolean;
+ };
+ input_schema?: any;
+ }>;
+ name?: string;
+ arguments?: string;
+ output?: string;
+ };
+ delta?: string;
+ arguments?: string;
+ timestamp?: number;
+}
+
+interface MCPEventsDisplayProps {
+ events: MCPEvent[];
+ className?: string;
+}
+
+const MCPEventsDisplay: React.FC<MCPEventsDisplayProps> = ({ events, className }) => {
+ console.log("MCPEventsDisplay: Received events:", events);
+
+ if (!events || events.length === 0) {
+ console.log("MCPEventsDisplay: No events, returning null");
+ return null;
+ }
+
+ // Find the list tools event
+ const toolsEvent = events.find(event =>
+ event.type === 'response.output_item.done' &&
+ event.item?.type === 'mcp_list_tools' &&
+ event.item.tools &&
+ event.item.tools.length > 0
+ );
+
+ // Find MCP call events
+ const mcpCallEvents = events.filter(event =>
+ event.type === 'response.output_item.done' &&
+ event.item?.type === 'mcp_call'
+ );
+
+ console.log("MCPEventsDisplay: toolsEvent:", toolsEvent);
+ console.log("MCPEventsDisplay: mcpCallEvents:", mcpCallEvents);
+
+ if (!toolsEvent && mcpCallEvents.length === 0) {
+ console.log("MCPEventsDisplay: No valid events found, returning null");
+ return null;
+ }
+
+
+ return (
+ <div className={`mcp-events-display ${className || ''}`}>
+ <style jsx>{`
+ .openai-mcp-tools {
+ position: relative;
+ margin: 0;
+ padding: 0;
+ }
+ .openai-mcp-tools .ant-collapse {
+ background: transparent !important;
+ border: none !important;
+ }
+ .openai-mcp-tools .ant-collapse-item {
+ border: none !important;
+ background: transparent !important;
+ }
+ .openai-mcp-tools .ant-collapse-header {
+ padding: 0 0 0 20px !important;
+ background: transparent !important;
+ border: none !important;
+ font-size: 14px !important;
+ color: #9ca3af !important;
+ font-weight: 400 !important;
+ line-height: 20px !important;
+ min-height: 20px !important;
+ }
+ .openai-mcp-tools .ant-collapse-header:hover {
+ background: transparent !important;
+ color: #6b7280 !important;
+ }
+ .openai-mcp-tools .ant-collapse-content {
+ border: none !important;
+ background: transparent !important;
+ }
+ .openai-mcp-tools .ant-collapse-content-box {
+ padding: 4px 0 0 20px !important;
+ }
+ .openai-mcp-tools .ant-collapse-expand-icon {
+ position: absolute !important;
+ left: 2px !important;
+ top: 2px !important;
+ color: #9ca3af !important;
+ font-size: 10px !important;
+ width: 16px !important;
+ height: 16px !important;
+ display: flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ }
+ .openai-mcp-tools .ant-collapse-expand-icon:hover {
+ color: #6b7280 !important;
+ }
+ .openai-vertical-line {
+ position: absolute;
+ left: 9px;
+ top: 18px;
+ bottom: 0;
+ width: 0.5px;
+ background-color: #f3f4f6;
+ opacity: 0.8;
+ }
+ .tool-item {
+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
+ font-size: 13px;
+ color: #4b5563;
+ line-height: 18px;
+ padding: 0;
+ margin: 0;
+ background: white;
+ position: relative;
+ z-index: 1;
+ }
+ .mcp-section {
+ margin-bottom: 12px;
+ background: white;
+ position: relative;
+ z-index: 1;
+ }
+ .mcp-section:last-child {
+ margin-bottom: 0;
+ }
+ .mcp-section-header {
+ font-size: 13px;
+ color: #6b7280;
+ font-weight: 500;
+ margin-bottom: 4px;
+ }
+ .mcp-code-block {
+ background: #f9fafb;
+ border: 1px solid #f3f4f6;
+ border-radius: 6px;
+ padding: 8px;
+ font-size: 12px;
+ }
+ .mcp-json {
+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
+ color: #374151;
+ margin: 0;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ }
+ .mcp-approved {
+ display: flex;
+ align-items: center;
+ font-size: 13px;
+ color: #6b7280;
+ }
+ .mcp-checkmark {
+ color: #10b981;
+ margin-right: 6px;
+ font-weight: bold;
+ }
+ .mcp-response-content {
+ font-size: 13px;
+ color: #374151;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
+ }
+ `}</style>
+ <div className="openai-mcp-tools">
+ <div className="openai-vertical-line"></div>
+ <Collapse
+ ghost
+ size="small"
+ expandIconPosition="start"
+ defaultActiveKey={toolsEvent ? ['list-tools'] : mcpCallEvents.map((_, index) => `mcp-call-${index}`)}
+ >
+ {/* List Tools Panel */}
+ {toolsEvent && (
+ <Panel
+ header="List tools"
+ key="list-tools"
+ >
+ <div>
+ {toolsEvent.item?.tools?.map((tool, index) => (
+ <div key={index} className="tool-item">
+ {tool.name}
+ </div>
+ ))}
+ </div>
+ </Panel>
+ )}
+
+ {/* MCP Call Panels */}
+ {mcpCallEvents.map((callEvent, index) => (
+ <Panel
+ header={callEvent.item?.name || 'Tool call'}
+ key={`mcp-call-${index}`}
+ >
+ <div>
+ {/* Request section */}
+ <div className="mcp-section">
+ <div className="mcp-section-header">Request</div>
+ <div className="mcp-code-block">
+ {callEvent.item?.arguments && (
+ <pre className="mcp-json">
+ {(() => {
+ try {
+ return JSON.stringify(JSON.parse(callEvent.item.arguments), null, 2);
+ } catch (e) {
+ return callEvent.item.arguments;
+ }
+ })()}
+ </pre>
+ )}
+ </div>
+ </div>
+
+ {/* Approved section */}
+ <div className="mcp-section">
+ <div className="mcp-approved">
+ <span className="mcp-checkmark">✓</span> Approved
+ </div>
+ </div>
+
+ {/* Response section */}
+ {callEvent.item?.output && (
+ <div className="mcp-section">
+ <div className="mcp-section-header">Response</div>
+ <div className="mcp-response-content">
+ {callEvent.item.output}
+ </div>
+ </div>
+ )}
+ </div>
+ </Panel>
+ ))}
+ </Collapse>
+ </div>
+ </div>
+ );
+};
+
+export default MCPEventsDisplay;
diff --git a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/anthropic_messages.tsx b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/anthropic_messages.tsx
index 573c1cc2917..38b7f2eb345 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/anthropic_messages.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/anthropic_messages.tsx
@@ -18,7 +18,7 @@ export async function makeAnthropicMessagesRequest(
traceId?: string,
vector_store_ids?: string[],
guardrails?: string[],
- selectedMCPTool?: string
+ selectedMCPTools?: string[]
) {
if (!accessToken) {
throw new Error("API key is required");
@@ -48,12 +48,13 @@ export async function makeAnthropicMessagesRequest(
const startTime = Date.now();
let firstTokenReceived = false;
- // Format MCP tool if selected
- const tools = selectedMCPTool ? [{
+ // Format MCP tools if selected
+ const tools = selectedMCPTools && selectedMCPTools.length > 0 ? [{
type: "mcp",
server_label: "litellm",
server_url: `${proxyBaseUrl}/mcp`,
require_approval: "never",
+ allowed_tools: selectedMCPTools,
headers: {
"x-litellm-api-key": `Bearer ${accessToken}`
}
diff --git a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx
index 70f5e36f863..be40bfcff77 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx
@@ -17,7 +17,7 @@ export async function makeOpenAIChatCompletionRequest(
traceId?: string,
vector_store_ids?: string[],
guardrails?: string[],
- selectedMCPTool?: string,
+ selectedMCPTools?: string[],
onImageGenerated?: (imageUrl: string, model?: string) => void
) {
// base url should be the current base_url
@@ -49,12 +49,13 @@ export async function makeOpenAIChatCompletionRequest(
let fullResponseContent = "";
let fullReasoningContent = "";
- // Format MCP tool if selected
- const tools = selectedMCPTool ? [{
+ // Format MCP tools if selected
+ const tools = selectedMCPTools && selectedMCPTools.length > 0 ? [{
type: "mcp",
server_label: "litellm",
server_url: `${proxyBaseUrl}/mcp`,
require_approval: "never",
+ allowed_tools: selectedMCPTools,
headers: {
"x-litellm-api-key": `Bearer ${accessToken}`
}
diff --git a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx
index b6d656bc708..a7f66c28723 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx
@@ -5,6 +5,7 @@ import { TokenUsage } from "../ResponseMetrics";
import { getProxyBaseUrl } from "@/components/networking";
import { MCPTool } from "@/components/chat_ui/llm_calls/fetch_mcp_tools";
import NotificationManager from "@/components/molecules/notifications_manager";
+import { MCPEvent } from "../MCPEventsDisplay";
export async function makeOpenAIResponsesRequest(
messages: MessageType[],
@@ -19,9 +20,10 @@ export async function makeOpenAIResponsesRequest(
traceId?: string,
vector_store_ids?: string[],
guardrails?: string[],
- selectedMCPTool?: string,
+ selectedMCPTools?: string[],
previousResponseId?: string | null,
- onResponseId?: (responseId: string) => void
+ onResponseId?: (responseId: string) => void,
+ onMCPEvent?: (event: MCPEvent) => void
) {
if (!accessToken) {
throw new Error("API key is required");
@@ -69,15 +71,13 @@ export async function makeOpenAIResponsesRequest(
};
});
- // Format MCP tool if selected
- const tools = selectedMCPTool ? [{
+ // Format MCP tools if selected
+ const tools = selectedMCPTools && selectedMCPTools.length > 0 ? [{
type: "mcp",
server_label: "litellm",
- server_url: `${proxyBaseUrl}/mcp`,
+ server_url: `litellm_proxy/mcp`,
require_approval: "never",
- headers: {
- "x-litellm-api-key": `Bearer ${accessToken}`
- }
+ allowed_tools: selectedMCPTools,
}] : undefined;
// Create request to OpenAI responses API
@@ -100,6 +100,29 @@ export async function makeOpenAIResponsesRequest(
// Use a type-safe approach to handle events
if (typeof event === 'object' && event !== null) {
+ // Handle MCP events first
+ if (event.type?.startsWith('response.mcp_') ||
+ (event.type === "response.output_item.done" &&
+ (event.item?.type === "mcp_list_tools" || event.item?.type === "mcp_call"))) {
+ console.log("MCP event received:", event);
+
+ if (onMCPEvent) {
+ const mcpEvent: MCPEvent = {
+ type: event.type,
+ sequence_number: event.sequence_number,
+ output_index: event.output_index,
+ item_id: event.item_id || event.item?.id, // Handle both structures
+ item: event.item,
+ delta: event.delta,
+ arguments: event.arguments,
+ timestamp: Date.now()
+ };
+ onMCPEvent(mcpEvent);
+ }
+
+ // Continue processing other aspects of the event
+ }
+
// Check for MCP tool usage
if (event.type === "response.output_item.done" &&
event.item?.type === "mcp_call" &&
diff --git a/ui/litellm-dashboard/src/components/public_model_hub.tsx b/ui/litellm-dashboard/src/components/public_model_hub.tsx
index 615ea67fb1a..cbd894aac68 100644
--- a/ui/litellm-dashboard/src/components/public_model_hub.tsx
+++ b/ui/litellm-dashboard/src/components/public_model_hub.tsx
@@ -822,6 +822,7 @@ const PublicModelHub: React.FC<PublicModelHubProps> = ({ accessToken }) => {
selectedTags: [],
selectedVectorStores: [],
selectedGuardrails: [],
+ selectedMCPTools: [],
endpointType: getEndpointType(selectedModel.mode || 'chat'),
selectedModel: selectedModel.model_group,
selectedSdk: 'openai'
@@ -844,6 +845,7 @@ const PublicModelHub: React.FC<PublicModelHubProps> = ({ accessToken }) => {
selectedTags: [],
selectedVectorStores: [],
selectedGuardrails: [],
+ selectedMCPTools: [],
endpointType: getEndpointType(selectedModel.mode || 'chat'),
selectedModel: selectedModel.model_group,
selectedSdk: 'openai'