The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] MCP Gateway - allow using MCPs with all LLM APIs when using /responses with LiteLLM (#12546)
Ishaan Jaff2d6751a3967c
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.mdindex d68416f1166..39f6206e9a3 100644--- a/docs/my-website/docs/mcp.md+++ b/docs/my-website/docs/mcp.md@@ -128,7 +128,7 @@ curl --location 'https://api.openai.com/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY"@@ -158,7 +158,7 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY"@@ -188,7 +188,7 @@ Use tools directly from Cursor IDE with LiteLLM MCP:{"mcpServers": {"LiteLLM": {- "url": "<your-litellm-proxy-base-url>/mcp",+ "url": "litellm_proxy","headers": {"x-litellm-api-key": "Bearer $LITELLM_API_KEY"}@@ -200,6 +200,24 @@ Use tools directly from Cursor IDE with LiteLLM MCP:</TabItem></Tabs>+#### How it works when server_url="litellm_proxy"++When server_url="litellm_proxy", LiteLLM bridges non-MCP providers to your MCP tools.++- Tool Discovery: LiteLLM fetches MCP tools and converts them to OpenAI-compatible definitions+- LLM Call: Tools are sent to the LLM with your input; LLM selects which tools to call+- Tool Execution: LiteLLM automatically parses arguments, routes calls to MCP servers, executes tools, and retrieves results+- Response Integration: Tool results are sent back to LLM for final response generation+- Output: Complete response combining LLM reasoning with tool execution results++This enables MCP tool usage with any LiteLLM-supported provider, regardless of native MCP support.++#### Auto-execution for require_approval: "never"++Setting require_approval: "never" triggers automatic tool execution, returning the final response in a single API call without additional user interaction.+++### Specific MCP ServersYou can choose to access specific MCP servers and only list their tools using the `x-mcp-servers` header. This header allows you to:@@ -225,7 +243,7 @@ curl --location 'https://api.openai.com/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",@@ -254,7 +272,7 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",@@ -277,7 +295,7 @@ This configuration restricts the request to only use tools from the specified MC{"mcpServers": {"LiteLLM": {- "url": "<your-litellm-proxy-base-url>/mcp",+ "url": "litellm_proxy","headers": {"x-litellm-api-key": "Bearer $LITELLM_API_KEY","x-mcp-servers": "Zapier_Gmail,Server2"@@ -317,7 +335,7 @@ Include the access group name in the `x-mcp-servers` header:{"mcpServers": {"LiteLLM": {- "url": "<your-litellm-proxy-base-url>/mcp",+ "url": "litellm_proxy","headers": {"x-litellm-api-key": "Bearer $LITELLM_API_KEY","x-mcp-servers": "dev_group"@@ -367,7 +385,7 @@ curl --location 'https://api.openai.com/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",@@ -398,7 +416,7 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",@@ -429,7 +447,7 @@ Use tools directly from Cursor IDE with LiteLLM MCP and include your MCP authent{"mcpServers": {"LiteLLM": {- "url": "<your-litellm-proxy-base-url>/mcp",+ "url": "litellm_proxy","headers": {"x-litellm-api-key": "Bearer $LITELLM_API_KEY","x-mcp-auth": "$MCP_AUTH_TOKEN"@@ -449,7 +467,7 @@ Connect to LiteLLM MCP using HTTP transport with MCP authentication:**Server URL:**```text showLineNumbers-<your-litellm-proxy-base-url>/mcp+litellm_proxy```**Headers:**@@ -476,7 +494,7 @@ from fastmcp import Clientfrom fastmcp.client.transports import StreamableHttpTransport# Create the transport with your LiteLLM MCP server URL and auth headers-server_url = "<your-litellm-proxy-base-url>/mcp"+server_url = "litellm_proxy"transport = StreamableHttpTransport(server_url,headers={@@ -557,7 +575,7 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \{"type": "mcp","server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp",+ "server_url": "litellm_proxy","require_approval": "never","headers": {"x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",diff --git a/litellm/experimental_mcp_client/tools.py b/litellm/experimental_mcp_client/tools.pyindex cdc26af4b7f..bfbd3f96a5c 100644--- a/litellm/experimental_mcp_client/tools.py+++ b/litellm/experimental_mcp_client/tools.py@@ -6,6 +6,7 @@ from mcp.types import CallToolRequestParams as MCPCallToolRequestParamsfrom mcp.types import CallToolResult as MCPCallToolResultfrom mcp.types import Tool as MCPToolfrom openai.types.chat import ChatCompletionToolParam+from openai.types.responses.function_tool_param import FunctionToolParamfrom openai.types.shared_params.function_definition import FunctionDefinitionfrom litellm.types.utils import ChatCompletionMessageToolCall@@ -27,6 +28,16 @@ def transform_mcp_tool_to_openai_tool(mcp_tool: MCPTool) -> ChatCompletionToolPa)+def transform_mcp_tool_to_openai_responses_api_tool(mcp_tool: MCPTool) -> FunctionToolParam:+ """Convert an MCP tool to an OpenAI Responses API tool."""+ return FunctionToolParam(+ name=mcp_tool.name,+ parameters=mcp_tool.inputSchema,+ strict=False,+ type="function",+ description=mcp_tool.description or "",+ )+async def load_mcp_tools(session: ClientSession, format: Literal["mcp", "openai"] = "mcp") -> Union[List[MCPTool], List[ChatCompletionToolParam]]:diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 8fc44b60a6c..0cab62c71be 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -5,14 +5,14 @@ model_list:- model_name: openai/*litellm_params:model: openai/*--guardrails:- - guardrail_name: "bedrock-pre-guard"+ - model_name: gemini/*litellm_params:- guardrail: bedrock # supported values: "aporia", "bedrock", "lakera"- mode: "during_call"- guardrailIdentifier: ff6ujrregl1q- guardrailVersion: "DRAFT"+ model: gemini/*litellm_settings:- callbacks: ["datadog_llm_observability"]\ No newline at end of file+ callbacks: ["datadog_llm_observability"]++mcp_servers:+ # HTTP Streamable Server+ deepwiki_mcp:+ url: "https://mcp.deepwiki.com/mcp"diff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex 888bf496d9a..07459547a0a 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -89,6 +89,137 @@ def mock_responses_api_response(})+async def aresponses_api_with_mcp(+ input: Union[str, ResponseInputParam],+ model: str,+ include: Optional[List[ResponseIncludable]] = None,+ instructions: Optional[str] = None,+ max_output_tokens: Optional[int] = None,+ prompt: Optional[PromptObject] = None,+ metadata: Optional[Dict[str, Any]] = None,+ parallel_tool_calls: Optional[bool] = None,+ previous_response_id: Optional[str] = None,+ reasoning: Optional[Reasoning] = None,+ store: Optional[bool] = None,+ background: Optional[bool] = None,+ stream: Optional[bool] = None,+ temperature: Optional[float] = None,+ text: Optional[ResponseTextConfigParam] = None,+ tool_choice: Optional[ToolChoice] = None,+ tools: Optional[Iterable[ToolParam]] = None,+ top_p: Optional[float] = None,+ truncation: Optional[Literal["auto", "disabled"]] = None,+ user: Optional[str] = None,+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.+ # The extra values given here take precedence over values defined on the client or passed to this method.+ extra_headers: Optional[Dict[str, Any]] = None,+ extra_query: Optional[Dict[str, Any]] = None,+ extra_body: Optional[Dict[str, Any]] = None,+ timeout: Optional[Union[float, httpx.Timeout]] = None,+ # LiteLLM specific params,+ custom_llm_provider: Optional[str] = None,+ **kwargs,+) -> Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator]:+ """+ Async version of responses API with MCP integration.++ When MCP tools with server_url="litellm_proxy" are provided, this function will:+ 1. Get available tools from the MCP server manager+ 2. Insert the tools into the messages/input+ 3. Call the standard responses API+ 4. If require_approval="never" and tool calls are returned, automatically execute them+ """+ from litellm.responses.mcp.litellm_proxy_mcp_handler import (+ LiteLLM_Proxy_MCP_Handler,+ )++ # Parse MCP tools and separate from other tools+ mcp_tools_with_litellm_proxy, 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)++ # Combine with other tools+ all_tools = openai_tools + other_tools if (openai_tools or other_tools) else None++ # Prepare call parameters for reuse+ call_params = {+ "include": include,+ "instructions": instructions,+ "max_output_tokens": max_output_tokens,+ "prompt": prompt,+ "metadata": metadata,+ "parallel_tool_calls": parallel_tool_calls,+ "reasoning": reasoning,+ "store": store,+ "background": background,+ "stream": stream,+ "temperature": temperature,+ "text": text,+ "tool_choice": tool_choice,+ "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,+ }++ # 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+ )++ # Check if we need to auto-execute tool calls (only for non-streaming responses)+ if (mcp_tools_with_litellm_proxy 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)++ if tool_calls:+ user_api_key_auth = kwargs.get("litellm_metadata", {}).get("user_api_key_auth")+ tool_results = await LiteLLM_Proxy_MCP_Handler._execute_tool_calls(tool_calls=tool_calls, user_api_key_auth=user_api_key_auth)++ if tool_results:+ follow_up_input = LiteLLM_Proxy_MCP_Handler._create_follow_up_input(+ response=response,+ tool_results=tool_results,+ original_input=input+ )++ 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+ )++ # Add custom output elements to the final response+ if isinstance(final_response, ResponsesAPIResponse):+ final_response = LiteLLM_Proxy_MCP_Handler._add_mcp_output_elements_to_response(+ response=final_response,+ mcp_tools_fetched=mcp_tools_fetched,+ tool_results=tool_results+ )+ return final_response++ return response++@clientasync def aresponses(@@ -182,6 +313,10 @@ async def aresponses(litellm_metadata=kwargs.get("litellm_metadata", {}),custom_llm_provider=custom_llm_provider,)++ if response is None:+ raise ValueError(f"Got an unexpected None response from the Responses API: {response}")+return responseexcept Exception as e:raise litellm.exception_type(@@ -229,6 +364,10 @@ def responses(Synchronous version of the Responses API.Uses the synchronous HTTP handler to make requests."""+ 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@@ -238,7 +377,9 @@ def responses(# get llm provider logiclitellm_params = GenericLiteLLMParams(**kwargs)- ## MOCK RESPONSE LOGIC+ #########################################################+ # MOCK RESPONSE LOGIC+ #########################################################if litellm_params.mock_response and isinstance(litellm_params.mock_response, str):@@ -257,6 +398,13 @@ def responses(api_base=litellm_params.api_base,api_key=litellm_params.api_key,)+ #########################################################+ # Native MCP Responses API+ #########################################################+ if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(tools=tools):+ return aresponses_api_with_mcp(+ **local_vars,+ )# get provider configresponses_api_provider_config: Optional[BaseResponsesAPIConfig] = (diff --git a/litellm/responses/mcp/litellm_proxy_mcp_handler.py b/litellm/responses/mcp/litellm_proxy_mcp_handler.pynew file mode 100644index 00000000000..c6bd541403a--- /dev/null+++ b/litellm/responses/mcp/litellm_proxy_mcp_handler.py@@ -0,0 +1,354 @@+from typing import 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+++class LiteLLM_Proxy_MCP_Handler:+ """+ Helper class with static methods for MCP integration with Responses API.++ This handles when a user passes mcp server_url="litellm_proxy" in their tools.+ """++ @staticmethod+ def _should_use_litellm_mcp_gateway(tools: Optional[Iterable[ToolParam]]) -> bool:+ """+ Returns True if the user passed a MCP tool with server_url="litellm_proxy"+ """+ if tools:+ for tool in tools:+ if (isinstance(tool, dict) and+ tool.get("type") == "mcp" and+ tool.get("server_url") == "litellm_proxy"):+ return True+ return False++ @staticmethod+ def _parse_mcp_tools(tools: Optional[Iterable[ToolParam]]) -> Tuple[List[ToolParam], List[Any]]:+ """+ Parse tools and separate MCP tools with litellm_proxy from other tools.++ Returns:+ Tuple of (mcp_tools_with_litellm_proxy, other_tools)+ """+ mcp_tools_with_litellm_proxy: List[ToolParam] = []+ other_tools: List[Any] = []++ if tools:+ for tool in tools:+ if (isinstance(tool, dict) and+ tool.get("type") == "mcp" and+ tool.get("server_url") == "litellm_proxy"):+ mcp_tools_with_litellm_proxy.append(tool)+ else:+ other_tools.append(tool)++ 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,+ )++ return await global_mcp_server_manager.list_tools(user_api_key_auth=user_api_key_auth)++ @staticmethod+ def _transform_mcp_tools_to_openai(mcp_tools: List[Any]) -> List[Any]:+ """Transform MCP tools to OpenAI-compatible format."""+ from litellm.experimental_mcp_client.tools import (+ transform_mcp_tool_to_openai_responses_api_tool,+ )++ openai_tools = []+ for mcp_tool in mcp_tools:+ openai_tool = transform_mcp_tool_to_openai_responses_api_tool(mcp_tool)+ openai_tools.append(openai_tool)++ return openai_tools++ @staticmethod+ def _should_auto_execute_tools(+ mcp_tools_with_litellm_proxy: Union[List[Dict[str, Any]], List[ToolParam]],+ ) -> bool:+ """Check if we should auto-execute tool calls.++ Only auto-execute tools if user passed a MCP tool with require_approval set to "never".+++ """+ for tool in mcp_tools_with_litellm_proxy:+ if isinstance(tool, dict):+ if tool.get("require_approval") == "never":+ return True+ elif getattr(tool, "require_approval", None) == "never":+ return True+ return False++ @staticmethod+ def _extract_tool_calls_from_response(response: ResponsesAPIResponse) -> List[Any]:+ """Extract tool calls from the response output."""+ tool_calls: List[Any] = []+ for output_item in response.output:+ # Check if this is a function call output item+ if (isinstance(output_item, dict) and+ output_item.get("type") == "function_call"):+ tool_calls.append(output_item)+ elif hasattr(output_item, 'type') and getattr(output_item, 'type') == "function_call":+ # Handle pydantic model case+ tool_calls.append(output_item)++ return tool_calls++ @staticmethod+ def _extract_tool_call_details(tool_call) -> Tuple[Optional[str], Optional[str], Optional[str]]:+ """Extract tool name, arguments, and call_id from a tool call."""+ if isinstance(tool_call, dict):+ tool_name = tool_call.get("name")+ tool_arguments = tool_call.get("arguments")+ tool_call_id = tool_call.get("call_id") or tool_call.get("id")+ else:+ tool_name = getattr(tool_call, "name", None)+ tool_arguments = getattr(tool_call, "arguments", None)+ tool_call_id = getattr(tool_call, "call_id", None) or getattr(tool_call, "id", None)++ return tool_name, tool_arguments, tool_call_id++ @staticmethod+ def _parse_tool_arguments(tool_arguments: Any) -> Dict[str, Any]:+ """Parse tool arguments, handling both string and dict formats."""+ import json++ if isinstance(tool_arguments, str):+ try:+ return json.loads(tool_arguments)+ except json.JSONDecodeError:+ return {}+ else:+ return tool_arguments or {}++ @staticmethod+ def _parse_mcp_result(result: Any) -> str:+ """Parse MCP tool call result and extract meaningful content."""+ if not result or not hasattr(result, 'content') or not result.content:+ return "Tool executed successfully"++ # Import MCP content types for isinstance checks+ try:+ from mcp.types import EmbeddedResource, ImageContent, TextContent+ except ImportError:+ # Fallback to generic handling if MCP types not available+ return "Tool executed successfully"++ text_parts = []+ other_content_types = []++ for content_item in result.content:+ if isinstance(content_item, TextContent):+ # Text content - extract the text+ text_parts.append(str(content_item.text))+ elif isinstance(content_item, ImageContent):+ # Image content+ other_content_types.append("Image")+ elif isinstance(content_item, EmbeddedResource):+ # Embedded resource+ other_content_types.append("EmbeddedResource")+ else:+ # Other unknown content types+ content_type = type(content_item).__name__+ other_content_types.append(content_type)++ # Combine text parts if any+ result_text = " ".join(text_parts) if text_parts else ""++ # Add info about other content types+ if other_content_types:+ other_info = f"[Generated {', '.join(other_content_types)}]"+ result_text = f"{result_text} {other_info}".strip()++ return result_text or "Tool executed successfully"++ @staticmethod+ async def _execute_tool_calls(+ tool_calls: List[Any],+ user_api_key_auth: Any+ ) -> List[Dict[str, Any]]:+ """Execute tool calls and return results."""+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )++ tool_results = []+ tool_call_id: Optional[str] = None+ for tool_call in tool_calls:+ try:+ tool_name, tool_arguments, tool_call_id = LiteLLM_Proxy_MCP_Handler._extract_tool_call_details(tool_call)++ if not tool_name:+ verbose_logger.warning(f"Tool call missing name: {tool_call}")+ continue++ parsed_arguments = LiteLLM_Proxy_MCP_Handler._parse_tool_arguments(tool_arguments)++ result = await global_mcp_server_manager.call_tool(+ name=tool_name,+ arguments=parsed_arguments,+ user_api_key_auth=user_api_key_auth,+ )++ # Format result for inclusion in response+ result_text = LiteLLM_Proxy_MCP_Handler._parse_mcp_result(result)+ tool_results.append({+ "tool_call_id": tool_call_id,+ "result": result_text+ })++ except Exception as e:+ verbose_logger.exception(f"Error executing MCP tool call: {e}")+ tool_results.append({+ "tool_call_id": tool_call_id,+ "result": f"Error executing tool: {str(e)}"+ })++ return tool_results++ @staticmethod+ def _create_follow_up_input(+ response: ResponsesAPIResponse,+ tool_results: List[Dict[str, Any]],+ original_input: Any = None+ ) -> List[Any]:+ """Create follow-up input with tool results in proper format."""+ follow_up_input: List[Any] = []++ # Add original user input if available to maintain conversation context+ if original_input:+ if isinstance(original_input, str):+ follow_up_input.append({+ "type": "message",+ "role": "user",+ "content": original_input+ })+ elif isinstance(original_input, list):+ follow_up_input.extend(original_input)+ else:+ follow_up_input.append(original_input)++ # Add the assistant message with function calls+ assistant_message_content: List[Any] = []+ function_calls: List[Dict[str, Any]] = []++ for output_item in response.output:+ if isinstance(output_item, dict):+ if output_item.get("type") == "function_call":+ call_id = output_item.get("call_id") or output_item.get("id")+ name = output_item.get("name")+ arguments = output_item.get("arguments")++ # Only add if we have required fields+ if call_id and name:+ function_calls.append({+ "type": "function_call",+ "call_id": call_id,+ "name": name,+ "arguments": arguments+ })+ elif output_item.get("type") == "message":+ # Extract content from message+ content = output_item.get("content", [])+ if isinstance(content, list):+ assistant_message_content.extend(content)+ else:+ assistant_message_content.append(content)++ # Add assistant message with content and function calls+ if assistant_message_content or function_calls:+ follow_up_input.append({+ "type": "message",+ "role": "assistant",+ "content": assistant_message_content+ })++ # Add function calls after assistant message+ for function_call in function_calls:+ follow_up_input.append(function_call)++ # Add tool results (function call outputs)+ for tool_result in tool_results:+ follow_up_input.append({+ "type": "function_call_output",+ "call_id": tool_result["tool_call_id"],+ "output": tool_result["result"]+ })++ return follow_up_input++ @staticmethod+ async def _make_follow_up_call(+ follow_up_input: List[Any],+ model: str,+ all_tools: Optional[List[Any]],+ response_id: str,+ **call_params: Any+ ) -> Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator]:+ """Make follow-up response API call with tool results."""+ return await aresponses(+ input=follow_up_input,+ model=model,+ tools=all_tools, # Keep tools for potential future calls+ previous_response_id=response_id, # Link to previous response+ **call_params+ )++ @staticmethod+ def _add_mcp_output_elements_to_response(+ response: ResponsesAPIResponse,+ mcp_tools_fetched: List[Any],+ tool_results: List[Dict[str, Any]]+ ) -> ResponsesAPIResponse:+ """Add custom output elements to the final response for MCP tool execution."""+ # Import the required classes for creating output items+ import json+ import uuid++ from litellm.types.responses.main import GenericResponseOutputItem, OutputText++ # Create output element for initial MCP tools+ mcp_tools_output = GenericResponseOutputItem(+ type="mcp_tools_fetched",+ id=f"mcp_tools_{uuid.uuid4().hex[:8]}",+ status="completed",+ role="system",+ content=[+ OutputText(+ type="output_text",+ text=json.dumps(mcp_tools_fetched, indent=2, default=str),+ annotations=[]+ )+ ]+ )++ # Create output element for tool execution results+ tool_results_output = GenericResponseOutputItem(+ type="tool_execution_results",+ id=f"tool_results_{uuid.uuid4().hex[:8]}",+ status="completed",+ role="system",+ content=[+ OutputText(+ type="output_text",+ text=json.dumps(tool_results, indent=2, default=str),+ annotations=[]+ )+ ]+ )++ # Add the new output elements to the response+ response.output.append(mcp_tools_output.model_dump()) # type: ignore+ response.output.append(tool_results_output.model_dump()) # type: ignore++ return responsediff --git a/tests/mcp_tests/test_aresponses_api_with_mcp.py b/tests/mcp_tests/test_aresponses_api_with_mcp.pynew file mode 100644index 00000000000..500bd8bcc06--- /dev/null+++ b/tests/mcp_tests/test_aresponses_api_with_mcp.py@@ -0,0 +1,253 @@+import os+import sys+import pytest+from typing import List, Any, cast++sys.path.insert(0, os.path.abspath("../../.."))++# Import required modules+from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler+from litellm.types.llms.openai import ResponsesAPIResponse, OpenAIMcpServerTool+++class MockUserAPIKeyAuth:+ """Mock UserAPIKeyAuth for testing"""+ def __init__(self):+ self.api_key = "test_key"+ self.user_id = "test_user"+ self.team_id = "test_team"+ self.user_email = "[email protected]"+ self.max_budget = 100.0+ self.spend = 0.0+ self.models = []+ self.aliases = {}+ self.config = {}+ self.permissions = {}+ self.metadata = {}+ self.object_permission_id = "test_permission_id"+++async def test_mcp_helper_methods():+ """Test the core MCP helper methods in LiteLLM_Proxy_MCP_Handler"""++ # Test _should_use_litellm_mcp_gateway+ mcp_tools: List[Any] = [+ {+ "type": "mcp",+ "server_url": "litellm_proxy",+ "require_approval": "never"+ }+ ]++ other_tools: List[Any] = [+ {+ "type": "function",+ "name": "get_weather",+ "description": "Get weather info",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {"type": "string"}+ }+ }+ }+ ]++ # Should return True for MCP tools with litellm_proxy+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(mcp_tools) == True++ # Should return False for other tools+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(other_tools) == False++ # Should return False for None+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(None) == False++ # Test _parse_mcp_tools+ mixed_tools = mcp_tools + other_tools+ mcp_parsed, other_parsed = LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(mixed_tools)++ assert len(mcp_parsed) == 1+ assert len(other_parsed) == 1+ assert mcp_parsed[0]["type"] == "mcp"+ assert other_parsed[0]["type"] == "function"++ # Test _should_auto_execute_tools+ mcp_tools_never = [{"require_approval": "never"}]+ mcp_tools_always = [{"require_approval": "always"}]++ assert LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(mcp_tools_never) == True+ assert LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(mcp_tools_always) == False++ print("✓ MCP helper methods test passed!")+++async def test_mcp_output_elements_addition():+ """Test adding MCP output elements to response"""++ # Create a mock response+ mock_response = ResponsesAPIResponse(+ **{ # type: ignore+ "id": "test_response_id",+ "object": "response",+ "created_at": 1234567890,+ "status": "completed",+ "error": None,+ "incomplete_details": None,+ "instructions": None,+ "max_output_tokens": None,+ "model": "gpt-4o",+ "output": [+ {+ "type": "message",+ "id": "msg_123",+ "status": "completed",+ "role": "assistant",+ "content": [+ {+ "type": "output_text",+ "text": "Hello, world!",+ "annotations": []+ }+ ]+ }+ ],+ "parallel_tool_calls": True,+ "previous_response_id": None,+ "reasoning": {"effort": None, "summary": None},+ "store": True,+ "temperature": 1.0,+ "text": {"format": {"type": "text"}},+ "tool_choice": "auto",+ "tools": [],+ "top_p": 1.0,+ "truncation": "disabled",+ "usage": {+ "input_tokens": 10,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 5,+ "output_tokens_details": {"reasoning_tokens": 0},+ "total_tokens": 15+ },+ "user": None,+ "metadata": {}+ }+ )++ # Mock MCP tools and tool results+ mock_mcp_tools = [+ {+ "name": "test_tool",+ "description": "A test tool",+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {"type": "string"}+ }+ }+ }+ ]++ mock_tool_results = [+ {+ "tool_call_id": "call_123",+ "result": "Tool executed successfully"+ }+ ]++ # Test adding output elements+ updated_response = LiteLLM_Proxy_MCP_Handler._add_mcp_output_elements_to_response(+ response=mock_response,+ mcp_tools_fetched=mock_mcp_tools,+ tool_results=mock_tool_results+ )++ # Verify output elements were added+ assert len(updated_response.output) == 3 # Original + 2 new elements++ # Check that MCP tools output was added - handle both dict and object cases+ mcp_tools_output = updated_response.output[1]+ if hasattr(mcp_tools_output, 'type'):+ # Handle as object with attributes+ output_obj = cast(Any, mcp_tools_output)+ assert output_obj.type == "mcp_tools_fetched"+ assert output_obj.role == "system"+ assert output_obj.status == "completed"+ elif isinstance(mcp_tools_output, dict):+ # Handle as dictionary+ assert mcp_tools_output["type"] == "mcp_tools_fetched"+ assert mcp_tools_output["role"] == "system"+ assert mcp_tools_output["status"] == "completed"++ # Check that tool results output was added+ tool_results_output = updated_response.output[2]+ if hasattr(tool_results_output, 'type'):+ # Handle as object with attributes+ output_obj = cast(Any, tool_results_output)+ assert output_obj.type == "tool_execution_results"+ assert output_obj.role == "system"+ assert output_obj.status == "completed"+ elif isinstance(tool_results_output, dict):+ # Handle as dictionary+ assert tool_results_output["type"] == "tool_execution_results"+ assert tool_results_output["role"] == "system"+ assert tool_results_output["status"] == "completed"++ print("✓ MCP output elements addition test passed!")+++async def test_aresponses_api_with_mcp_mock_integration():+ """+ Test the core MCP integration logic without complex external mocking.+ This focuses on verifying the MCP tool parsing and handling works correctly.+ """+ # Define MCP tools with litellm_proxy server_url and require_approval="never"+ mcp_tools: List[OpenAIMcpServerTool] = [+ {+ "type": "mcp",+ "server_url": "litellm_proxy",+ "require_approval": "never",+ "server_label": "test_server"+ }+ ]++ # Test the helper methods that the integration relies on+ from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler++ # Test 1: Verify MCP tools are detected correctly+ should_use_mcp = LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(cast(Any, mcp_tools))+ assert should_use_mcp == True, "Should detect MCP tools with litellm_proxy server_url"++ # Test 2: Verify auto-execution detection works+ should_auto_execute = LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(cast(Any, mcp_tools))+ assert should_auto_execute == True, "Should auto-execute tools with require_approval='never'"++ # Test 3: Verify tool parsing works correctly+ mcp_parsed, other_parsed = LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(cast(Any, mcp_tools))+ assert len(mcp_parsed) == 1, "Should parse one MCP tool"+ assert len(other_parsed) == 0, "Should have no other tools"+ assert mcp_parsed[0]["type"] == "mcp", "Parsed tool should be MCP type"+ assert mcp_parsed[0]["server_url"] == "litellm_proxy", "Should preserve server_url"+ assert mcp_parsed[0].get("require_approval") == "never", "Should preserve require_approval"++ # Test 4: Test with mixed tools+ mixed_tools = mcp_tools + [+ {+ "type": "function",+ "name": "test_function",+ "parameters": {"type": "object"}+ }+ ]++ mcp_parsed, other_parsed = LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(cast(Any, mixed_tools))+ assert len(mcp_parsed) == 1, "Should parse one MCP tool from mixed list"+ assert len(other_parsed) == 1, "Should have one other tool from mixed list"++ print("✓ MCP integration core logic test completed successfully!")+ print(f"MCP tools detected: {should_use_mcp}")+ print(f"Auto-execute enabled: {should_auto_execute}")+ print(f"MCP tools parsed: {len(mcp_parsed)}")+ print(f"Other tools parsed: {len(other_parsed)}")+