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: update MCP handler invocation to pass full call context from main.py

Yuta Saito8cccf3e9f043
diff --git a/litellm/main.py b/litellm/main.py
index 42840793d3f..47e6aae7d8f 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -1098,54 +1098,11 @@ def completion( # type: ignore # noqa: PLR0915
handle_chat_completion_with_mcp,
)
- call_args_for_mcp: Dict[str, Any] = {
- "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,
- }
- call_args_for_mcp.update(kwargs)
-
+ mcp_handler_context = locals().copy()
completion_callable = globals().get("acompletion")
mcp_result = run_async_function(
handle_chat_completion_with_mcp,
- call_args_for_mcp,
+ mcp_handler_context,
completion_callable,
)
if mcp_result is not None:
diff --git a/litellm/responses/mcp/chat_completions_handler.py b/litellm/responses/mcp/chat_completions_handler.py
index d91d13efdf4..1957e5fa92e 100644
--- a/litellm/responses/mcp/chat_completions_handler.py
+++ b/litellm/responses/mcp/chat_completions_handler.py
@@ -21,6 +21,62 @@ from litellm.utils import CustomStreamWrapper
CompletionCallable = Callable[..., Awaitable[Union[ModelResponse, CustomStreamWrapper]]]
+_CHAT_COMPLETION_CALL_ARG_KEYS = [
+ "model",
+ "messages",
+ "functions",
+ "function_call",
+ "timeout",
+ "temperature",
+ "top_p",
+ "n",
+ "stream",
+ "stream_options",
+ "stop",
+ "max_tokens",
+ "max_completion_tokens",
+ "modalities",
+ "prediction",
+ "audio",
+ "presence_penalty",
+ "frequency_penalty",
+ "logit_bias",
+ "user",
+ "response_format",
+ "seed",
+ "tools",
+ "tool_choice",
+ "parallel_tool_calls",
+ "logprobs",
+ "top_logprobs",
+ "deployment_id",
+ "reasoning_effort",
+ "verbosity",
+ "safety_identifier",
+ "service_tier",
+ "base_url",
+ "api_version",
+ "api_key",
+ "model_list",
+ "extra_headers",
+ "thinking",
+ "web_search_options",
+ "shared_session",
+]
+
+
+def _build_call_args_from_context(call_context: Dict[str, Any]) -> Dict[str, Any]:
+ """Build kwargs for `acompletion` from the `completion` call context."""
+
+ call_args = {
+ key: call_context.get(key)
+ for key in _CHAT_COMPLETION_CALL_ARG_KEYS
+ if key in call_context
+ }
+ additional_kwargs = dict(call_context.get("kwargs") or {})
+ call_args.update(additional_kwargs)
+ return call_args
+
async def _call_acompletion_internal(
completion_callable: CompletionCallable, **call_args: Any
@@ -34,11 +90,13 @@ async def _call_acompletion_internal(
async def handle_chat_completion_with_mcp(
- call_args: Dict[str, Any],
+ call_context: Dict[str, Any],
completion_callable: CompletionCallable,
) -> Optional[Union[ModelResponse, CustomStreamWrapper]]:
"""Handle MCP-enabled tool execution for chat completion requests."""
+ call_args = _build_call_args_from_context(call_context)
+
tools = call_args.get("tools")
if not tools:
return None
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 1eab01d5b86..96e7c39aee2 100644
--- a/tests/test_litellm/responses/mcp/test_chat_completions_handler.py
+++ b/tests/test_litellm/responses/mcp/test_chat_completions_handler.py
@@ -55,20 +55,31 @@ async def test_handle_chat_completion_without_auto_execution_calls_model(monkeyp
"_should_auto_execute_tools",
staticmethod(lambda **_: False),
)
+ captured_secret_fields = {}
+
+ def mock_extract(**kwargs):
+ captured_secret_fields["value"] = kwargs.get("secret_fields")
+ return (None, None, None, None)
+
monkeypatch.setattr(
ResponsesAPIRequestUtils,
"extract_mcp_headers_from_request",
- staticmethod(lambda **_: (None, None, None, None)),
+ staticmethod(mock_extract),
)
- call_args = {"tools": tools, "messages": []}
- result = await handle_chat_completion_with_mcp(call_args, completion_callable)
+ call_context = {
+ "tools": tools,
+ "messages": [],
+ "kwargs": {"secret_fields": {"api_key": "value"}},
+ }
+ result = await handle_chat_completion_with_mcp(call_context, completion_callable)
assert result == "ok"
completion_callable.assert_awaited_once()
kwargs = completion_callable.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
@@ -144,8 +155,8 @@ async def test_handle_chat_completion_auto_exec_performs_follow_up(monkeypatch):
staticmethod(lambda **_: (None, None, None, None)),
)
- call_args = {"tools": tools, "messages": ["msg"], "stream": True}
- result = await handle_chat_completion_with_mcp(call_args, completion_callable)
+ call_context = {"tools": tools, "messages": ["msg"], "stream": True}
+ result = await handle_chat_completion_with_mcp(call_context, completion_callable)
assert result is follow_up_response
assert completion_callable.await_count == 2