Skip to content

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

fix: event loop nesting issue in MCP chat completions with streaming

Yuta Saitoba43f742ab86
diff --git a/litellm/main.py b/litellm/main.py
index c1c4efd943f..8fce4793ead 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -1097,18 +1097,58 @@ def completion( # type: ignore # noqa: PLR0915
skip_mcp_handler = kwargs.pop("_skip_mcp_handler", False)
if not skip_mcp_handler and tools:
from litellm.responses.mcp.chat_completions_handler import (
- handle_chat_completion_with_mcp,
+ acompletion_with_mcp,
)
-
- mcp_handler_context = locals().copy()
- completion_callable = globals().get("acompletion")
- mcp_result = run_async_function(
- handle_chat_completion_with_mcp,
- mcp_handler_context,
- completion_callable,
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import (
+ LiteLLM_Proxy_MCP_Handler,
)
- if mcp_result is not None:
- return mcp_result
+
+ # Check if MCP tools are present (following responses pattern)
+ if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(tools=tools):
+ # Return coroutine - acompletion will await it
+ return acompletion_with_mcp(
+ model=model,
+ messages=messages,
+ functions=functions,
+ function_call=function_call,
+ timeout=timeout,
+ temperature=temperature,
+ top_p=top_p,
+ n=n,
+ stream=stream,
+ stream_options=stream_options,
+ stop=stop,
+ max_tokens=max_tokens,
+ max_completion_tokens=max_completion_tokens,
+ modalities=modalities,
+ prediction=prediction,
+ audio=audio,
+ presence_penalty=presence_penalty,
+ frequency_penalty=frequency_penalty,
+ logit_bias=logit_bias,
+ user=user,
+ response_format=response_format,
+ seed=seed,
+ tools=tools,
+ tool_choice=tool_choice,
+ parallel_tool_calls=parallel_tool_calls,
+ logprobs=logprobs,
+ top_logprobs=top_logprobs,
+ deployment_id=deployment_id,
+ reasoning_effort=reasoning_effort,
+ verbosity=verbosity,
+ safety_identifier=safety_identifier,
+ service_tier=service_tier,
+ base_url=base_url,
+ api_version=api_version,
+ api_key=api_key,
+ model_list=model_list,
+ extra_headers=extra_headers,
+ thinking=thinking,
+ web_search_options=web_search_options,
+ shared_session=shared_session,
+ **kwargs,
+ )
######### unpacking kwargs #####################
args = locals()
api_base = kwargs.get("api_base", None)
diff --git a/litellm/responses/mcp/chat_completions_handler.py b/litellm/responses/mcp/chat_completions_handler.py
index 1957e5fa92e..641dc60ebd6 100644
--- a/litellm/responses/mcp/chat_completions_handler.py
+++ b/litellm/responses/mcp/chat_completions_handler.py
@@ -6,6 +6,7 @@ from typing import (
Callable,
Dict,
Iterable,
+ List,
Optional,
Union,
cast,
@@ -197,3 +198,150 @@ async def handle_chat_completion_with_mcp(
follow_up_call_args["stream"] = call_args.get("stream")
return await _call_acompletion_internal(completion_callable, **follow_up_call_args)
+
+
+async def acompletion_with_mcp(
+ model: str,
+ messages: List,
+ tools: Optional[List] = None,
+ **kwargs: Any,
+) -> Union[ModelResponse, CustomStreamWrapper]:
+ """
+ Async completion with MCP integration.
+
+ This function handles MCP tool integration following the same pattern as aresponses_api_with_mcp.
+ It's designed to be called from the synchronous completion() function and return a coroutine.
+
+ When MCP tools with server_url="litellm_proxy" are provided, this function will:
+ 1. Get available tools from the MCP server manager
+ 2. Transform them to OpenAI format
+ 3. Call acompletion with the transformed tools
+ 4. If require_approval="never" and tool calls are returned, automatically execute them
+ 5. Make a follow-up call with the tool results
+ """
+ from litellm import acompletion as litellm_acompletion
+
+ # Parse MCP tools and separate from other tools
+ (
+ mcp_tools_with_litellm_proxy,
+ other_tools,
+ ) = LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(tools)
+
+ if not mcp_tools_with_litellm_proxy:
+ # No MCP tools, proceed with regular completion
+ return await litellm_acompletion(
+ model=model,
+ messages=messages,
+ tools=tools,
+ **kwargs,
+ )
+
+ # Extract user_api_key_auth from metadata or kwargs
+ user_api_key_auth = kwargs.get("user_api_key_auth") or (
+ (kwargs.get("metadata", {}) or {}).get("user_api_key_auth")
+ )
+
+ # Process MCP tools
+ (
+ deduplicated_mcp_tools,
+ tool_server_map,
+ ) = 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(
+ deduplicated_mcp_tools,
+ target_format="chat",
+ )
+
+ # Combine with other tools
+ all_tools = openai_tools + other_tools if (openai_tools or other_tools) else None
+
+ # Determine if we should auto-execute tools
+ should_auto_execute = LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(
+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy
+ )
+
+ # Extract MCP auth headers
+ (
+ mcp_auth_header,
+ mcp_server_auth_headers,
+ oauth2_headers,
+ raw_headers,
+ ) = ResponsesAPIRequestUtils.extract_mcp_headers_from_request(
+ secret_fields=kwargs.get("secret_fields"),
+ tools=tools,
+ )
+
+ # Prepare call parameters
+ # Remove keys that shouldn't be passed to acompletion
+ clean_kwargs = {k: v for k, v in kwargs.items() if k not in ["acompletion"]}
+
+ base_call_args = {
+ "model": model,
+ "messages": messages,
+ "tools": all_tools,
+ "_skip_mcp_handler": True, # Prevent recursion
+ **clean_kwargs,
+ }
+
+ # If not auto-executing, just make the call with transformed tools
+ if not should_auto_execute:
+ return await litellm_acompletion(**base_call_args)
+
+ # For auto-execute: disable streaming for initial call
+ stream = kwargs.get("stream", False)
+ mock_tool_calls = base_call_args.pop("mock_tool_calls", None)
+
+ initial_call_args = dict(base_call_args)
+ initial_call_args["stream"] = False
+ if mock_tool_calls is not None:
+ initial_call_args["mock_tool_calls"] = mock_tool_calls
+
+ # Make initial call
+ initial_response = await litellm_acompletion(**initial_call_args)
+
+ if not isinstance(initial_response, ModelResponse):
+ return initial_response
+
+ # Extract tool calls from response
+ tool_calls = LiteLLM_Proxy_MCP_Handler._extract_tool_calls_from_chat_response(
+ response=initial_response
+ )
+
+ if not tool_calls:
+ # No tool calls, return response or retry with streaming if needed
+ if stream:
+ retry_args = dict(base_call_args)
+ retry_args["stream"] = stream
+ return await litellm_acompletion(**retry_args)
+ return initial_response
+
+ # Execute tool calls
+ tool_results = await LiteLLM_Proxy_MCP_Handler._execute_tool_calls(
+ tool_server_map=tool_server_map,
+ tool_calls=tool_calls,
+ user_api_key_auth=user_api_key_auth,
+ mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
+ oauth2_headers=oauth2_headers,
+ raw_headers=raw_headers,
+ )
+
+ if not tool_results:
+ return initial_response
+
+ # Create follow-up messages with tool results
+ follow_up_messages = LiteLLM_Proxy_MCP_Handler._create_follow_up_messages_for_chat(
+ original_messages=messages,
+ response=initial_response,
+ tool_results=tool_results,
+ )
+
+ # Make follow-up call with original stream setting
+ follow_up_call_args = dict(base_call_args)
+ follow_up_call_args["messages"] = follow_up_messages
+ follow_up_call_args["stream"] = stream
+
+ return await litellm_acompletion(**follow_up_call_args)
diff --git a/tests/test_litellm/responses/mcp/test_chat_completions_handler.py b/tests/test_litellm/responses/mcp/test_chat_completions_handler.py
index 96e7c39aee2..03a749a8083 100644
--- a/tests/test_litellm/responses/mcp/test_chat_completions_handler.py
+++ b/tests/test_litellm/responses/mcp/test_chat_completions_handler.py
@@ -1,10 +1,10 @@
import pytest
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, patch
from litellm.types.utils import ModelResponse
from litellm.responses.mcp.chat_completions_handler import (
- handle_chat_completion_with_mcp,
+ acompletion_with_mcp,
)
from litellm.responses.mcp.litellm_proxy_mcp_handler import (
LiteLLM_Proxy_MCP_Handler,
@@ -13,19 +13,24 @@ from litellm.responses.utils import ResponsesAPIRequestUtils
@pytest.mark.asyncio
-async def test_handle_chat_completion_returns_none_without_tools():
- completion_callable = AsyncMock()
+async def test_acompletion_with_mcp_returns_normal_completion_without_tools(monkeypatch):
+ mock_acompletion = AsyncMock(return_value="normal_response")
- result = await handle_chat_completion_with_mcp({}, completion_callable)
+ with patch("litellm.acompletion", mock_acompletion):
+ result = await acompletion_with_mcp(
+ model="test-model",
+ messages=[],
+ tools=None,
+ )
- assert result is None
- completion_callable.assert_not_awaited()
+ assert result == "normal_response"
+ mock_acompletion.assert_awaited_once()
@pytest.mark.asyncio
-async def test_handle_chat_completion_without_auto_execution_calls_model(monkeypatch):
+async def test_acompletion_with_mcp_without_auto_execution_calls_model(monkeypatch):
tools = [{"type": "function", "function": {"name": "tool"}}]
- completion_callable = AsyncMock(return_value="ok")
+ mock_acompletion = AsyncMock(return_value="ok")
monkeypatch.setattr(
LiteLLM_Proxy_MCP_Handler,
@@ -35,7 +40,7 @@ async def test_handle_chat_completion_without_auto_execution_calls_model(monkeyp
monkeypatch.setattr(
LiteLLM_Proxy_MCP_Handler,
"_parse_mcp_tools",
- staticmethod(lambda tools: (tools, {})),
+ staticmethod(lambda tools: (tools, [])),
)
async def mock_process(**_):
return ([], {})
@@ -67,23 +72,25 @@ async def test_handle_chat_completion_without_auto_execution_calls_model(monkeyp
staticmethod(mock_extract),
)
- call_context = {
- "tools": tools,
- "messages": [],
- "kwargs": {"secret_fields": {"api_key": "value"}},
- }
- result = await handle_chat_completion_with_mcp(call_context, completion_callable)
+ with patch("litellm.acompletion", mock_acompletion):
+ result = await acompletion_with_mcp(
+ model="test-model",
+ messages=[],
+ tools=tools,
+ secret_fields={"api_key": "value"},
+ )
assert result == "ok"
- completion_callable.assert_awaited_once()
- kwargs = completion_callable.await_args.kwargs
+ mock_acompletion.assert_awaited_once()
+ assert mock_acompletion.await_args is not None
+ kwargs = mock_acompletion.await_args.kwargs
assert kwargs.get("_skip_mcp_handler") is True
assert kwargs.get("tools") == ["openai-tool"]
assert captured_secret_fields["value"] == {"api_key": "value"}
@pytest.mark.asyncio
-async def test_handle_chat_completion_auto_exec_performs_follow_up(monkeypatch):
+async def test_acompletion_with_mcp_auto_exec_performs_follow_up(monkeypatch):
tools = [{"type": "function", "function": {"name": "tool"}}]
initial_response = ModelResponse(
id="1",
@@ -99,7 +106,7 @@ async def test_handle_chat_completion_auto_exec_performs_follow_up(monkeypatch):
created=0,
object="chat.completion",
)
- completion_callable = AsyncMock(
+ mock_acompletion = AsyncMock(
side_effect=[initial_response, follow_up_response]
)
@@ -111,7 +118,7 @@ async def test_handle_chat_completion_auto_exec_performs_follow_up(monkeypatch):
monkeypatch.setattr(
LiteLLM_Proxy_MCP_Handler,
"_parse_mcp_tools",
- staticmethod(lambda tools: (tools, {"tool": "server"})),
+ staticmethod(lambda tools: (tools, [])),
)
async def mock_process(**_):
return (tools, {"tool": "server"})
@@ -155,13 +162,18 @@ async def test_handle_chat_completion_auto_exec_performs_follow_up(monkeypatch):
staticmethod(lambda **_: (None, None, None, None)),
)
- call_context = {"tools": tools, "messages": ["msg"], "stream": True}
- result = await handle_chat_completion_with_mcp(call_context, completion_callable)
+ with patch("litellm.acompletion", mock_acompletion):
+ result = await acompletion_with_mcp(
+ model="test-model",
+ messages=["msg"],
+ tools=tools,
+ stream=True,
+ )
assert result is follow_up_response
- assert completion_callable.await_count == 2
- first_call = completion_callable.await_args_list[0].kwargs
- second_call = completion_callable.await_args_list[1].kwargs
+ assert mock_acompletion.await_count == 2
+ first_call = mock_acompletion.await_args_list[0].kwargs
+ second_call = mock_acompletion.await_args_list[1].kwargs
assert first_call["stream"] is False
assert second_call["messages"] == ["follow-up"]
assert second_call["stream"] is True