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 origin/litellm_internal_staging into litellm_mcp_walker_consolidation

Tin Chi Lo8e0d3af81b45
diff --cc litellm/proxy/_experimental/mcp_server/faults/list_outcomes.py
index 00000000000,6f27c1c0472..10463496409
mode 000000,100644..100644
--- a/litellm/proxy/_experimental/mcp_server/faults/list_outcomes.py
+++ b/litellm/proxy/_experimental/mcp_server/faults/list_outcomes.py
@@@ -1,0 -1,190 +1,177 @@@
+ """Per-server outcomes for the aggregate MCP tools/list fan-out.
+
+ The aggregate listing deliberately keeps serving the healthy subset when one server fails, but a
+ failed server must contribute a classified outcome instead of silently shrinking the list: an empty
+ contribution with no signal makes a broken upstream indistinguishable from a healthy server with no
+ tools. Outcomes carry only machine fields (category and status code) so nothing from an upstream
+ body crosses the trust boundary; classification is total, so any exception out of a server fetch
+ becomes an outcome, never a second failure.
+ """
+
+ from __future__ import annotations
+
+ from collections.abc import Iterator
+ from typing import Literal, NamedTuple, NoReturn, TypeAlias
+
+ import httpx
+ from mcp.types import Tool as MCPTool
+ from pydantic import BaseModel, ConfigDict
+ from typing_extensions import assert_never
+
+ from litellm.proxy._experimental.mcp_server.exceptions import (
+ MCPServerListError,
+ MCPUpstreamAuthError,
+ )
++from litellm.proxy._experimental.mcp_server.faults.traversal import iter_exception_tree
+
+ ListFaultCategory: TypeAlias = Literal[
+ "auth_required",
+ "forbidden",
+ "timeout",
+ "unreachable",
+ "upstream_error",
+ "internal",
+ ]
+
+
+ class ServerListOk(BaseModel):
+ model_config = ConfigDict(frozen=True)
+ tag: Literal["ok"] = "ok"
+ tool_count: int
+
+
+ class ServerListFault(BaseModel):
+ """Why a server contributed nothing to a listing: the caller must authenticate upstream
+ (``auth_required``/``forbidden``), the upstream did not answer (``timeout``/``unreachable``),
+ the upstream answered outside its contract (``upstream_error``), or the gateway itself failed
+ (``internal``). ``status_code`` is the upstream HTTP status when one exists."""
+
+ model_config = ConfigDict(frozen=True)
+ tag: ListFaultCategory
+ status_code: int | None = None
+
+
+ ServerOutcome: TypeAlias = ServerListOk | ServerListFault
+
+ SERVER_OUTCOMES_META_KEY = "litellm.ai/server_outcomes"
+ """The tools/list result ``_meta`` key carrying per-server outcomes. Prefixed with the litellm.ai
+ domain per the MCP spec's ``_meta`` key format so it cannot collide with spec-reserved names."""
+
+
+ class AggregateToolListing(NamedTuple):
+ tools: list[MCPTool]
+ outcomes: dict[str, ServerOutcome]
+
+
+ def _iter_upstream_responses(exc: BaseException) -> Iterator[httpx.Response]:
- """Yield every ``httpx.Response`` in the exception tree (``__cause__``/``__context__``/
- ExceptionGroup members) in deliberate order, mirroring how upstream failures surface through the
- MCP SDK's task groups. Explicit links come first: each node's ``raise ... from`` cause, then
- group members in raise order, then the incidental ``__context__`` chain, so a response raised
- while handling the real failure can never shadow one on the explicit causal chain. Consumers
- apply their own predicate over the stream: selecting the first response and THEN testing it
- would miss a causal auth response sitting behind an unrelated earlier one."""
- seen: set[int] = set()
- stack = [exc]
- while stack:
- current = stack.pop()
- if id(current) in seen:
- continue
- seen.add(id(current))
++ """Yield every ``httpx.Response`` in the exception tree, in the shared traversal's deliberate
++ order (explicit causes first, ExceptionGroup members in raise order, the incidental
++ ``__context__`` chain last), so a response raised while handling the real failure can never
++ shadow one on the explicit causal chain. Consumers apply their own predicate over the stream:
++ selecting the first response and THEN testing it would miss a causal auth response sitting
++ behind an unrelated earlier one."""
++ for current in iter_exception_tree(exc):
+ response = getattr(current, "response", None)
+ if isinstance(response, httpx.Response):
+ yield response
- if current.__context__ is not None:
- stack.append(current.__context__)
- exceptions = getattr(current, "exceptions", None)
- if isinstance(exceptions, tuple):
- stack.extend(reversed(exceptions))
- if current.__cause__ is not None:
- stack.append(current.__cause__)
+
+
+ def _find_upstream_response(exc: BaseException) -> httpx.Response | None:
+ return next(_iter_upstream_responses(exc), None)
+
+
+ def upstream_auth_challenge(exc: BaseException) -> tuple[int, str | None] | None:
+ """The first upstream 401/403 in deliberate order and its ``WWW-Authenticate`` challenge, both
+ read from the SAME response, so the status that picks the carrier channel and the challenge that
+ rides with it can never come from two different responses in the tree. Non-auth responses do not
+ end the scan: a causal 401 behind an unrelated 5xx must still be found, or the client never
+ receives the challenge it needs to re-authenticate."""
+ for response in _iter_upstream_responses(exc):
+ if response.status_code in (401, 403):
+ return response.status_code, response.headers.get("www-authenticate")
+ return None
+
+
+ def raise_classified_list_failure(
+ exc: BaseException,
+ server_name: str,
+ suppress_challenge: bool = False,
+ ) -> NoReturn:
+ """The one place a failed server fetch chooses its carrier: an upstream 401/403 travels as
+ ``MCPUpstreamAuthError`` with the upstream's own challenge preserved (a challenge is only ever
+ fabricated at the HTTP edge, and only for a 401), everything else as ``MCPServerListError`` with
+ a classified fault. Every fetch site delegates here so the two channels cannot drift apart per
+ call site. ``suppress_challenge`` is for dcr_bridge servers, whose upstream challenge points
+ clients at the wrong protected-resource metadata and must never relay."""
+ auth = upstream_auth_challenge(exc)
+ if auth is not None:
+ status_code, challenge = auth
+ raise MCPUpstreamAuthError(
+ status_code=status_code,
+ www_authenticate=None if suppress_challenge else challenge,
+ server_name=server_name,
+ ) from exc
+ raise MCPServerListError(classify_list_exception(exc), server_name) from exc
+
+
+ def classify_list_exception(exc: BaseException) -> ServerListFault:
+ """Classify a per-server listing failure into exactly one outcome. Total: an exception this
+ function cannot recognize is the gateway's own fault (``internal``), never a re-raise."""
+ if isinstance(exc, MCPServerListError) and isinstance(exc.fault, ServerListFault):
+ return exc.fault
+ if isinstance(exc, MCPUpstreamAuthError):
+ tag = "forbidden" if exc.status_code == 403 else "auth_required"
+ return ServerListFault(tag=tag, status_code=exc.status_code)
+ if isinstance(exc, TimeoutError):
+ return ServerListFault(tag="timeout")
+ if isinstance(exc, ConnectionError):
+ return ServerListFault(tag="unreachable")
+ auth = upstream_auth_challenge(exc)
+ if auth is not None:
+ status_code, _ = auth
+ return ServerListFault(
+ tag="forbidden" if status_code == 403 else "auth_required",
+ status_code=status_code,
+ )
+ response = _find_upstream_response(exc)
+ if response is not None:
+ return ServerListFault(tag="upstream_error", status_code=response.status_code)
+ if isinstance(exc, (httpx.TimeoutException,)):
+ return ServerListFault(tag="timeout")
+ if isinstance(exc, httpx.TransportError):
+ return ServerListFault(tag="unreachable")
+ return ServerListFault(tag="internal")
+
+
+ def outcome_wire_value(outcome: ServerOutcome) -> dict[str, object]:
+ """The client-visible form of one outcome, for the tools/list result ``_meta`` and the REST
+ response: category plus status code only, never upstream prose or URLs."""
+ match outcome.tag:
+ case "ok":
+ return {"status": "ok", "tool_count": outcome.tool_count}
+ case "auth_required" | "forbidden" | "timeout" | "unreachable" | "upstream_error" | "internal":
+ return {
+ "status": outcome.tag,
+ **({"http_status": outcome.status_code} if outcome.status_code is not None else {}),
+ }
+ case _:
+ assert_never(outcome.tag)
+
+
+ def list_fault_http_status(fault: ServerListFault) -> int:
+ """The truthful HTTP status for a single-upstream listing fault per RFC 9110: the upstream's own
+ 401/403 for auth, 504 for a timeout, 502 for an unreachable or misbehaving upstream, and 500 only
+ for the gateway's own failure."""
+ match fault.tag:
+ case "auth_required":
+ return fault.status_code or 401
+ case "forbidden":
+ return 403
+ case "timeout":
+ return 504
+ case "unreachable" | "upstream_error":
+ return 502
+ case "internal":
+ return 500
+ case _:
+ assert_never(fault.tag)
diff --cc litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index f2d3f568635,d06dad34d8c..8f30071eb5d
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@@ -437,22 -685,14 +685,14 @@@ def _caller_authorization_fans_out
def _extract_upstream_auth_failure(
exc: BaseException,
) -> Optional[tuple[int, Optional[str]]]:
- """Walk the exception tree looking for an HTTP 401/403 response from the
- upstream MCP server.
+ """The upstream 401/403 and its ``WWW-Authenticate`` header from the exception tree, or ``None``.
- The MCP SDK wraps transport errors in anyio ``ExceptionGroup`` objects and
- may chain through ``__cause__`` / ``__context__``; ``iter_exception_tree``
- visits all of those layers, explicit links first. The first exception
- bearing a real ``httpx.Response`` with a 401/403 wins, and its status code
- and upstream ``WWW-Authenticate`` header are extracted.
-
- Returns ``(status_code, www_authenticate)`` on match, else ``None``.
- """
- for current in iter_exception_tree(exc):
- response = getattr(current, "response", None)
- if isinstance(response, httpx.Response) and response.status_code in (401, 403):
- return response.status_code, response.headers.get("www-authenticate")
- return None
- Delegates to the shared traversal in ``faults.list_outcomes`` so every consumer (tool listing,
++ Delegates to the shared traversal in ``faults`` so every consumer (tool listing,
+ tool calls, the connect-time probe) selects the same response with the same deliberate order:
+ explicit ``raise ... from`` causes first, ExceptionGroup members in raise order, the incidental
+ ``__context__`` chain last. A response raised while handling the real failure can therefore never
+ shadow the causal one."""
+ return upstream_auth_challenge(exc)
def _warn_on_server_name_fields(
diff --cc tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py
index 28ee7435702,d864b442bd3..83e4dcf5677
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py
@@@ -1666,29 -1913,250 +1913,278 @@@ def test_is_context_window_error_detect
assert not _is_context_window_error(None)
+def test_is_context_window_error_sees_through_trees_the_chain_walk_missed():
+ """Overflow shapes the old single-path depth-5 chain walk could not reach: hidden in
+ ``__context__`` behind a non-matching ``__cause__``, buried inside an anyio-style
+ ``ExceptionGroup``, and chained deeper than five links."""
+ import litellm
+ from litellm.proxy._experimental.mcp_server.semantic_tool_filter import (
+ _is_context_window_error,
+ )
+
+ def _cwe() -> litellm.ContextWindowExceededError:
+ return litellm.ContextWindowExceededError(message="overflow", model="m", llm_provider="openai")
+
+ shadowed = ValueError("wrapper")
+ shadowed.__cause__ = TypeError("unrelated failure")
+ shadowed.__context__ = _cwe()
+ assert _is_context_window_error(shadowed)
+
+ grouped = BaseExceptionGroup("task group", [RuntimeError("sibling"), _cwe()])
+ assert _is_context_window_error(grouped)
+
+ deep: BaseException = _cwe()
+ for depth in range(6):
+ wrapper = ValueError(f"layer {depth}")
+ wrapper.__cause__ = deep
+ deep = wrapper
+ assert _is_context_window_error(deep)
++
++
+ def _make_keyword_embedding_router(recorded_inputs):
+ """
+ Mock litellm Router whose embeddings are deterministic keyword one-hots:
+ texts mentioning linear/issue/ticket embed to [1, 0], everything else to
+ [0, 1]. Lets tests assert real similarity ranking through the actual
+ semantic-router index. Every embedding input batch is appended to
+ recorded_inputs.
+ """
+ from litellm.types.utils import Embedding, EmbeddingResponse
+
+ def _vector(text):
+ lowered = text.lower()
+ if "kanban" in lowered:
+ return [0.6, 0.8]
+ if "linear" in lowered or "issue" in lowered or "ticket" in lowered:
+ return [1.0, 0.0]
+ return [0.0, 1.0]
+
+ def mock_embedding_sync(*args, **kwargs):
+ texts = kwargs["input"]
+ recorded_inputs.append(list(texts))
+ return EmbeddingResponse(
+ data=[Embedding(embedding=_vector(t), index=i, object="embedding") for i, t in enumerate(texts)],
+ model="text-embedding-3-small",
+ object="list",
+ usage={"prompt_tokens": 10, "total_tokens": 10},
+ )
+
+ async def mock_embedding_async(*args, **kwargs):
+ return mock_embedding_sync(*args, **kwargs)
+
+ mock_router = Mock()
+ mock_router.embedding = mock_embedding_sync
+ mock_router.aembedding = mock_embedding_async
+ return mock_router
+
+
+ def _make_keyword_filter(recorded_inputs, top_k: int = 3):
+ from litellm.proxy._experimental.mcp_server.semantic_tool_filter import (
+ SemanticMCPToolFilter,
+ )
+
+ return SemanticMCPToolFilter(
+ embedding_model="text-embedding-3-small",
+ litellm_router_instance=_make_keyword_embedding_router(recorded_inputs),
+ top_k=top_k,
+ similarity_threshold=0.3,
+ enabled=True,
+ )
+
+
+ def _linear_issue_tool():
+ return MCPTool(
+ name="linear_stub-get_issue",
+ description="Get a Linear issue (ticket) by its identifier such as LIT-1234",
+ inputSchema={"type": "object"},
+ )
+
+
+ def _linear_list_tool():
+ return MCPTool(
+ name="linear_stub-list_issues",
+ description="List Linear issues (tickets) in the workspace",
+ inputSchema={"type": "object"},
+ )
+
+
+ def _weather_tool():
+ return MCPTool(
+ name="weather_stub-get_weather",
+ description="Get the current weather conditions for a city",
+ inputSchema={"type": "object"},
+ )
+
+
+ @pytest.mark.asyncio
+ async def test_filter_indexes_request_tools_when_startup_index_is_empty():
+ """
+ Regression test: the startup index is built by listing every MCP server
+ WITHOUT per-user credentials, so a gateway whose servers all require
+ per-user auth (e.g. interactive OAuth) starts with an empty index
+ (tool_router is None). filter_tools then failed open and returned all N
+ tools unfiltered (customer-visible as an N->N header and, past 128 tools,
+ an OpenAI 400 "tools array too long"). The authed request-time tools must
+ instead be indexed on first sight so filtering actually runs.
+ """
+ filter_instance = _make_keyword_filter([])
+ assert filter_instance.tool_router is None
+
+ tools = [_linear_issue_tool(), _weather_tool()]
+ filtered = await filter_instance.filter_tools(
+ query="what is Linear ticket LIT-3794 about",
+ available_tools=tools,
+ )
+
+ assert [t.name for t in filtered] == ["linear_stub-get_issue"]
+ print("✅ Empty startup index is built from authed request-time tools")
+
+
+ @pytest.mark.asyncio
+ async def test_filter_indexes_tools_missing_from_partial_index():
+ """
+ Regression test: servers whose tools/list needs per-user auth contribute
+ zero routes to the startup index while anonymously listable servers are
+ indexed. Tools reaching the filter through the authed request-time
+ expansion must be added to the existing router (and only embedded once;
+ repeat requests embed just the query).
+ """
+ recorded_inputs = []
+ filter_instance = _make_keyword_filter(recorded_inputs)
+ filter_instance._build_router([_weather_tool()])
+ assert filter_instance.tool_router is not None
+
+ tools = [_linear_issue_tool(), _weather_tool()]
+ query = "what is Linear ticket LIT-3794 about"
+
+ filtered = await filter_instance.filter_tools(query=query, available_tools=tools)
+ assert [t.name for t in filtered] == ["linear_stub-get_issue"]
+
+ calls_after_first = len(recorded_inputs)
+ filtered_again = await filter_instance.filter_tools(query=query, available_tools=tools)
+ assert [t.name for t in filtered_again] == ["linear_stub-get_issue"]
+ assert len(recorded_inputs) == calls_after_first + 1
+
+ print("✅ Partial startup index is completed from request-time tools, embedding each tool once")
+
+
+ @pytest.mark.asyncio
+ async def test_filter_fails_open_when_matches_are_not_in_available_tools():
+ """
+ Regression test: when the semantic router's matches are all tools that are
+ NOT in the request's available_tools (an index/request mismatch), the
+ filter returned an empty list, stripping every tool from the request and
+ breaking it outright (observed live as a 3->0 header followed by a
+ provider 400). It must fail open with the full tool list instead, matching
+ the zero-match fallback.
+ """
+ filter_instance = _make_keyword_filter([])
+ filter_instance._build_router([_weather_tool()])
+
+ tools = [_linear_issue_tool(), _linear_list_tool()]
+ filtered = await filter_instance.filter_tools(
+ query="current weather in San Francisco",
+ available_tools=tools,
+ )
+
+ assert [t.name for t in filtered] == ["linear_stub-get_issue", "linear_stub-list_issues"]
+ print("✅ Matches outside available_tools fail open instead of dropping every tool")
+
+
+ @pytest.mark.asyncio
+ async def test_request_time_context_window_error_is_request_scoped():
+ """
+ Regression test: an oversized tool description hitting the embedding
+ context window while lazily indexing request-time tools must fail only
+ the requesting call. Previously the lazy path reused the startup build
+ and recorded the overflow in the shared context_window_error, after
+ which EVERY user's MCP requests on the worker were blocked with a 400
+ until restart (index poisoning via a single request).
+ """
+ from litellm.proxy._experimental.mcp_server.semantic_tool_filter import (
+ SemanticToolFilterContextWindowError,
+ )
+
+ state = {"raise_context_error": True}
+ filter_instance = _make_context_window_filter(state)
+ tools = [
+ MCPTool(name="tool_a", description="Tool A", inputSchema={"type": "object"}),
+ MCPTool(name="tool_b", description="Tool B", inputSchema={"type": "object"}),
+ ]
+
+ with pytest.raises(SemanticToolFilterContextWindowError):
+ await filter_instance.filter_tools(query="send an email", available_tools=tools)
+
+ assert filter_instance.context_window_error is None
+ assert filter_instance.tool_router is None
+
+ state["raise_context_error"] = False
+ filtered = await filter_instance.filter_tools(query="send an email", available_tools=tools)
+
+ assert len(filtered) > 0
+ assert filter_instance.context_window_error is None
+ assert filter_instance.tool_router is not None
+ print("✅ Request-time context window overflow is scoped to the request, not the worker")
+
+
+ @pytest.mark.asyncio
+ async def test_foreign_index_routes_cannot_displace_available_tools():
+ """
+ Regression test: routes indexed from OTHER principals' tool listings must
+ not occupy the match candidate set for this request. Previously the
+ router matched over the whole shared index, so foreign routes that
+ embedded closer to the query displaced the caller's own tools from
+ top_k, degrading results to the fail-open list (or, before the
+ empty-result guard, stripping every tool). Matching is now scoped to the
+ request's own tool names via route_filter.
+ """
+ filter_instance = _make_keyword_filter([], top_k=1)
+ foreign_tools = [
+ MCPTool(
+ name=f"other_user-linear_tool_{i}",
+ description=f"Get a Linear issue variant {i}",
+ inputSchema={"type": "object"},
+ )
+ for i in range(6)
+ ]
+ filter_instance._build_router(foreign_tools)
+
+ my_kanban = MCPTool(
+ name="mine-kanban_board",
+ description="Manage kanban board cards",
+ inputSchema={"type": "object"},
+ )
+ filtered = await filter_instance.filter_tools(
+ query="what is Linear ticket LIT-3794 about",
+ available_tools=[my_kanban, _weather_tool()],
+ )
+
+ assert [t.name for t in filtered] == ["mine-kanban_board"]
+ print("✅ Foreign index routes cannot displace the caller's own tools")
+
+
+ @pytest.mark.asyncio
+ async def test_top_k_above_router_default_is_respected():
+ """
+ Regression test: semantic-router's SemanticRouter defaults to top_k=5 at
+ the index-query layer, silently capping any configured filter top_k
+ above 5 regardless of the limit passed to __call__. The router must be
+ sized (and resized) to honor the configured top_k.
+ """
+ filter_instance = _make_keyword_filter([], top_k=6)
+ tools = [
+ MCPTool(
+ name=f"linear_stub-tool_{i}",
+ description=f"Work with Linear issues part {i}",
+ inputSchema={"type": "object"},
+ )
+ for i in range(6)
+ ]
+
+ filtered = await filter_instance.filter_tools(
+ query="Linear ticket work",
+ available_tools=tools,
+ )
+
+ assert len(filtered) == 6
+ print("✅ Configured top_k above the semantic-router default of 5 is honored")