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: completions mcp output ordering

Yuta Saito4164c9ca18ce
diff --git a/litellm/responses/mcp/chat_completions_handler.py b/litellm/responses/mcp/chat_completions_handler.py
index 0b0004d1548..d05e6c8c684 100644
--- a/litellm/responses/mcp/chat_completions_handler.py
+++ b/litellm/responses/mcp/chat_completions_handler.py
@@ -5,6 +5,7 @@ from typing import (
List,
Optional,
Union,
+ cast,
)
from litellm.responses.mcp.litellm_proxy_mcp_handler import (
@@ -174,10 +175,313 @@ async def acompletion_with_mcp(
)
return response
- # For auto-execute: disable streaming for initial call
+ # For auto-execute: handle streaming vs non-streaming differently
stream = kwargs.get("stream", False)
mock_tool_calls = base_call_args.pop("mock_tool_calls", None)
+ if stream:
+ # Streaming mode: make initial call with streaming, collect chunks, detect tool calls
+ initial_call_args = dict(base_call_args)
+ initial_call_args["stream"] = True
+ if mock_tool_calls is not None:
+ initial_call_args["mock_tool_calls"] = mock_tool_calls
+
+ # Make initial streaming call
+ initial_stream = await litellm_acompletion(**initial_call_args)
+
+ if not isinstance(initial_stream, CustomStreamWrapper):
+ # Not a stream, return as-is
+ if isinstance(initial_stream, ModelResponse):
+ _add_mcp_metadata_to_response(
+ response=initial_stream,
+ openai_tools=openai_tools,
+ )
+ return initial_stream
+
+ # Create a custom async generator that collects chunks and handles tool execution
+ from litellm.main import stream_chunk_builder
+ from litellm.types.utils import ModelResponseStream
+
+ class MCPStreamingIterator:
+ """Custom iterator that collects chunks, detects tool calls, and adds MCP metadata to final chunk."""
+
+ def __init__(self, stream_wrapper, messages, tool_server_map, user_api_key_auth,
+ mcp_auth_header, mcp_server_auth_headers, oauth2_headers, raw_headers,
+ litellm_call_id, litellm_trace_id, openai_tools, base_call_args):
+ self.stream_wrapper = stream_wrapper
+ self.messages = messages
+ self.tool_server_map = tool_server_map
+ self.user_api_key_auth = user_api_key_auth
+ self.mcp_auth_header = mcp_auth_header
+ self.mcp_server_auth_headers = mcp_server_auth_headers
+ self.oauth2_headers = oauth2_headers
+ self.raw_headers = raw_headers
+ self.litellm_call_id = litellm_call_id
+ self.litellm_trace_id = litellm_trace_id
+ self.openai_tools = openai_tools
+ self.base_call_args = base_call_args
+ self.collected_chunks: List[ModelResponseStream] = []
+ self.tool_calls: Optional[List] = None
+ self.tool_results: Optional[List] = None
+ self.complete_response: Optional[ModelResponse] = None
+ self.stream_exhausted = False
+ self.tool_execution_done = False
+ self.follow_up_stream = None
+ self.follow_up_iterator = None
+ self.follow_up_exhausted = False
+
+ async def __aiter__(self):
+ return self
+
+ def _add_mcp_list_tools_to_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream:
+ """Add mcp_list_tools to the first chunk."""
+ from litellm.types.utils import StreamingChoices
+
+ if not self.openai_tools:
+ return chunk
+
+ if hasattr(chunk, "choices") and chunk.choices:
+ for choice in chunk.choices:
+ if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta:
+ # Get existing provider_specific_fields or create new dict
+ provider_fields = (
+ getattr(choice.delta, "provider_specific_fields", None) or {}
+ )
+
+ # Add only mcp_list_tools to first chunk
+ provider_fields["mcp_list_tools"] = self.openai_tools
+
+ # Set the provider_specific_fields
+ setattr(choice.delta, "provider_specific_fields", provider_fields)
+
+ return chunk
+
+ def _add_mcp_tool_metadata_to_final_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream:
+ """Add mcp_tool_calls and mcp_call_results to the final chunk."""
+ from litellm.types.utils import StreamingChoices
+
+ if hasattr(chunk, "choices") and chunk.choices:
+ for choice in chunk.choices:
+ if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta:
+ # Get existing provider_specific_fields or create new dict
+ provider_fields = (
+ getattr(choice.delta, "provider_specific_fields", None) or {}
+ )
+
+ # Add tool_calls and tool_results if available
+ if self.tool_calls:
+ provider_fields["mcp_tool_calls"] = self.tool_calls
+ if self.tool_results:
+ provider_fields["mcp_call_results"] = self.tool_results
+
+ # Set the provider_specific_fields
+ setattr(choice.delta, "provider_specific_fields", provider_fields)
+
+ return chunk
+
+ async def __anext__(self):
+ # Phase 1: Collect and yield initial stream chunks
+ if not self.stream_exhausted:
+ # Get the iterator from the stream wrapper
+ if not hasattr(self, '_stream_iterator'):
+ self._stream_iterator = self.stream_wrapper.__aiter__()
+ # Add mcp_list_tools to the first chunk (available from the start)
+ _add_mcp_metadata_to_response(
+ response=self.stream_wrapper,
+ openai_tools=self.openai_tools,
+ )
+
+ try:
+ chunk = await self._stream_iterator.__anext__()
+ self.collected_chunks.append(chunk)
+
+ # Add mcp_list_tools to the first chunk
+ if len(self.collected_chunks) == 1:
+ chunk = self._add_mcp_list_tools_to_chunk(chunk)
+
+ # Check if this is the final chunk (has finish_reason)
+ is_final = (
+ hasattr(chunk, "choices")
+ and chunk.choices
+ and hasattr(chunk.choices[0], "finish_reason")
+ and chunk.choices[0].finish_reason is not None
+ )
+
+ if is_final:
+ # This is the final chunk, mark stream as exhausted
+ self.stream_exhausted = True
+ # Process tool calls after we've collected all chunks
+ await self._process_tool_calls()
+ # Apply MCP metadata (tool_calls and tool_results) to final chunk
+ chunk = self._add_mcp_tool_metadata_to_final_chunk(chunk)
+ # If we have tool results, prepare follow-up call immediately
+ if self.tool_results and self.complete_response:
+ await self._prepare_follow_up_call()
+
+ return chunk
+ except StopAsyncIteration:
+ self.stream_exhausted = True
+ # Process tool calls after stream is exhausted
+ await self._process_tool_calls()
+ # If we have chunks, yield the final one with metadata
+ if self.collected_chunks:
+ final_chunk = self.collected_chunks[-1]
+ final_chunk = self._add_mcp_tool_metadata_to_final_chunk(final_chunk)
+ # If we have tool results, prepare follow-up call
+ if self.tool_results and self.complete_response:
+ await self._prepare_follow_up_call()
+ return final_chunk
+
+ # Phase 2: Yield follow-up stream chunks if available
+ if self.follow_up_stream and not self.follow_up_exhausted:
+ if not self.follow_up_iterator:
+ self.follow_up_iterator = self.follow_up_stream.__aiter__()
+ from litellm._logging import verbose_logger
+ verbose_logger.debug("Follow-up stream iterator created")
+
+ try:
+ chunk = await self.follow_up_iterator.__anext__()
+ from litellm._logging import verbose_logger
+ verbose_logger.debug(f"Follow-up chunk yielded: {chunk}")
+ return chunk
+ except StopAsyncIteration:
+ self.follow_up_exhausted = True
+ from litellm._logging import verbose_logger
+ verbose_logger.debug("Follow-up stream exhausted")
+ # After follow-up stream is exhausted, check if we need to raise StopAsyncIteration
+ raise StopAsyncIteration
+
+ # If we're here and follow_up_stream is None but we expected it, log a warning
+ if self.stream_exhausted and self.tool_results and self.complete_response and self.follow_up_stream is None:
+ from litellm._logging import verbose_logger
+ verbose_logger.warning(
+ "Follow-up stream was not created despite having tool results"
+ )
+
+ raise StopAsyncIteration
+
+ async def _process_tool_calls(self):
+ """Process tool calls after streaming completes."""
+ if self.tool_execution_done:
+ return
+
+ self.tool_execution_done = True
+
+ if not self.collected_chunks:
+ return
+
+ # Build complete response from chunks
+ complete_response = stream_chunk_builder(
+ chunks=self.collected_chunks,
+ messages=self.messages,
+ )
+
+ if isinstance(complete_response, ModelResponse):
+ self.complete_response = complete_response
+ # Extract tool calls from complete response
+ self.tool_calls = LiteLLM_Proxy_MCP_Handler._extract_tool_calls_from_chat_response(
+ response=complete_response
+ )
+
+ if self.tool_calls:
+ # Execute tool calls
+ self.tool_results = await LiteLLM_Proxy_MCP_Handler._execute_tool_calls(
+ tool_server_map=self.tool_server_map,
+ tool_calls=self.tool_calls,
+ user_api_key_auth=self.user_api_key_auth,
+ mcp_auth_header=self.mcp_auth_header,
+ mcp_server_auth_headers=self.mcp_server_auth_headers,
+ oauth2_headers=self.oauth2_headers,
+ raw_headers=self.raw_headers,
+ litellm_call_id=self.litellm_call_id,
+ litellm_trace_id=self.litellm_trace_id,
+ )
+
+ async def _prepare_follow_up_call(self):
+ """Prepare and initiate follow-up call with tool results."""
+ if self.follow_up_stream is not None:
+ return # Already prepared
+
+ if not self.tool_results or not self.complete_response:
+ return
+
+ from litellm import acompletion as litellm_acompletion
+
+ # Create follow-up messages with tool results
+ follow_up_messages = LiteLLM_Proxy_MCP_Handler._create_follow_up_messages_for_chat(
+ original_messages=self.messages,
+ response=self.complete_response,
+ tool_results=self.tool_results,
+ )
+
+ # Make follow-up call with streaming
+ follow_up_call_args = dict(self.base_call_args)
+ follow_up_call_args["messages"] = follow_up_messages
+ follow_up_call_args["stream"] = True
+ # Ensure follow-up call doesn't trigger MCP handler again
+ follow_up_call_args["_skip_mcp_handler"] = True
+
+ follow_up_response = await litellm_acompletion(**follow_up_call_args)
+
+ # Ensure follow-up response is a CustomStreamWrapper
+ if isinstance(follow_up_response, CustomStreamWrapper):
+ self.follow_up_stream = follow_up_response
+ from litellm._logging import verbose_logger
+ verbose_logger.debug("Follow-up stream created successfully")
+ else:
+ # Unexpected response type - log and set to None
+ from litellm._logging import verbose_logger
+ verbose_logger.warning(
+ f"Follow-up response is not a CustomStreamWrapper: {type(follow_up_response)}"
+ )
+ self.follow_up_stream = None
+
+ # Create the custom iterator
+ iterator = MCPStreamingIterator(
+ stream_wrapper=initial_stream,
+ messages=messages,
+ tool_server_map=tool_server_map,
+ 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,
+ litellm_call_id=kwargs.get("litellm_call_id"),
+ litellm_trace_id=kwargs.get("litellm_trace_id"),
+ openai_tools=openai_tools,
+ base_call_args=base_call_args,
+ )
+
+ # Create a wrapper class that delegates to our custom iterator
+ # We'll use a simple approach: just replace the __aiter__ method
+ class MCPStreamWrapper(CustomStreamWrapper):
+ def __init__(self, original_wrapper, custom_iterator):
+ # Initialize with the same parameters as original wrapper
+ super().__init__(
+ completion_stream=None,
+ model=getattr(original_wrapper, "model", "unknown"),
+ logging_obj=getattr(original_wrapper, "logging_obj", None),
+ custom_llm_provider=getattr(original_wrapper, "custom_llm_provider", None),
+ stream_options=getattr(original_wrapper, "stream_options", None),
+ make_call=getattr(original_wrapper, "make_call", None),
+ _response_headers=getattr(original_wrapper, "_response_headers", None),
+ )
+ self._original_wrapper = original_wrapper
+ self._custom_iterator = custom_iterator
+ # Copy important attributes from original wrapper
+ if hasattr(original_wrapper, "_hidden_params"):
+ self._hidden_params = original_wrapper._hidden_params
+
+ def __aiter__(self):
+ return self._custom_iterator
+
+ def __getattr__(self, name):
+ # Delegate all other attributes to original wrapper
+ return getattr(self._original_wrapper, name)
+
+ return cast(CustomStreamWrapper, MCPStreamWrapper(initial_stream, iterator))
+
+ # Non-streaming mode: use existing logic
initial_call_args = dict(base_call_args)
initial_call_args["stream"] = False
if mock_tool_calls is not None:
@@ -195,17 +499,6 @@ async def acompletion_with_mcp(
)
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
- response = await litellm_acompletion(**retry_args)
- if isinstance(response, (ModelResponse, CustomStreamWrapper)):
- _add_mcp_metadata_to_response(
- response=response,
- openai_tools=openai_tools,
- )
- return response
_add_mcp_metadata_to_response(
response=initial_response,
openai_tools=openai_tools,
diff --git a/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx b/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx
index 1db4d3a5857..3a7f8fec650 100644
--- a/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx
+++ b/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx
@@ -607,12 +607,16 @@ const ChatUI: React.FC<ChatUIProps> = ({
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,
- );
+ // Only check for duplicates if item_id is defined (for mcp_list_tools, item_id is "mcp_list_tools")
+ const isDuplicate = event.item_id
+ ? prev.some(
+ (existingEvent) =>
+ existingEvent.item_id === event.item_id &&
+ existingEvent.type === event.type &&
+ (existingEvent.sequence_number === event.sequence_number ||
+ (existingEvent.sequence_number === undefined && event.sequence_number === undefined)),
+ )
+ : false;
if (isDuplicate) {
console.log("ChatUI: Duplicate MCP event, skipping");
diff --git a/ui/litellm-dashboard/src/components/playground/llm_calls/chat_completion.tsx b/ui/litellm-dashboard/src/components/playground/llm_calls/chat_completion.tsx
index efcf7504b28..c3c623c25c3 100644
--- a/ui/litellm-dashboard/src/components/playground/llm_calls/chat_completion.tsx
+++ b/ui/litellm-dashboard/src/components/playground/llm_calls/chat_completion.tsx
@@ -59,12 +59,13 @@ export async function makeOpenAIChatCompletionRequest(
let fullResponseContent = "";
let fullReasoningContent = "";
- // Track MCP metadata from final chunk
+ // Track MCP metadata cumulatively across chunks
let mcpMetadata: {
mcp_list_tools?: any[];
mcp_tool_calls?: any[];
mcp_call_results?: any[];
- } | null = null;
+ } = {};
+ let mcpListToolsProcessed = false;
// Build tools array
const tools: any[] = [];
@@ -167,16 +168,48 @@ export async function makeOpenAIChatCompletionRequest(
onSearchResults(delta.provider_specific_fields.search_results);
}
- // Check for MCP metadata in provider_specific_fields (typically in final chunk)
+ // Check for MCP metadata in provider_specific_fields
if (delta && delta.provider_specific_fields) {
const providerFields = delta.provider_specific_fields;
+
+ // Merge MCP metadata cumulatively (don't overwrite)
+ if (providerFields.mcp_list_tools && !mcpMetadata.mcp_list_tools) {
+ mcpMetadata.mcp_list_tools = providerFields.mcp_list_tools;
+ // Process mcp_list_tools immediately when found (typically in first chunk)
+ if (onMCPEvent && !mcpListToolsProcessed) {
+ mcpListToolsProcessed = true;
+ const toolsEvent: MCPEvent = {
+ type: "response.output_item.done",
+ item_id: "mcp_list_tools", // Add item_id to prevent duplicate detection issues
+ item: {
+ type: "mcp_list_tools",
+ tools: providerFields.mcp_list_tools.map((tool: any) => ({
+ name: tool.function?.name || tool.name || "",
+ description: tool.function?.description || tool.description || "",
+ input_schema: tool.function?.parameters || tool.input_schema || {},
+ })),
+ },
+ timestamp: Date.now(),
+ };
+ onMCPEvent(toolsEvent);
+ console.log("MCP list_tools event sent:", toolsEvent);
+ }
+ }
+
+ if (providerFields.mcp_tool_calls) {
+ mcpMetadata.mcp_tool_calls = providerFields.mcp_tool_calls;
+ }
+
+ if (providerFields.mcp_call_results) {
+ mcpMetadata.mcp_call_results = providerFields.mcp_call_results;
+ }
+
if (providerFields.mcp_list_tools || providerFields.mcp_tool_calls || providerFields.mcp_call_results) {
- mcpMetadata = {
- mcp_list_tools: providerFields.mcp_list_tools,
- mcp_tool_calls: providerFields.mcp_tool_calls,
- mcp_call_results: providerFields.mcp_call_results,
- };
- console.log("MCP metadata found in chunk:", mcpMetadata);
+ console.log("MCP metadata found in chunk:", {
+ mcp_list_tools: providerFields.mcp_list_tools ? "present" : "absent",
+ mcp_tool_calls: providerFields.mcp_tool_calls ? "present" : "absent",
+ mcp_call_results: providerFields.mcp_call_results ? "present" : "absent",
+ });
}
}
@@ -204,35 +237,19 @@ export async function makeOpenAIChatCompletionRequest(
}
}
- // Process MCP metadata from final chunk and convert to MCPEvent format
- if (mcpMetadata && onMCPEvent) {
- // Convert mcp_list_tools to MCPEvent
- if (mcpMetadata.mcp_list_tools && mcpMetadata.mcp_list_tools.length > 0) {
- const toolsEvent: MCPEvent = {
- type: "response.output_item.done",
- item: {
- type: "mcp_list_tools",
- tools: mcpMetadata.mcp_list_tools.map((tool: any) => ({
- name: tool.function?.name || tool.name || "",
- description: tool.function?.description || tool.description || "",
- input_schema: tool.function?.parameters || tool.input_schema || {},
- })),
- },
- timestamp: Date.now(),
- };
- onMCPEvent(toolsEvent);
- }
-
+ // Process remaining MCP metadata (mcp_tool_calls and mcp_call_results) after stream completes
+ // Note: mcp_list_tools is already processed when found in the first chunk
+ if (onMCPEvent && (mcpMetadata.mcp_tool_calls || mcpMetadata.mcp_call_results)) {
// Convert mcp_tool_calls and mcp_call_results to MCPEvent[]
- if (mcpMetadata?.mcp_tool_calls && mcpMetadata?.mcp_tool_calls.length > 0) {
- mcpMetadata?.mcp_tool_calls.forEach((toolCall: any, index: number) => {
+ if (mcpMetadata.mcp_tool_calls && mcpMetadata.mcp_tool_calls.length > 0) {
+ mcpMetadata.mcp_tool_calls.forEach((toolCall: any, index: number) => {
const functionName = toolCall.function?.name || toolCall.name || "";
const functionArgs = toolCall.function?.arguments || toolCall.arguments || "{}";
// Find corresponding result
- const result = mcpMetadata?.mcp_call_results?.find(
+ const result = mcpMetadata.mcp_call_results?.find(
(r: any) => r.tool_call_id === toolCall.id || r.tool_call_id === toolCall.call_id
- ) || mcpMetadata?.mcp_call_results?.[index];
+ ) || mcpMetadata.mcp_call_results?.[index];
const callEvent: MCPEvent = {
type: "response.output_item.done",
@@ -246,6 +263,7 @@ export async function makeOpenAIChatCompletionRequest(
timestamp: Date.now(),
};
onMCPEvent(callEvent);
+ console.log("MCP call event sent:", callEvent);
});
}
}