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
Fix order of streaming for mcp responses
Sameer Kankutee0880c3deee1
diff --git a/litellm/proxy/hooks/responses_id_security.py b/litellm/proxy/hooks/responses_id_security.pyindex d196a68d369..15798e15479 100644--- a/litellm/proxy/hooks/responses_id_security.py+++ b/litellm/proxy/hooks/responses_id_security.py@@ -29,7 +29,8 @@ if TYPE_CHECKING:class ResponsesIDSecurity(CustomLogger):def __init__(self):- pass+ # Cache for encrypted response IDs to ensure consistency across streaming chunks+ self._encrypted_response_id_cache: dict[str, str] = {}async def async_pre_call_hook(self,@@ -211,31 +212,39 @@ class ResponsesIDSecurity(CustomLogger):and isinstance(response_id, str)and response_id.startswith("resp_")):- encrypted_response_id = SpecialEnums.LITELLM_MANAGED_RESPONSE_API_RESPONSE_ID_COMPLETE_STR.value.format(- response_id,- user_api_key_dict.user_id or "",- user_api_key_dict.team_id or "",- )+ # Check cache first to ensure consistency across streaming chunks+ if response_id in self._encrypted_response_id_cache:+ setattr(response, "id", self._encrypted_response_id_cache[response_id])+ else:+ encrypted_response_id = SpecialEnums.LITELLM_MANAGED_RESPONSE_API_RESPONSE_ID_COMPLETE_STR.value.format(+ response_id,+ user_api_key_dict.user_id or "",+ user_api_key_dict.team_id or "",+ )- encoded_user_id_and_response_id = encrypt_value_helper(- value=encrypted_response_id- )- setattr(- response, "id", f"resp_{encoded_user_id_and_response_id}"- ) # maintain the 'resp_' prefix for the responses api response id+ encoded_user_id_and_response_id = encrypt_value_helper(+ value=encrypted_response_id+ )+ encrypted_id = f"resp_{encoded_user_id_and_response_id}"+ self._encrypted_response_id_cache[response_id] = encrypted_id+ setattr(response, "id", encrypted_id)elif response_obj and isinstance(response_obj, ResponsesAPIResponse):- encrypted_response_id = SpecialEnums.LITELLM_MANAGED_RESPONSE_API_RESPONSE_ID_COMPLETE_STR.value.format(- response_obj.id,- user_api_key_dict.user_id or "",- user_api_key_dict.team_id or "",- )- encoded_user_id_and_response_id = encrypt_value_helper(- value=encrypted_response_id- )- setattr(- response_obj, "id", f"resp_{encoded_user_id_and_response_id}"- ) # maintain the 'resp_' prefix for the responses api response id+ # Check cache first to ensure consistency across streaming chunks+ if response_obj.id in self._encrypted_response_id_cache:+ setattr(response_obj, "id", self._encrypted_response_id_cache[response_obj.id])+ else:+ encrypted_response_id = SpecialEnums.LITELLM_MANAGED_RESPONSE_API_RESPONSE_ID_COMPLETE_STR.value.format(+ response_obj.id,+ user_api_key_dict.user_id or "",+ user_api_key_dict.team_id or "",+ )+ encoded_user_id_and_response_id = encrypt_value_helper(+ value=encrypted_response_id+ )+ encrypted_id = f"resp_{encoded_user_id_and_response_id}"+ self._encrypted_response_id_cache[response_obj.id] = encrypted_id+ setattr(response_obj, "id", encrypted_id)setattr(response, "response", response_obj)return responsediff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.pyindex 6e32a0d48d7..e7866ae0f06 100644--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py@@ -344,8 +344,12 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):self._pending_tool_events.append(item_done_event)def _default_response_created_event_data(self) -> dict:+ # Use cached response ID if available, otherwise generate a new one+ if self._cached_response_id is None:+ self._cached_response_id = f"resp_{str(uuid.uuid4())}"+response_created_event_data = {- "id": f"resp_{str(uuid.uuid4())}",+ "id": self._cached_response_id,"object": "response","created_at": int(time.time()),"status": "in_progress",@@ -1074,6 +1078,10 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):responses_api_request=self.responses_api_request,)+ # Use the cached response ID to ensure consistency across all events+ if self._cached_response_id:+ responses_api_response.id = self._cached_response_id+# Encode the response ID to match non-streaming behaviorencoded_response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id(responses_api_response=responses_api_response,diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.pyindex 731aa5c692b..0ada532c413 100644--- a/litellm/responses/mcp/mcp_streaming_iterator.py+++ b/litellm/responses/mcp/mcp_streaming_iterator.py@@ -269,7 +269,7 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):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.phase = "initial_response" # initial_response -> mcp_discovery -> tool_execution -> follow_up_response -> finishedself.finished = False# Event queues and generation flags@@ -305,6 +305,12 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):# Mark as async iteratorself.is_async = True++ # Track if we've emitted initial OpenAI lifecycle events+ self.initial_events_emitted = False++ # Cache the response ID to ensure consistency across all events+ self._cached_response_id: Optional[str] = Nonedef _extract_mcp_headers_from_params(self) -> None:"""Extract MCP headers from original request params to pass to tool calls"""@@ -388,38 +394,43 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):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+ 1. initial_response - Stream the first LLM response (includes response.created, response.in_progress, response.output_item.added)+ 2. mcp_discovery - Emit MCP discovery events (after response.output_item.added)+ 3. continue_initial_response - Continue streaming the initial response content+ 4. tool_execution - Emit tool execution events+ 5. follow_up_response - Stream the follow-up response+ 6. 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+ # Phase 1: Initial Response Stream (emit standard OpenAI events first)if self.phase == "initial_response":+ # Create the initial response iterator if not already created+ if self.base_iterator is None:+ await self._create_initial_response_iterator()+if self.base_iterator:# Check if base_iterator is actually iterableif hasattr(self.base_iterator, "__anext__"):try:chunk = await cast(Any, self.base_iterator).__anext__() # type: ignore[attr-defined]+ # Capture the response ID from the first event to ensure consistency+ if self._cached_response_id is None and hasattr(chunk, 'response'):+ response_obj = getattr(chunk, 'response', None)+ if response_obj and hasattr(response_obj, 'id'):+ self._cached_response_id = response_obj.id+ verbose_logger.debug(f"Cached response ID: {self._cached_response_id}")++ # After emitting response.output_item.added, transition to MCP discovery+ # Check if this is the output_item.added event+ if not self.initial_events_emitted and hasattr(chunk, 'type'):+ chunk_type = getattr(chunk, 'type', None)+ if chunk_type == ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED:+ self.initial_events_emitted = True+ # Transition to MCP discovery phase after returning this chunk+ self.phase = "mcp_discovery"+ return chunk+# If auto-execution is enabled, check for completed responsesif self.should_auto_execute and self._is_response_completed(chunk@@ -454,7 +465,28 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):self.phase = "finished"raise StopAsyncIteration- # Phase 3: Tool Execution Events+ # Phase 2: MCP Discovery Events (after response.output_item.added)+ if self.phase == "mcp_discovery":+ # Emit MCP discovery events+ if self.mcp_discovery_events:+ return self.mcp_discovery_events.pop(0)+ self.phase = "continue_initial_response"+ # Fall through to continue processing the initial response++ # Phase 3: Continue Initial Response (after MCP discovery events)+ if self.phase == "continue_initial_response":+ try:+ return await self._process_base_iterator_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++ # Phase 4: Tool Execution Eventsif self.phase == "tool_execution":# Emit any queued tool execution eventsif self.tool_execution_events:@@ -464,7 +496,7 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):self.phase = "follow_up_response"await self._create_follow_up_iterator()- # Phase 4: Follow-up Response Stream+ # Phase 5: Follow-up Response Streamif self.phase == "follow_up_response":if self.follow_up_iterator:try:@@ -476,7 +508,7 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):self.phase = "finished"raise StopAsyncIteration- # Phase 5: Finished+ # Phase 6: Finishedif self.phase == "finished":raise StopAsyncIteration@@ -491,6 +523,35 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):getattr(chunk, "type", None) == ResponsesAPIStreamEvents.RESPONSE_COMPLETED)+ async def _process_base_iterator_chunk(self) -> ResponsesAPIStreamingResponse:+ """+ Process a chunk from the base iterator with response ID consistency enforcement.+ """+ if not self.base_iterator or not hasattr(self.base_iterator, "__anext__"):+ raise StopAsyncIteration++ chunk = await cast(Any, self.base_iterator).__anext__() # type: ignore[attr-defined]++ # Ensure response ID consistency - update chunk if needed+ if self._cached_response_id and hasattr(chunk, 'response'):+ response_obj = getattr(chunk, 'response', None)+ if response_obj and hasattr(response_obj, 'id'):+ if response_obj.id != self._cached_response_id:+ verbose_logger.debug(f"Updating response ID from {response_obj.id} to {self._cached_response_id}")+ response_obj.id = self._cached_response_id++ # 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+async def _create_initial_response_iterator(self) -> None:"""Create the initial response iterator by making the first LLM call"""try: