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]

merge: bring litellm_internal_staging into litellm_fix_agent_mcp_grants

mateo-berri5e4dec4b8816
diff --cc litellm/proxy/_experimental/mcp_server/server.py
index bff525995a4,0b424c31c4b..a44a041fdff
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@@ -1444,72 -1449,6 +1453,72 @@@ if MCP_AVAILABLE
return allowed_mcp_servers
+ def _http_detail_message(detail: object) -> str:
+ return str(detail.get("error")) if isinstance(detail, dict) and detail.get("error") else str(detail)
+
+ def _server_answers_to(server: MCPServer, name: str) -> bool:
+ requested: Final = name.lower()
+ return any(requested == known.lower() for known in iter_known_server_prefixes(server) if known)
+
+ class _McpDeniedDetail(TypedDict):
+ error: ReadOnly[str]
+
- async def _raise_denied_scoped_mcp_access(
++ async def raise_denied_scoped_mcp_access(
+ requested_names: Sequence[str],
+ user_api_key_auth: UserAPIKeyAuth | None,
+ client_ip: str | None = None,
+ ) -> None:
+ """A scoped request (``/mcp/<name>`` path or ``x-mcp-servers`` header) resolved to zero
+ allowed servers, so the denial must be loud: a silent 200 with no tools reads as a healthy
+ server with no tools. Unknown, unauthorized, and access-group names all share one generic
+ error so scoping cannot probe which servers exist; the agent variant fires only when the
+ same request resolves once the agent binding is stripped, proving the binding caused the veto."""
+ agent_id: Final = user_api_key_auth.agent_id if user_api_key_auth else None
+ if user_api_key_auth is not None and agent_id:
+ resolved_without_agent: Final = await _get_allowed_mcp_servers(
+ user_api_key_auth=user_api_key_auth.model_copy(update=types.MappingProxyType({"agent_id": None})),
+ mcp_servers=requested_names,
+ client_ip=client_ip,
+ )
+
+ def _resolved_to_server(name: str) -> bool:
+ return any(_server_answers_to(server, name) for server in resolved_without_agent)
+
+ vetoed_server: Final = next((name for name in requested_names if _resolved_to_server(name)), None)
+ if vetoed_server is not None:
+ agent_denial: Final[_McpDeniedDetail] = {
+ "error": (
+ f"MCP server '{vetoed_server}' is not available to this key: the key is bound to "
+ f"agent '{agent_id}', whose MCP grants do not include this server. Add the server "
+ f"to the agent's object_permission.mcp_servers (edit the agent in the Admin UI or "
+ f"PATCH /v1/agents/{agent_id}), or use a key that is not bound to the agent."
+ )
+ }
+ raise HTTPException(status_code=403, detail=agent_denial)
+ vetoed_group: Final = next(
+ (
+ name
+ for name in requested_names
+ if not _resolved_to_server(name)
+ and any(name in (server.access_groups or ()) for server in resolved_without_agent)
+ ),
+ None,
+ )
+ if vetoed_group is not None:
+ group_denial: Final[_McpDeniedDetail] = {
+ "error": (
+ f"MCP access group '{vetoed_group}' is not available to this key: the key is bound to "
+ f"agent '{agent_id}', whose MCP grants do not include it. Add the group to the "
+ f"agent's object_permission.mcp_access_groups (edit the agent in the Admin UI or "
+ f"PATCH /v1/agents/{agent_id}), or use a key that is not bound to the agent."
+ )
+ }
+ raise HTTPException(status_code=403, detail=group_denial)
+ generic_denial: Final[_McpDeniedDetail] = {
+ "error": f"The key is not allowed to access the requested MCP servers: {', '.join(requested_names)}"
+ }
+ raise HTTPException(status_code=403, detail=generic_denial)
+
def _tool_name_matches(tool_name: str, filter_list: list[str], mcp_server: MCPServer) -> bool:
"""
Check if a tool name matches any name in the filter list.
@@@ -2034,12 -1977,6 +2047,12 @@@
mcp_servers=mcp_servers,
client_ip=client_ip,
)
+ if mcp_servers and not allowed_mcp_servers:
- await _raise_denied_scoped_mcp_access(
++ await raise_denied_scoped_mcp_access(
+ requested_names=mcp_servers,
+ user_api_key_auth=user_api_key_auth,
+ client_ip=client_ip,
+ )
# Pre-fetch OAuth credentials only when at least one server uses OAuth2,
# to avoid an unnecessary DB round-trip on requests with no OAuth2 MCP servers.
@@@ -3182,12 -3116,6 +3195,12 @@@
mcp_servers=mcp_servers,
allowed_mcp_servers=allowed_mcp_servers,
)
+ if mcp_servers and not allowed_mcp_servers:
- await _raise_denied_scoped_mcp_access(
++ await raise_denied_scoped_mcp_access(
+ requested_names=mcp_servers,
+ user_api_key_auth=user_api_key_auth,
+ client_ip=client_ip,
+ )
if not allowed_mcp_servers:
raise HTTPException(
status_code=403,
diff --cc litellm/proxy/_experimental/mcp_server/tool_search.py
index 0078ec06d9f,f19340d30cb..24e2f5ce64d
--- a/litellm/proxy/_experimental/mcp_server/tool_search.py
+++ b/litellm/proxy/_experimental/mcp_server/tool_search.py
@@@ -307,8 -365,7 +365,8 @@@ async def handle_mcp_tool_call
) -> CallToolResult:
from litellm.proxy._experimental.mcp_server.server import (
_get_allowed_mcp_servers,
- _raise_denied_scoped_mcp_access,
execute_mcp_tool,
++ raise_denied_scoped_mcp_access,
)
allowed_mcp_servers: Final = await _get_allowed_mcp_servers(
@@@ -316,12 -373,6 +374,12 @@@
mcp_servers=mcp_servers,
client_ip=client_ip,
)
+ if mcp_servers and not allowed_mcp_servers:
- await _raise_denied_scoped_mcp_access(
++ await raise_denied_scoped_mcp_access(
+ requested_names=mcp_servers,
+ user_api_key_auth=user_api_key_dict,
+ client_ip=client_ip,
+ )
# Reject before dispatch when the key has no accessible servers; otherwise an
# unprefixed local tool name would fall through to the local registry in
diff --cc litellm/proxy/hooks/mcp_semantic_filter/hook.py
index afc430173ad,8b82842353c..bec12ba8201
--- a/litellm/proxy/hooks/mcp_semantic_filter/hook.py
+++ b/litellm/proxy/hooks/mcp_semantic_filter/hook.py
@@@ -196,14 -192,13 +196,14 @@@ class SemanticToolFilterHook(CustomLogg
LiteLLM_Proxy_MCP_Handler,
)
+ via_gateway: Final = await (
- LiteLLM_Proxy_MCP_Handler._routes_through_gateway(tools, served_names)
++ LiteLLM_Proxy_MCP_Handler.routes_through_gateway(tools, served_names)
+ if served_names is not None
- else LiteLLM_Proxy_MCP_Handler._routes_through_gateway(tools)
++ else LiteLLM_Proxy_MCP_Handler.routes_through_gateway(tools)
+ )
return [
- (
- {**tool, "allowed_tools": selected_tool_names}
- if isinstance(tool, dict) and LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway([tool])
- else tool
- )
- for tool in tools
+ {**tool, "allowed_tools": selected_tool_names} if isinstance(tool, dict) and routed else tool
+ for tool, routed in zip(tools, via_gateway, strict=True)
]
def _is_mcp_tool(self, tool: object) -> bool:
diff --cc litellm/responses/mcp/litellm_proxy_mcp_handler.py
index 5db6bac10a1,15434bedbb7..a5021e2f777
--- a/litellm/responses/mcp/litellm_proxy_mcp_handler.py
+++ b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
@@@ -150,41 -87,57 +150,41 @@@ class LiteLLM_Proxy_MCP_Handler
@staticmethod
def _should_use_litellm_mcp_gateway(tools: Iterable[ToolParam] | None) -> bool:
- """
- Returns True if any MCP tool should be handled via the litellm proxy MCP gateway.
- This includes tools with server_url="litellm_proxy" as well as URLs ending in /mcp/<name>.
- """
- if tools:
- for tool in tools:
- if isinstance(tool, dict) and tool.get("type") == "mcp":
- server_url = tool.get("server_url", "")
- if isinstance(server_url, str) and server_url.startswith(LITELLM_PROXY_MCP_SERVER_URL):
- return True
- if isinstance(server_url, str) and _PROXY_MCP_PATH_RE.match(server_url):
- return True
- return False
+ """True when a tool may name this gateway: server_url "litellm_proxy..." or an http(s) URL ending in
+ /mcp/<name>. `_split_mcp_tools` then settles which of the latter the gateway actually serves."""
+ return any(_names_gateway_explicitly(tool) or _proxy_path_mcp_name(tool) is not None for tool in tools or ())
+
+ @staticmethod
+ def _parse_mcp_tools(tools: Iterable[Mapping[str, object]] | None) -> SplitTools:
+ items: Final = tuple(tools or ())
+ gateway_tools: Final[list[ToolParam]] = [tool for tool in items if _names_gateway_explicitly(tool)]
+ other_tools: Final[list[Any]] = [tool for tool in items if not _names_gateway_explicitly(tool)]
+ return gateway_tools, other_tools
+
+ @staticmethod
+ async def _split_mcp_tools(
+ tools: Iterable[Mapping[str, object]] | None,
+ served_names: Callable[[Collection[str]], Awaitable[frozenset[str]]] = _gateway_served_names,
+ ) -> SplitTools:
+ items: Final = tuple(tools or ())
+ served: Final = await _served_mcp_path_names(items, served_names)
+ return LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(
+ [
+ {**tool, "server_url": f"{LITELLM_PROXY_MCP_SERVER_URL_PREFIX}{name}"}
+ if (name := _proxy_path_mcp_name(tool)) in served
+ else tool
+ for tool in items
+ ]
+ )
@staticmethod
- async def _routes_through_gateway(
- def _parse_mcp_tools(
++ async def routes_through_gateway(
tools: Iterable[Mapping[str, object]] | None,
- ) -> tuple[list[ToolParam], list[Any]]:
- """
- Parse tools and separate MCP tools with litellm_proxy from other tools.
-
- Returns:
- Tuple of (mcp_tools_with_litellm_proxy, other_tools)
- """
- mcp_tools_with_litellm_proxy: Final[list[ToolParam]] = []
- other_tools: Final[list[Any]] = []
-
- if tools:
- for tool in tools:
- if isinstance(tool, dict) and tool.get("type") == "mcp":
- server_url = tool.get("server_url", "")
- if isinstance(server_url, str) and server_url.startswith(LITELLM_PROXY_MCP_SERVER_URL):
- mcp_tools_with_litellm_proxy.append(tool)
- elif isinstance(server_url, str):
- # Also intercept URLs like http://localhost:4000/mcp/atlassian_test
- # by rewriting them to the internal litellm_proxy format.
- m = _PROXY_MCP_PATH_RE.match(server_url)
- if m:
- rewritten = {
- **tool,
- "server_url": f"{LITELLM_PROXY_MCP_SERVER_URL_PREFIX}{m.group(1)}",
- }
- mcp_tools_with_litellm_proxy.append(rewritten)
- else:
- other_tools.append(tool)
- else:
- other_tools.append(tool)
- else:
- other_tools.append(tool)
-
- return mcp_tools_with_litellm_proxy, other_tools
+ served_names: Callable[[Collection[str]], Awaitable[frozenset[str]]] = _gateway_served_names,
+ ) -> tuple[bool, ...]:
+ items: Final = tuple(tools or ())
+ served: Final = await _served_mcp_path_names(items, served_names)
+ return tuple(_names_gateway_explicitly(tool) or _proxy_path_mcp_name(tool) in served for tool in items)
@staticmethod
async def _apply_toolset_permissions(
diff --cc tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py
index 4efe4d9bfd9,80151d0cba8..9745a0af970
--- a/tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py
+++ b/tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py
@@@ -722,173 -724,208 +725,380 @@@ def test_extract_tool_call_details_stil
assert arguments == '{"city": "Paris"}'
+def _registered(
+ server_id: str,
+ name: str,
+ alias: str | None = None,
+ server_name: str | None = None,
+ access_groups: list[str] | None = None,
+):
+ from litellm.types.mcp import MCPTransport
+ from litellm.types.mcp_server.mcp_server_manager import MCPServer
+
+ return MCPServer(
+ server_id=server_id,
+ name=name,
+ alias=alias,
+ server_name=server_name,
+ transport=MCPTransport.http,
+ access_groups=access_groups,
+ )
+
+
+async def _no_toolset(_: str) -> bool:
+ return False
+
+
+ZAPIER_TOOL: Mcp = {
+ "type": "mcp",
+ "server_label": "zapier",
+ "server_url": "https://mcp.zapier.com/api/mcp/mcp",
+ "require_approval": "never",
+}
+EXPLICIT_GATEWAY_TOOL = {"type": "mcp", "server_label": "github", "server_url": "litellm_proxy/mcp/github"}
+FUNCTION_TOOL = {"type": "function", "name": "get_weather", "parameters": {}}
+
+
+async def test_gateway_served_names_matches_alias_server_name_name_access_group_and_toolset():
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import _gateway_served_names
+
+ servers = (
+ _registered("id-1", "github-name", alias="github", server_name="github-server", access_groups=["prod-group"]),
+ _registered("id-2", "deepwiki"),
+ )
+
+ async def toolset_exists(name: str) -> bool:
+ return name == "my-toolset"
+
+ served = await _gateway_served_names(
+ {"github", "github-server", "github-name", "deepwiki", "prod-group", "my-toolset", "mcp", "nope"},
+ servers=lambda: servers,
+ toolset_exists=toolset_exists,
+ )
+
+ assert served == {"github", "github-server", "github-name", "deepwiki", "prod-group", "my-toolset"}
+
+
+async def test_gateway_served_names_matches_server_id_short_prefix_and_alias_case_like_the_gateway():
+ from litellm.proxy._experimental.mcp_server.utils import compute_short_server_prefix
+ from litellm.responses.mcp.litellm_proxy_mcp_handler import _gateway_served_names
+
+ server_id = "0b9ae4ca-1bd2-4faa-b183-7dd812597e3b"
+ short_prefix = compute_short_server_prefix(server_id)
+ servers = (_registered(server_id, "github-name", alias="github", access_groups=["prod-group"]),)
+
+ served = await _gateway_served_names(
+ {server_id, short_prefix, "GitHub", "PROD-GROUP", "nope"}, servers=lambda: servers, toolset_exists=_no_toolset
+ )
+
+ assert served == {server_id, short_prefix, "GitHub"}
+
+
+async def test_routes_through_gateway_flags_explicit_and_served_tools_only():
+ served_tool = {"type": "mcp", "server_label": "github", "server_url": "http://localhost:4000/mcp/github"}
+
+ async def served_names(names):
+ assert names == {"github", "mcp"}
+ return frozenset({"github"})
+
- flags = await LiteLLM_Proxy_MCP_Handler._routes_through_gateway(
++ flags = await LiteLLM_Proxy_MCP_Handler.routes_through_gateway(
+ [ZAPIER_TOOL, EXPLICIT_GATEWAY_TOOL, served_tool, FUNCTION_TOOL], served_names=served_names
+ )
+
+ assert flags == (False, True, True, False)
+
+
+async def test_split_mcp_tools_leaves_external_mcp_path_urls_for_the_provider():
+
+ async def served_names(names):
+ assert names == {"mcp"}
+ return frozenset()
+
+ gateway_tools, other_tools = await LiteLLM_Proxy_MCP_Handler._split_mcp_tools(
+ [ZAPIER_TOOL, EXPLICIT_GATEWAY_TOOL, FUNCTION_TOOL], served_names=served_names
+ )
+
+ assert gateway_tools == [EXPLICIT_GATEWAY_TOOL]
+ assert other_tools == [ZAPIER_TOOL, FUNCTION_TOOL]
+
+
+async def test_split_mcp_tools_repoints_served_proxy_urls_at_the_gateway():
+ served_tool = {
+ "type": "mcp",
+ "server_label": "toolset",
+ "server_url": "http://localhost:4000/mcp/my-toolset",
+ "require_approval": "never",
+ "allowed_tools": ["get_me"],
+ }
+ unserved_tool = {"type": "mcp", "server_label": "typo", "server_url": "http://localhost:4000/mcp/githb"}
+
+ async def served_names(names):
+ return frozenset({"my-toolset"})
+
+ gateway_tools, other_tools = await LiteLLM_Proxy_MCP_Handler._split_mcp_tools(
+ [served_tool, unserved_tool], served_names=served_names
+ )
+
+ assert gateway_tools == [{**served_tool, "server_url": "litellm_proxy/mcp/my-toolset"}]
+ assert other_tools == [unserved_tool]
+
+
+async def test_split_mcp_tools_skips_resolution_when_nothing_points_at_the_proxy():
+ async def served_names(names):
+ raise AssertionError("no lookup expected")
+
+ gateway_tools, other_tools = await LiteLLM_Proxy_MCP_Handler._split_mcp_tools(
+ [EXPLICIT_GATEWAY_TOOL, FUNCTION_TOOL], served_names=served_names
+ )
+
+ assert gateway_tools == [EXPLICIT_GATEWAY_TOOL]
+ assert other_tools == [FUNCTION_TOOL]
+
+
+def test_should_use_gateway_still_triggers_on_http_mcp_path():
+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway([ZAPIER_TOOL]) is True
+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway([EXPLICIT_GATEWAY_TOOL]) is True
+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway([FUNCTION_TOOL]) is False
+ assert LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(None) is False
+
+
+async def test_aresponses_api_with_mcp_forwards_unserved_external_mcp_tool_to_the_provider(monkeypatch):
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager
+ from litellm.responses import main as responses_main
+ from litellm.types.llms.openai import ResponsesAPIResponse
+
+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", types.SimpleNamespace(prisma_client=None))
+ monkeypatch.setattr(global_mcp_server_manager, "get_registry", lambda: {})
+ provider_tools: list[object] = []
+
+ def fake_provider(**kwargs: object) -> object:
+ request_params = cast(dict[str, object], kwargs["response_api_optional_request_params"])
+ provider_tools.append(request_params.get("tools"))
+
+ async def respond() -> ResponsesAPIResponse:
+ return ResponsesAPIResponse(id="resp_zapier", created_at=0, output=[])
+
+ return respond()
+
+ monkeypatch.setattr(responses_main.base_llm_http_handler, "response_api_handler", fake_provider)
+
+ response = await responses_main.aresponses_api_with_mcp(
+ input="Reply with the single word ok.", model="openai/gpt-4.1", tools=[ZAPIER_TOOL]
+ )
+
+ assert isinstance(response, ResponsesAPIResponse)
+ assert provider_tools == [[ZAPIER_TOOL]]
++
++
+ def _response_with_reasoning_and_tool_call() -> Any:
+ """A first-turn response as a reasoning model returns it: reasoning item, then a function call."""
+ return ResponsesAPIResponse(
+ id="resp_first",
+ created_at=1234567890,
+ model="gpt-5",
+ object="response",
+ status="completed",
+ output=[
+ {
+ "type": "reasoning",
+ "id": "rs_1",
+ "summary": [],
+ "encrypted_content": "gAAAAA-opaque-blob",
+ },
+ {
+ "type": "function_call",
+ "id": "fc_1",
+ "call_id": "call-1",
+ "name": "foo",
+ "arguments": "{}",
+ "status": "completed",
+ },
+ ],
+ parallel_tool_calls=False,
+ tool_choice="auto",
+ tools=[],
+ )
+
+
+ def test_create_follow_up_input_preserves_reasoning_when_stateless():
+ """
+ Regression test (LIT-5427): a store=false follow-up has to replay the reasoning
+ item, including reasoning.encrypted_content, since the provider kept no state.
+ """
+ follow_up = LiteLLM_Proxy_MCP_Handler._create_follow_up_input(
+ response=_response_with_reasoning_and_tool_call(),
+ tool_results=[{"tool_call_id": "call-1", "name": "foo", "result": "done"}],
+ original_input="hi",
+ preserve_reasoning=True,
+ )
+
+ assert follow_up[1] == {
+ "type": "reasoning",
+ "id": "rs_1",
+ "summary": [],
+ "encrypted_content": "gAAAAA-opaque-blob",
+ }
+ assert follow_up[2] == {
+ "type": "function_call",
+ "call_id": "call-1",
+ "name": "foo",
+ "arguments": "{}",
+ }
+ assert follow_up[3] == {
+ "type": "function_call_output",
+ "call_id": "call-1",
+ "output": "done",
+ }
+
+
+ def _response_with_interleaved_reasoning_and_tool_calls() -> Any:
+ """A first-turn response that reasons before each of two function calls."""
+ return ResponsesAPIResponse(
+ id="resp_first",
+ created_at=1234567890,
+ model="gpt-5",
+ object="response",
+ status="completed",
+ output=[
+ {"type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "blob-1"},
+ {"type": "function_call", "id": "fc_1", "call_id": "call-1", "name": "foo", "arguments": "{}"},
+ {"type": "reasoning", "id": "rs_2", "summary": [], "encrypted_content": "blob-2"},
+ {"type": "function_call", "id": "fc_2", "call_id": "call-2", "name": "bar", "arguments": "{}"},
+ ],
+ parallel_tool_calls=False,
+ tool_choice="auto",
+ tools=[],
+ )
+
+
+ def test_create_follow_up_input_keeps_each_reasoning_item_before_its_function_call():
+ """
+ Regression test (LIT-5427): the provider pairs a replayed reasoning item with the
+ item that follows it, so the replay has to keep the response's output order instead
+ of grouping every reasoning item ahead of every function call.
+ """
+ follow_up = LiteLLM_Proxy_MCP_Handler._create_follow_up_input(
+ response=_response_with_interleaved_reasoning_and_tool_calls(),
+ tool_results=[
+ {"tool_call_id": "call-1", "name": "foo", "result": "one"},
+ {"tool_call_id": "call-2", "name": "bar", "result": "two"},
+ ],
+ original_input="hi",
+ preserve_reasoning=True,
+ )
+
+ assert [cast(dict[str, Any], item)["type"] for item in follow_up] == [
+ "message",
+ "reasoning",
+ "function_call",
+ "reasoning",
+ "function_call",
+ "function_call_output",
+ "function_call_output",
+ ]
+ assert [cast(dict[str, Any], item).get("id") or cast(dict[str, Any], item).get("call_id") for item in follow_up[1:5]] == [
+ "rs_1",
+ "call-1",
+ "rs_2",
+ "call-2",
+ ]
+
+
+ def test_create_follow_up_input_omits_reasoning_when_stateful():
+ """With store=true the provider still holds the reasoning item, so don't resend it."""
+ follow_up = LiteLLM_Proxy_MCP_Handler._create_follow_up_input(
+ response=_response_with_reasoning_and_tool_call(),
+ tool_results=[{"tool_call_id": "call-1", "name": "foo", "result": "done"}],
+ original_input="hi",
+ )
+
+ assert not [item for item in follow_up if isinstance(item, dict) and item.get("type") == "reasoning"]
+
+
+ @pytest.mark.parametrize(
+ "call_params, expected",
+ [
+ ({"store": False}, True),
+ ({"store": True}, False),
+ ({"store": None}, False),
+ ({}, False),
+ ],
+ )
+ def test_is_persistence_disabled(call_params: dict[str, Any], expected: bool):
+ assert LiteLLM_Proxy_MCP_Handler._is_persistence_disabled(call_params) is expected
+
+
+ @pytest.mark.parametrize(
+ "store, caller_previous_response_id, expected_previous_response_id",
+ [
+ (False, None, None),
+ (False, "resp_caller", "resp_caller"),
+ (True, None, "resp_first"),
+ (True, "resp_caller", "resp_first"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_mcp_follow_up_call_is_stateless_when_store_is_false(
+ monkeypatch: pytest.MonkeyPatch,
+ store: bool,
+ caller_previous_response_id: str | None,
+ expected_previous_response_id: str | None,
+ ):
+ """
+ Regression test (LIT-5427): linking the MCP follow-up call to the first response's id
+ fails for zero data retention callers, because store=false means it was never persisted.
+ The caller's own previous_response_id was valid for the first call, so it stays.
+ """
+ captured_calls: list[dict[str, Any]] = []
+ first_response = _response_with_reasoning_and_tool_call()
+
+ async def fake_aresponses(**kwargs: Any) -> ResponsesAPIResponse:
+ captured_calls.append(kwargs)
+ return first_response if len(captured_calls) == 1 else ResponsesAPIResponse(
+ id="resp_follow_up",
+ created_at=1234567891,
+ model="gpt-5",
+ object="response",
+ status="completed",
+ output=[],
+ parallel_tool_calls=False,
+ tool_choice="auto",
+ tools=[],
+ )
+
+ async def fake_process(**kwargs: Any) -> tuple[list[Any], dict[str, str]]:
+ return ([], {"foo": "litellm_proxy"})
+
+ async def fake_execute(**kwargs: Any) -> list[dict[str, Any]]:
+ return [{"tool_call_id": "call-1", "name": "foo", "result": "done"}]
+
+ monkeypatch.setattr(responses_main, "aresponses", fake_aresponses)
+ monkeypatch.setattr(mcp_handler_module, "aresponses", fake_aresponses)
+ monkeypatch.setattr(
+ LiteLLM_Proxy_MCP_Handler, "_process_mcp_tools_without_openai_transform", staticmethod(fake_process)
+ )
+ monkeypatch.setattr(LiteLLM_Proxy_MCP_Handler, "_execute_tool_calls", staticmethod(fake_execute))
+
+ await responses_main.aresponses_api_with_mcp(
+ input="hi",
+ model="gpt-5",
+ tools=[{"type": "mcp", "server_url": "litellm_proxy", "require_approval": "never"}],
+ store=store,
+ previous_response_id=caller_previous_response_id,
+ )
+
+ assert len(captured_calls) == 2
+ follow_up_call = captured_calls[1]
+ assert follow_up_call["previous_response_id"] == expected_previous_response_id
+
+ reasoning_items = [
+ item for item in follow_up_call["input"] if isinstance(item, dict) and item.get("type") == "reasoning"
+ ]
+ assert bool(reasoning_items) is (store is False)