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(responses): continue MCP gateway tool turns from the final response and surface failures
Thibault Serot3a2d14e1a6f1
diff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex 92dd5a513b9..12f9be970c7 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -261,7 +261,7 @@ async def aresponses_api_with_mcp(pre_processed_mcp_tools=original_mcp_tools,)- return LiteLLM_Proxy_MCP_Handler._create_mcp_streaming_response(+ mcp_streaming_response = LiteLLM_Proxy_MCP_Handler._create_mcp_streaming_response(input=input,model=model,all_tools=all_tools,@@ -272,6 +272,10 @@ async def aresponses_api_with_mcp(tool_server_map=tool_server_map,**kwargs,)+ await mcp_streaming_response._create_initial_response_iterator()+ if mcp_streaming_response._initial_creation_error is not None:+ raise mcp_streaming_response._initial_creation_error+ return mcp_streaming_response# Determine if we should auto-execute toolsshould_auto_execute = bool(mcp_tools_with_litellm_proxy) and LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.pyindex c705a04963c..d6b45855be5 100644--- a/litellm/responses/mcp/mcp_streaming_iterator.py+++ b/litellm/responses/mcp/mcp_streaming_iterator.py@@ -5,6 +5,8 @@ from litellm._uuid import uuidfrom litellm.responses.streaming_iterator import BaseResponsesAPIStreamingIteratorfrom litellm.types.llms.openai import (BaseLiteLLMOpenAIResponseObject,+ ErrorEvent,+ ErrorEventError,MCPCallArgumentsDeltaEvent,MCPCallArgumentsDoneEvent,MCPCallCompletedEvent,@@ -316,6 +318,11 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):# Cache the response ID to ensure consistency across all eventsself._cached_response_id: Optional[str] = None+ self._initial_creation_error: Exception | None = None+ self._stream_error: Exception | None = None+ self._error_event_emitted = False+ self._last_sequence_number = 0+def _extract_mcp_headers_from_params(self) -> None:"""Extract MCP headers from original request params to pass to tool calls"""from typing import Dict, Optional@@ -380,10 +387,31 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):return LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(self.mcp_tools_with_litellm_proxy)+ def _make_stream_error_event(self) -> ResponsesAPIStreamingResponse:+ err = self._stream_error+ status_code = getattr(err, "status_code", None)+ return ErrorEvent(+ type=ResponsesAPIStreamEvents.ERROR,+ sequence_number=self._last_sequence_number + 1,+ error=ErrorEventError(+ type="mcp_gateway_error",+ code=str(status_code) if status_code is not None else "internal_error",+ message=str(err) if err is not None else "MCP gateway stream failed",+ param=None,+ ),+ )+def __aiter__(self):return selfasync def __anext__(self) -> ResponsesAPIStreamingResponse:+ chunk = await self._anext_impl()+ sequence_number = getattr(chunk, "sequence_number", None)+ if isinstance(sequence_number, int) and sequence_number > self._last_sequence_number:+ self._last_sequence_number = sequence_number+ return chunk++ async def _anext_impl(self) -> ResponsesAPIStreamingResponse:"""Phase-based streaming:1. initial_response - Stream the first LLM response (includes response.created, response.in_progress, response.output_item.added)@@ -438,10 +466,16 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):self.phase = "continue_initial_response"return await self.__anext__()self.phase = "finished"+ if self._stream_error is not None and not self._error_event_emitted:+ self._error_event_emitted = True+ return self._make_stream_error_event()raise StopAsyncIteration# Phase 6: Finishedif self.phase == "finished":+ if self._stream_error is not None and not self._error_event_emitted:+ self._error_event_emitted = True+ return self._make_stream_error_event()raise StopAsyncIteration# Should not reach here@@ -530,6 +564,12 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):chunk = await cast(Any, self.base_iterator).__anext__() # type: ignore[attr-defined]+ if self._cached_response_id is None and hasattr(chunk, "response"):+ new_response = getattr(chunk, "response", None)+ new_response_id = getattr(new_response, "id", None) if new_response is not None else None+ if new_response_id:+ self._cached_response_id = new_response_id+# Ensure response ID consistency - update chunk if neededif self._cached_response_id and hasattr(chunk, "response"):response_obj = getattr(chunk, "response", None)@@ -589,6 +629,8 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):traceback.print_exc()self.base_iterator = None+ self._initial_creation_error = e+ self._stream_error = e# Don't set phase to "finished" here — let __anext__ emit any# pre-generated MCP discovery events before ending the iteration.@@ -761,6 +803,7 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):if hasattr(follow_up_response, "__aiter__"):self.base_iterator = follow_up_responseself.collected_response = None+ self._cached_response_id = Noneexcept Exception as e:verbose_logger.error(f"Error creating follow-up iterator: {e}")@@ -768,6 +811,7 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):traceback.print_exc()self.base_iterator = None+ self._stream_error = edef __iter__(self):return selfdiff --git a/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.pyindex cdace5f6327..24edf12fffe 100644--- a/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py+++ b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py@@ -39,8 +39,13 @@ def _output_item_added_chunk():return SimpleNamespace(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED)-def _completed_chunk(output):- response = ResponsesAPIResponse(id="resp-1", created_at=0, output=output)+def _created_chunk(response_id: str):+ response = ResponsesAPIResponse(id=response_id, created_at=0, output=[])+ return SimpleNamespace(type=ResponsesAPIStreamEvents.RESPONSE_CREATED, response=response)+++def _completed_chunk(output, response_id: str = "resp-1"):+ response = ResponsesAPIResponse(id=response_id, created_at=0, output=output)return SimpleNamespace(type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED, response=response)@@ -52,12 +57,12 @@ def _text_message(text: str):return {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]}-def _tool_call_stream(call_id: str, tool_name: str) -> _FakeAsyncStream:- return _FakeAsyncStream([_completed_chunk([_function_call(call_id, tool_name)])])+def _tool_call_stream(call_id: str, tool_name: str, response_id: str = "resp-1") -> _FakeAsyncStream:+ return _FakeAsyncStream([_completed_chunk([_function_call(call_id, tool_name)], response_id=response_id)])-def _text_only_stream(text: str) -> _FakeAsyncStream:- return _FakeAsyncStream([_completed_chunk([_text_message(text)])])+def _text_only_stream(text: str, response_id: str = "resp-1") -> _FakeAsyncStream:+ return _FakeAsyncStream([_completed_chunk([_text_message(text)], response_id=response_id)])def _mock_mcp_environment(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:@@ -170,3 +175,85 @@ async def test_tool_call_rounds_are_capped(monkeypatch):for call in aresponses_mock.call_args_list[:-1]:assert "tools" in call.kwargsassert "tools" not in aresponses_mock.call_args_list[-1].kwargs+++async def test_continuation_id_is_final_round_not_interim_tool_call(monkeypatch):+ """+ Regression test for the broken `previous_response_id` continuation after a+ gateway-executed MCP tool call. Each auto-execute round is a distinct+ upstream response: the interim round holds only the model's function_call+ (no tool output), the final round holds the answer. The client must be+ handed the FINAL round's response id, because that is the one whose stored+ chain includes the function_call_output. Pinning every event to the interim+ round's id made the next turn continue from a response with a dangling+ function_call, which the provider rejects with+ "No tool output found for function call ...".+ """+ _mock_mcp_environment(monkeypatch)++ aresponses_mock = AsyncMock(side_effect=[_text_only_stream("The first item is Alpha.", response_id="resp-final")])+ monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock)++ iterator = _make_iterator(+ [+ _created_chunk("resp-interim"),+ _output_item_added_chunk(),+ _completed_chunk([_function_call("call_1", "read_wiki_contents")], response_id="resp-interim"),+ ]+ )++ chunks = [chunk async for chunk in iterator]+ completed = [c for c in chunks if getattr(c, "type", None) == ResponsesAPIStreamEvents.RESPONSE_COMPLETED]++ assert completed[-1].response.output[0]["content"][0]["text"] == "The first item is Alpha."+ assert completed[-1].response.id == "resp-final"+ assert completed[-1].response.id != "resp-interim"+++async def test_follow_up_call_failure_emits_terminal_error_event(monkeypatch):+ """+ Regression test for the silent-swallow path: when the follow-up LLM call+ raises, the stream must emit a terminal `error` event instead of ending+ silently after the tool events (which surfaced to clients as a successful+ but empty completion).+ """+ _mock_mcp_environment(monkeypatch)++ aresponses_mock = AsyncMock(side_effect=RuntimeError("boom from provider"))+ monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock)++ iterator = _make_iterator(+ [+ _output_item_added_chunk(),+ _completed_chunk([_function_call("call_1", "read_wiki_contents")]),+ ]+ )++ chunks = [chunk async for chunk in iterator]+ error_events = [c for c in chunks if getattr(c, "type", None) == ResponsesAPIStreamEvents.ERROR]++ assert len(error_events) == 1+ assert error_events[0].error.type == "mcp_gateway_error"+ assert "boom from provider" in error_events[0].error.message+++async def test_initial_call_failure_is_stashed_for_eager_reraise(monkeypatch):+ """+ Regression test: a failing initial LLM call must be stashed as+ `_initial_creation_error` so `aresponses_api_with_mcp` can re-raise it as a+ real 4xx before any SSE bytes are written, instead of returning HTTP 200+ with an empty stream.+ """+ _mock_mcp_environment(monkeypatch)++ aresponses_mock = AsyncMock(side_effect=RuntimeError("initial boom"))+ monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock)++ iterator = _make_iterator([_output_item_added_chunk()])+ await iterator._create_initial_response_iterator()++ assert iterator._initial_creation_error is not None+ assert "initial boom" in str(iterator._initial_creation_error)