From 5edc48692849dd5e6a817f681ef1fe6237a10a4c Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Mon, 13 Jul 2026 11:09:01 -0700 Subject: [PATCH 01/17] test(e2e): cover MCP gateway auth headers and per-server max concurrency --- pyproject.toml | 1 + tests/e2e/CLAUDE.md | 3 +- tests/e2e/coverage_registry/mcp.yaml | 8 + tests/e2e/docker-compose.yml | 10 +- tests/e2e/e2e_config.py | 6 + tests/e2e/mcp/conftest.py | 19 +++ tests/e2e/mcp/mcp_client.py | 208 ++++++++++++++++++++++++++ tests/e2e/mcp/stub/Dockerfile | 9 ++ tests/e2e/mcp/stub/stub_server.py | 71 +++++++++ tests/e2e/mcp/test_mcp_gateway_e2e.py | 174 +++++++++++++++++++++ tests/e2e/models.py | 25 ++++ uv.lock | 2 + 12 files changed, 534 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/mcp/conftest.py create mode 100644 tests/e2e/mcp/mcp_client.py create mode 100644 tests/e2e/mcp/stub/Dockerfile create mode 100644 tests/e2e/mcp/stub/stub_server.py create mode 100644 tests/e2e/mcp/test_mcp_gateway_e2e.py diff --git a/pyproject.toml b/pyproject.toml index 2c19bf64b4f6..0fdbd29c6db1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -189,6 +189,7 @@ dev = [ e2e-dev = [ "playwright==1.61.0", "websockets>=15.0.1,<16.0", + "mcp>=1.26.0,<2.0", ] proxy-dev = [ "prisma==0.11.0", diff --git a/tests/e2e/CLAUDE.md b/tests/e2e/CLAUDE.md index 0e1eafb51965..e2d13c80e35e 100644 --- a/tests/e2e/CLAUDE.md +++ b/tests/e2e/CLAUDE.md @@ -13,6 +13,7 @@ Each subdirectory under `tests/e2e/` is one suite, scoped to an endpoint family - `realtime/` - realtime websocket sessions, including the pipecat audio path - `quota_management/` - quota enforcement and accounting, one subfolder per behavior: `ratelimit/` (rpm/tpm blocks, window reset, pacing headers on live traffic), `budgets/` (budget definition, enforcement, and reset windows: key, team, tag, soft, multi-window), and `spend_tracking/` (spend logging and cost attribution on `/spend/*`) - `management/` - key/team/user/organization management routes: create/update/delete persistence via the info routes, team membership, and llm-only-key route denials; also the dashboard UI behavior on top of them, driven through the proxy-served UI at /ui with playwright (optional dep behind importorskip) +- `mcp/` - the MCP gateway: server registration via `/v1/mcp/server`, tool listing/calling over the streamable-http protocol under both auth headers, and per-server enforcement such as `max_concurrent_requests`; `stub/` holds the deterministic upstream MCP server the compose stack runs for it - `logging/` - logging-integration delivery (datadog and friends) - `security/` - secret handling and log-leak protection - `router/` - routing and reliability behavior (fallbacks, cooldowns) @@ -107,7 +108,7 @@ MCPs - endpoint features with the protocol op as the variant mcp... operation : list_tools | call_tool | list_resources | read_resource | list_prompts | get_prompt auth_family : none | api_key | bearer | oauth - assertion : succeeds | denied_without_permission + assertion : succeeds | denied_without_permission | caps_concurrency e.g. mcp.call_tool.oauth.succeeds ``` diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml index d477b257cb0f..e7d028136c32 100644 --- a/tests/e2e/coverage_registry/mcp.yaml +++ b/tests/e2e/coverage_registry/mcp.yaml @@ -79,6 +79,14 @@ assertions: [succeeds] source: "rest_endpoints.py:305-334" rationale: No upstream auth required; demo servers +- id: mcp.call_tool.api_key.caps_concurrency + module: mcp + tier: P1 + operation: call_tool + auth_family: api_key + assertions: [caps_concurrency] + source: "mcp_server_manager.py:3751" + rationale: Per-server max_concurrent_requests semaphore bounds in-flight upstream tool calls; excess calls queue - id: mcp.get_prompt.api_key.succeeds module: mcp tier: P1 diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml index 5f75409f0253..63fe884cfba5 100644 --- a/tests/e2e/docker-compose.yml +++ b/tests/e2e/docker-compose.yml @@ -166,7 +166,15 @@ services: target: /app/config.yaml command: ["--config", "/app/config.yaml", "--port", "4000"] -# throwaway db + mcp-stub: + build: ./mcp/stub + healthcheck: + test: ["CMD", "python", "-c", "import socket; socket.create_connection(('localhost', 8765), timeout=2)"] + interval: 3s + timeout: 3s + retries: 20 + +# throwaway db db: image: postgres:16 environment: diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.py index e84438430fd0..8864efd752fa 100644 --- a/tests/e2e/e2e_config.py +++ b/tests/e2e/e2e_config.py @@ -36,6 +36,12 @@ # service records every intake POST and replays them on GET /requests). DD_SINK_URL = os.environ.get("E2E_DD_SINK_URL", "http://localhost:9915").rstrip("/") +# The MCP upstream the mcp suite registers on the proxy: the mcp-stub compose +# service, addressed by service name on the compose network. It must be +# reachable from the proxy, not from pytest; override when the proxy under +# test runs somewhere the compose stub is not visible from. +MCP_STUB_URL = os.environ.get("E2E_MCP_STUB_URL", "http://mcp-stub:8765/mcp") + # Writes on the proxy are eventually consistent (e.g. spend rows flush on # proxy_batch_write_at, ~60s). Read-backs poll to this deadline, never sleep-once. POLL_TIMEOUT = float(os.environ.get("E2E_POLL_TIMEOUT", "120")) diff --git a/tests/e2e/mcp/conftest.py b/tests/e2e/mcp/conftest.py new file mode 100644 index 000000000000..f9a0fbf8d806 --- /dev/null +++ b/tests/e2e/mcp/conftest.py @@ -0,0 +1,19 @@ +"""Fixtures for the mcp e2e suite. + +The shared lifecycle (`resources`, `scoped_key`), the liveness gate, and the +`e2e` marker come from the parent tests/e2e/conftest.py; this adds the suite +client. The mcp SDK lives in the `e2e-dev` dependency group (like playwright +for management/), so its import is guarded to skip the suite rather than +error at collection when it is not installed. +""" + +import pytest + +pytest.importorskip("mcp", reason="mcp SDK not installed; run `uv sync --inexact --group e2e-dev`") + +from mcp_client import McpClient, build_client # noqa: E402 # import must follow the importorskip guard above + + +@pytest.fixture(scope="session") +def client() -> McpClient: + return build_client() diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py new file mode 100644 index 000000000000..010d4b32a954 --- /dev/null +++ b/tests/e2e/mcp/mcp_client.py @@ -0,0 +1,208 @@ +"""Client for the mcp e2e suite. + +Management routes (/v1/mcp/server CRUD) go through the shared Gateway +transport. The MCP protocol itself (initialize, tools/list, tools/call over +streamable HTTP) goes through the official mcp SDK, the same client library +production MCP hosts use, aimed at the gateway's per-server URL namespace +{PROXY}/{alias}/mcp. The gateway accepts the LiteLLM virtual key as either +`x-litellm-api-key: Bearer sk-...` or `Authorization: Bearer sk-...` (both +Bearer-prefixed on the MCP routes, matching the docs); `McpAuth` models the +two header styles so each test states which one it drives. +""" + +from __future__ import annotations + +import asyncio +import time +from dataclasses import dataclass +from typing import Literal, Mapping, cast + +import httpx +import pytest +from mcp import ClientSession +from mcp.client.streamable_http import streamable_http_client +from mcp.types import CallToolResult, TextContent +from pydantic import BaseModel + +from e2e_config import PROXY_BASE_URL, REQUEST_TIMEOUT +from e2e_gateway import Gateway, build_gateway +from e2e_http import NoBody, unwrap +from models import McpServerCreateBody, McpServerInfo + +McpHeaderName = Literal["x-litellm-api-key", "Authorization"] + +ToolArguments = Mapping[str, str | float] + + +@dataclass(frozen=True, slots=True) +class McpAuth: + """One of the two documented ways to present a LiteLLM key to the MCP gateway.""" + + header_name: McpHeaderName + key: str + + def headers(self) -> dict[str, str]: + return {self.header_name: f"Bearer {self.key}"} + + +@dataclass(frozen=True, slots=True) +class McpToolNames: + names: tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class McpDenied: + """A tools/list attempt the gateway rejected before serving the session.""" + + status_code: int | None + message: str + + +type ListToolsOutcome = McpToolNames | McpDenied + + +@dataclass(frozen=True, slots=True) +class McpToolText: + """The text content of one tools/call result.""" + + text: str + is_error: bool + + +class StubToolStats(BaseModel): + """JSON the stub's `stats` tool returns for one marker (see stub/stub_server.py).""" + + marker: str + max_in_flight: int + completed: int + + +def _mcp_url(alias: str) -> str: + return f"{PROXY_BASE_URL}/{alias}/mcp" + + +def _first_text(result: CallToolResult) -> str: + first = result.content[0] if result.content else None + if isinstance(first, TextContent): + return first.text + return f"" + + +def _http_status(root: BaseException) -> int | None: + """The HTTP status behind an SDK failure; the SDK wraps transport errors in + (possibly nested) ExceptionGroups, so walk them without recursing.""" + pending: list[BaseException] = [root] # mutable-ok: bounded worklist over an exception tree + while pending: + exc = pending.pop() + if isinstance(exc, httpx.HTTPStatusError): + return exc.response.status_code + if isinstance(exc, BaseExceptionGroup): + pending.extend(cast("tuple[BaseException, ...]", exc.exceptions)) + return None + + +def _http_client(headers: dict[str, str]) -> httpx.AsyncClient: + return httpx.AsyncClient(headers=headers, timeout=httpx.Timeout(REQUEST_TIMEOUT), follow_redirects=True) + + +async def _list_tool_names(url: str, headers: dict[str, str]) -> tuple[str, ...]: + async with _http_client(headers) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + listed = await session.list_tools() + return tuple(sorted(tool.name for tool in listed.tools)) + + +async def _call_tool(url: str, headers: dict[str, str], tool: str, arguments: ToolArguments) -> McpToolText: + async with _http_client(headers) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + result = await session.call_tool(tool, dict(arguments)) + return McpToolText(text=_first_text(result), is_error=bool(result.isError)) + + +@dataclass(frozen=True, slots=True) +class McpClient: + gateway: Gateway + + def create_server(self, body: McpServerCreateBody) -> McpServerInfo: + return unwrap( + self.gateway.transport.post( + "/v1/mcp/server", + headers=self.gateway.transport.master, + json=body, + response_type=McpServerInfo, + ) + ) + + def server_info(self, server_id: str) -> McpServerInfo: + return unwrap( + self.gateway.transport.get( + f"/v1/mcp/server/{server_id}", + headers=self.gateway.transport.master, + params=NoBody(), + response_type=McpServerInfo, + ) + ) + + def delete_server(self, server_id: str) -> None: + _ = self.gateway.transport.delete( + f"/v1/mcp/server/{server_id}", + headers=self.gateway.transport.master, + json=NoBody(), + response_type=NoBody, + ) + + def list_tools_once(self, alias: str, auth: McpAuth) -> ListToolsOutcome: + try: + return McpToolNames(names=asyncio.run(_list_tool_names(_mcp_url(alias), auth.headers()))) + except Exception as exc: # noqa: BLE001 - the SDK raises ExceptionGroup-wrapped transport errors; modelled as a value + return McpDenied(status_code=_http_status(exc), message=str(exc)) + + def poll_tool_names(self, alias: str, auth: McpAuth) -> tuple[str, ...]: + """tools/list to the shared deadline: a just-created server record + propagates to the gateway asynchronously and a just-created key can lag + the auth cache, so the first attempts may 401 or list nothing.""" + deadline = time.monotonic() + self.gateway.poll_timeout + outcome: ListToolsOutcome = McpDenied(status_code=None, message="never attempted") + while time.monotonic() < deadline: + outcome = self.list_tools_once(alias, auth) + match outcome: + case McpToolNames(names=names) if names: + return names + case _: + time.sleep(self.gateway.poll_interval) + pytest.fail( + f"MCP tools for {alias!r} never listed within {self.gateway.poll_timeout}s; last outcome: {outcome}" + ) + + def call_tool(self, alias: str, auth: McpAuth, tool: str, arguments: ToolArguments) -> McpToolText: + return asyncio.run(_call_tool(_mcp_url(alias), auth.headers(), tool, arguments)) + + def burst_call_tool( + self, + alias: str, + auth: McpAuth, + tool: str, + arguments_per_call: tuple[ToolArguments, ...], + ) -> tuple[McpToolText, ...]: + """Fire every call at once, each over its own MCP session, like N + independent clients hitting the gateway simultaneously.""" + + async def _burst() -> tuple[McpToolText, ...]: + url = _mcp_url(alias) + headers = auth.headers() + results = await asyncio.gather(*(_call_tool(url, headers, tool, args) for args in arguments_per_call)) + return tuple(results) + + return asyncio.run(_burst()) + + def stub_stats(self, alias: str, auth: McpAuth, stats_tool: str, marker: str) -> StubToolStats: + outcome = self.call_tool(alias, auth, stats_tool, {"marker": marker}) + return StubToolStats.model_validate_json(outcome.text) + + +def build_client() -> McpClient: + return McpClient(gateway=build_gateway()) diff --git a/tests/e2e/mcp/stub/Dockerfile b/tests/e2e/mcp/stub/Dockerfile new file mode 100644 index 000000000000..2b09b33217d1 --- /dev/null +++ b/tests/e2e/mcp/stub/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim + +RUN pip install --no-cache-dir mcp==1.26.0 + +WORKDIR /app +COPY stub_server.py /app/stub_server.py + +EXPOSE 8765 +CMD ["python", "stub_server.py"] diff --git a/tests/e2e/mcp/stub/stub_server.py b/tests/e2e/mcp/stub/stub_server.py new file mode 100644 index 000000000000..89d44a365661 --- /dev/null +++ b/tests/e2e/mcp/stub/stub_server.py @@ -0,0 +1,71 @@ +"""Deterministic MCP upstream for the mcp e2e suite. + +Serves the streamable-http MCP protocol with three tools. `echo` answers +immediately so auth tests can assert an exact round-trip. `slow_echo` holds the +request open for `sleep_seconds` while per-`marker` in-flight and max-in-flight +counters track how many calls the proxy let through simultaneously; that is the +observable a per-server `max_concurrent_requests` cap must bound. `stats` reads +those counters back, so tests observe upstream concurrency through the proxy +itself and the stub needs no side-channel port. + +Counter updates are plain attribute mutations between awaits, so asyncio's +single-threaded scheduling makes them atomic; markers come from +`unique_marker()` so concurrent test runs never share a counter. +""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import dataclass + +from mcp.server.fastmcp import FastMCP + +mcp = FastMCP("e2e-stub", host="0.0.0.0", port=8765, stateless_http=True) + + +@dataclass +class _MarkerStats: + in_flight: int = 0 + max_in_flight: int = 0 + completed: int = 0 + + +_stats: dict[str, _MarkerStats] = {} + + +@mcp.tool() +def echo(text: str) -> str: + """Return `text` unchanged.""" + return text + + +@mcp.tool() +async def slow_echo(text: str, marker: str, sleep_seconds: float) -> str: + """Return `text` after `sleep_seconds`, recording concurrency under `marker`.""" + stats = _stats.setdefault(marker, _MarkerStats()) + stats.in_flight += 1 + stats.max_in_flight = max(stats.max_in_flight, stats.in_flight) + try: + await asyncio.sleep(sleep_seconds) + finally: + stats.in_flight -= 1 + stats.completed += 1 + return text + + +@mcp.tool() +def stats(marker: str) -> str: + """Return the JSON stats recorded for `marker`.""" + recorded = _stats.get(marker, _MarkerStats()) + return json.dumps( + { + "marker": marker, + "max_in_flight": recorded.max_in_flight, + "completed": recorded.completed, + } + ) + + +if __name__ == "__main__": + mcp.run(transport="streamable-http") diff --git a/tests/e2e/mcp/test_mcp_gateway_e2e.py b/tests/e2e/mcp/test_mcp_gateway_e2e.py new file mode 100644 index 000000000000..daa4af78551d --- /dev/null +++ b/tests/e2e/mcp/test_mcp_gateway_e2e.py @@ -0,0 +1,174 @@ +"""Live e2e: MCP gateway tool access and the per-server concurrency cap. + +Covers mcp.list_tools.api_key.succeeds + mcp.call_tool.api_key.succeeds (the +`x-litellm-api-key` header), mcp.list_tools.bearer.succeeds + +mcp.call_tool.bearer.succeeds (the `Authorization` header), and +mcp.call_tool.api_key.caps_concurrency (`max_concurrent_requests`), all +against the deterministic mcp-stub compose service (tests/e2e/mcp/stub/). + +Each test walks the full lifecycle: register the server over the management +API and defer its deletion, assert the recorded state round-trips +(GET /v1/mcp/server/{id} echoes what was configured), then drive the real MCP +protocol through the gateway the way a production MCP host does (initialize, +tools/list, tools/call over streamable HTTP at {PROXY}/{alias}/mcp) and +assert the enforced behavior. Both auth headers carry `Bearer `; that is +the documented contract on the MCP routes (a bare key in `x-litellm-api-key` +is accepted on LLM routes but 401s here). + +The concurrency test's observable is the stub's own per-marker in-flight +counter, read back through the proxy via the stub's `stats` tool. The +proxy-side semaphore queues excess tool calls instead of rejecting them, so +with a cap of MAX_CONCURRENT a burst of BURST simultaneous slow_echo calls +must all succeed while the stub never sees more than MAX_CONCURRENT of them +overlap. The uncapped control server drives the identical burst through the +identical machinery and must see all BURST calls overlap; that is the +fail-before-fix evidence built into the test, since a broken (or skipped) +semaphore makes the capped server record BURST in-flight exactly like the +control and the equality assertion fail. +""" + +from __future__ import annotations + +import pytest + +from e2e_config import MCP_STUB_URL, unique_marker +from lifecycle import ResourceManager +from mcp_client import McpAuth, McpClient, McpDenied +from models import McpServerCreateBody + +pytestmark = pytest.mark.e2e + +STUB_TOOLS = ("echo", "slow_echo", "stats") +MAX_CONCURRENT = 2 +BURST = 6 +SLOW_CALL_SECONDS = 2.0 + + +class TestMcpToolAccess: + """Any virtual key reaches an allow_all_keys server through either + documented auth header; a key the proxy does not recognize is turned away + at the door.""" + + @pytest.mark.covers("mcp.list_tools.api_key.succeeds") + @pytest.mark.covers("mcp.call_tool.api_key.succeeds") + def test_list_and_call_tools_with_x_litellm_api_key_header( + self, client: McpClient, resources: ResourceManager, scoped_key: str + ) -> None: + alias = f"e2emcp{unique_marker()}" + created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_URL + assert stored.allow_all_keys is True + + auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) + names = client.poll_tool_names(alias, auth) + expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) + assert names == expected, f"gateway listed {names}, expected exactly {expected}" + + payload = f"e2e-{unique_marker()}" + result = client.call_tool(alias, auth, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo call errored: {result.text[:300]}" + assert result.text == payload + + denied = client.list_tools_once(alias, McpAuth(header_name="x-litellm-api-key", key="sk-not-a-real-key")) + assert isinstance(denied, McpDenied), f"unrecognized key was served tools: {denied}" + assert denied.status_code == 401, f"expected 401 for an unrecognized key, got {denied}" + + @pytest.mark.covers("mcp.list_tools.bearer.succeeds") + @pytest.mark.covers("mcp.call_tool.bearer.succeeds") + def test_list_and_call_tools_with_authorization_bearer_header( + self, client: McpClient, resources: ResourceManager, scoped_key: str + ) -> None: + alias = f"e2emcp{unique_marker()}" + created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_URL + + auth = McpAuth(header_name="Authorization", key=scoped_key) + names = client.poll_tool_names(alias, auth) + expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) + assert names == expected, f"gateway listed {names}, expected exactly {expected}" + + payload = f"e2e-{unique_marker()}" + result = client.call_tool(alias, auth, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo call errored: {result.text[:300]}" + assert result.text == payload + + +class TestMcpServerMaxConcurrency: + """`max_concurrent_requests` bounds how many tool calls the gateway lets + reach one server at a time; excess calls queue and still succeed.""" + + @pytest.mark.covers("mcp.call_tool.api_key.caps_concurrency") + def test_max_concurrent_requests_caps_in_flight_upstream_calls( + self, client: McpClient, resources: ResourceManager, scoped_key: str + ) -> None: + auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) + + capped_alias = f"e2emcpcap{unique_marker()}" + capped = client.create_server( + McpServerCreateBody( + alias=capped_alias, + url=MCP_STUB_URL, + allow_all_keys=True, + max_concurrent_requests=MAX_CONCURRENT, + ) + ) + resources.defer(lambda: client.delete_server(capped.server_id)) + + control_alias = f"e2emcpfree{unique_marker()}" + control = client.create_server(McpServerCreateBody(alias=control_alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(control.server_id)) + + assert client.server_info(capped.server_id).max_concurrent_requests == MAX_CONCURRENT + assert client.server_info(control.server_id).max_concurrent_requests is None + + _ = client.poll_tool_names(capped_alias, auth) + _ = client.poll_tool_names(control_alias, auth) + + capped_marker = unique_marker() + capped_results = client.burst_call_tool( + capped_alias, + auth, + f"{capped_alias}-slow_echo", + tuple( + {"text": "capped", "marker": capped_marker, "sleep_seconds": SLOW_CALL_SECONDS} + for _ in range(BURST) + ), + ) + assert len(capped_results) == BURST + assert all(result.is_error is False and result.text == "capped" for result in capped_results), ( + f"queued calls must all still succeed under the cap: {capped_results}" + ) + + capped_stats = client.stub_stats(capped_alias, auth, f"{capped_alias}-stats", capped_marker) + assert capped_stats.completed == BURST + assert capped_stats.max_in_flight == MAX_CONCURRENT, ( + f"stub saw {capped_stats.max_in_flight} overlapping calls; the cap of {MAX_CONCURRENT} " + f"must be the exact ceiling AND be reached ({BURST} queued calls saturate it)" + ) + + control_marker = unique_marker() + control_results = client.burst_call_tool( + control_alias, + auth, + f"{control_alias}-slow_echo", + tuple( + {"text": "control", "marker": control_marker, "sleep_seconds": SLOW_CALL_SECONDS} + for _ in range(BURST) + ), + ) + assert all(result.is_error is False and result.text == "control" for result in control_results) + + control_stats = client.stub_stats(control_alias, auth, f"{control_alias}-stats", control_marker) + assert control_stats.completed == BURST + assert control_stats.max_in_flight == BURST, ( + f"uncapped control saw {control_stats.max_in_flight} overlapping calls, expected all {BURST}; " + f"if this fails the instrument cannot detect over-cap concurrency and the capped assertion is vacuous" + ) diff --git a/tests/e2e/models.py b/tests/e2e/models.py index c4ecd0cfa638..4a0981c4d6db 100644 --- a/tests/e2e/models.py +++ b/tests/e2e/models.py @@ -95,6 +95,31 @@ class KeyInfoResponse(BaseModel): info: KeyInfo +# ---------- mcp servers ---------- + + +class McpServerCreateBody(BaseModel): + """POST /v1/mcp/server. `allow_all_keys` opts the server out of per-key + object_permission grants so any virtual key on the proxy may use it.""" + + alias: str + url: str + transport: str = "http" + allow_all_keys: bool = True + max_concurrent_requests: int | None = None + + +class McpServerInfo(BaseModel): + """Response of POST /v1/mcp/server and GET /v1/mcp/server/{server_id}.""" + + server_id: str + alias: str | None = None + url: str | None = None + transport: str | None = None + allow_all_keys: bool | None = None + max_concurrent_requests: int | None = None + + # ---------- customers ---------- diff --git a/uv.lock b/uv.lock index 22e3a3feece4..1ed564439836 100644 --- a/uv.lock +++ b/uv.lock @@ -3926,6 +3926,7 @@ dev = [ { name = "vcrpy" }, ] e2e-dev = [ + { name = "mcp" }, { name = "playwright" }, { name = "websockets" }, ] @@ -4101,6 +4102,7 @@ dev = [ { name = "vcrpy", specifier = "==8.2.1" }, ] e2e-dev = [ + { name = "mcp", specifier = ">=1.26.0,<2.0" }, { name = "playwright", specifier = "==1.61.0" }, { name = "websockets", specifier = ">=15.0.1,<16.0" }, ] From d74cf13489fb9a059acfb935a44ef98b8036c220 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Mon, 13 Jul 2026 11:23:05 -0700 Subject: [PATCH 02/17] fix(e2e): restore uv.lock exclude-newer anchor and gate proxy startup on mcp-stub health --- tests/e2e/docker-compose.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml index 63fe884cfba5..89430c9b7586 100644 --- a/tests/e2e/docker-compose.yml +++ b/tests/e2e/docker-compose.yml @@ -131,6 +131,8 @@ services: condition: service_healthy dd-sink: condition: service_healthy + mcp-stub: + condition: service_healthy env_file: .env environment: LITELLM_MASTER_KEY: sk-1234 From 565a87212c870b815c790c700dd7149700875850 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Mon, 13 Jul 2026 12:01:10 -0700 Subject: [PATCH 03/17] refactor(e2e): inline the concurrency burst in the test via a thread pool --- tests/e2e/mcp/mcp_client.py | 20 ++--------- tests/e2e/mcp/test_mcp_gateway_e2e.py | 48 ++++++++++++++++++--------- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index 010d4b32a954..c4c6a317364e 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -179,26 +179,10 @@ def poll_tool_names(self, alias: str, auth: McpAuth) -> tuple[str, ...]: ) def call_tool(self, alias: str, auth: McpAuth, tool: str, arguments: ToolArguments) -> McpToolText: + """One tools/call over its own fresh MCP session, so concurrent callers + behave like independent clients.""" return asyncio.run(_call_tool(_mcp_url(alias), auth.headers(), tool, arguments)) - def burst_call_tool( - self, - alias: str, - auth: McpAuth, - tool: str, - arguments_per_call: tuple[ToolArguments, ...], - ) -> tuple[McpToolText, ...]: - """Fire every call at once, each over its own MCP session, like N - independent clients hitting the gateway simultaneously.""" - - async def _burst() -> tuple[McpToolText, ...]: - url = _mcp_url(alias) - headers = auth.headers() - results = await asyncio.gather(*(_call_tool(url, headers, tool, args) for args in arguments_per_call)) - return tuple(results) - - return asyncio.run(_burst()) - def stub_stats(self, alias: str, auth: McpAuth, stats_tool: str, marker: str) -> StubToolStats: outcome = self.call_tool(alias, auth, stats_tool, {"marker": marker}) return StubToolStats.model_validate_json(outcome.text) diff --git a/tests/e2e/mcp/test_mcp_gateway_e2e.py b/tests/e2e/mcp/test_mcp_gateway_e2e.py index daa4af78551d..196d6462373b 100644 --- a/tests/e2e/mcp/test_mcp_gateway_e2e.py +++ b/tests/e2e/mcp/test_mcp_gateway_e2e.py @@ -29,6 +29,8 @@ from __future__ import annotations +from concurrent.futures import ThreadPoolExecutor + import pytest from e2e_config import MCP_STUB_URL, unique_marker @@ -109,6 +111,12 @@ class TestMcpServerMaxConcurrency: def test_max_concurrent_requests_caps_in_flight_upstream_calls( self, client: McpClient, resources: ResourceManager, scoped_key: str ) -> None: + """Two servers against the same stub: one capped at MAX_CONCURRENT, one + uncapped control. The tools/list polls are the settle step; they hold + until the just-created records are servable on the gateway (and the + fresh key has cleared the auth cache) so the bursts measure the + semaphore, not propagation. Each burst is BURST simultaneous slow_echo + calls, one per thread, each over its own MCP session.""" auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) capped_alias = f"e2emcpcap{unique_marker()}" @@ -133,15 +141,19 @@ def test_max_concurrent_requests_caps_in_flight_upstream_calls( _ = client.poll_tool_names(control_alias, auth) capped_marker = unique_marker() - capped_results = client.burst_call_tool( - capped_alias, - auth, - f"{capped_alias}-slow_echo", - tuple( - {"text": "capped", "marker": capped_marker, "sleep_seconds": SLOW_CALL_SECONDS} + with ThreadPoolExecutor(max_workers=BURST) as pool: + futures = [ + pool.submit( + client.call_tool, + capped_alias, + auth, + f"{capped_alias}-slow_echo", + {"text": "capped", "marker": capped_marker, "sleep_seconds": SLOW_CALL_SECONDS}, + ) for _ in range(BURST) - ), - ) + ] + capped_results = [future.result() for future in futures] + assert len(capped_results) == BURST assert all(result.is_error is False and result.text == "capped" for result in capped_results), ( f"queued calls must all still succeed under the cap: {capped_results}" @@ -155,15 +167,19 @@ def test_max_concurrent_requests_caps_in_flight_upstream_calls( ) control_marker = unique_marker() - control_results = client.burst_call_tool( - control_alias, - auth, - f"{control_alias}-slow_echo", - tuple( - {"text": "control", "marker": control_marker, "sleep_seconds": SLOW_CALL_SECONDS} + with ThreadPoolExecutor(max_workers=BURST) as pool: + futures = [ + pool.submit( + client.call_tool, + control_alias, + auth, + f"{control_alias}-slow_echo", + {"text": "control", "marker": control_marker, "sleep_seconds": SLOW_CALL_SECONDS}, + ) for _ in range(BURST) - ), - ) + ] + control_results = [future.result() for future in futures] + assert all(result.is_error is False and result.text == "control" for result in control_results) control_stats = client.stub_stats(control_alias, auth, f"{control_alias}-stats", control_marker) From 23dffc74535181590aa07fc478fb340cbcda141c Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Mon, 13 Jul 2026 12:16:53 -0700 Subject: [PATCH 04/17] fix(e2e): use a plain union assignment instead of a PEP 695 type statement --- tests/e2e/mcp/mcp_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index c4c6a317364e..c6bb720eecc4 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -58,7 +58,7 @@ class McpDenied: message: str -type ListToolsOutcome = McpToolNames | McpDenied +ListToolsOutcome = McpToolNames | McpDenied @dataclass(frozen=True, slots=True) From ff3ef9d7e869c845f7f2d1e60fec223446d0710e Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Mon, 13 Jul 2026 12:35:50 -0700 Subject: [PATCH 05/17] refactor(e2e): keep the concurrency test self-contained with local tuning values --- tests/e2e/mcp/test_mcp_gateway_e2e.py | 90 +++++++++++---------------- 1 file changed, 37 insertions(+), 53 deletions(-) diff --git a/tests/e2e/mcp/test_mcp_gateway_e2e.py b/tests/e2e/mcp/test_mcp_gateway_e2e.py index 196d6462373b..a45295cd2f8f 100644 --- a/tests/e2e/mcp/test_mcp_gateway_e2e.py +++ b/tests/e2e/mcp/test_mcp_gateway_e2e.py @@ -18,13 +18,12 @@ The concurrency test's observable is the stub's own per-marker in-flight counter, read back through the proxy via the stub's `stats` tool. The proxy-side semaphore queues excess tool calls instead of rejecting them, so -with a cap of MAX_CONCURRENT a burst of BURST simultaneous slow_echo calls -must all succeed while the stub never sees more than MAX_CONCURRENT of them -overlap. The uncapped control server drives the identical burst through the -identical machinery and must see all BURST calls overlap; that is the -fail-before-fix evidence built into the test, since a broken (or skipped) -semaphore makes the capped server record BURST in-flight exactly like the -control and the equality assertion fail. +under a cap every call in a simultaneous burst must still succeed while the +stub never sees more than the cap overlap. The uncapped control server drives +the identical burst through the identical machinery and must see the whole +burst overlap; that is the fail-before-fix evidence built into the test, +since a broken (or skipped) semaphore makes the capped server record the full +burst exactly like the control and the equality assertion fail. """ from __future__ import annotations @@ -35,15 +34,12 @@ from e2e_config import MCP_STUB_URL, unique_marker from lifecycle import ResourceManager -from mcp_client import McpAuth, McpClient, McpDenied +from mcp_client import McpAuth, McpClient, McpDenied, McpToolText from models import McpServerCreateBody pytestmark = pytest.mark.e2e STUB_TOOLS = ("echo", "slow_echo", "stats") -MAX_CONCURRENT = 2 -BURST = 6 -SLOW_CALL_SECONDS = 2.0 class TestMcpToolAccess: @@ -111,12 +107,15 @@ class TestMcpServerMaxConcurrency: def test_max_concurrent_requests_caps_in_flight_upstream_calls( self, client: McpClient, resources: ResourceManager, scoped_key: str ) -> None: - """Two servers against the same stub: one capped at MAX_CONCURRENT, one - uncapped control. The tools/list polls are the settle step; they hold - until the just-created records are servable on the gateway (and the - fresh key has cleared the auth cache) so the bursts measure the - semaphore, not propagation. Each burst is BURST simultaneous slow_echo - calls, one per thread, each over its own MCP session.""" + """Two servers against the same stub: one capped at 2 concurrent + requests, one uncapped control. The tools/list polls are the settle + step; they hold until the just-created records are servable on the + gateway (and the fresh key has cleared the auth cache) so the bursts + measure the semaphore, not propagation. Each burst is 6 simultaneous + slow_echo calls, one per thread, each over its own MCP session.""" + max_concurrent = 2 + burst_size = 6 + slow_call_seconds = 2.0 auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) capped_alias = f"e2emcpcap{unique_marker()}" @@ -125,7 +124,7 @@ def test_max_concurrent_requests_caps_in_flight_upstream_calls( alias=capped_alias, url=MCP_STUB_URL, allow_all_keys=True, - max_concurrent_requests=MAX_CONCURRENT, + max_concurrent_requests=max_concurrent, ) ) resources.defer(lambda: client.delete_server(capped.server_id)) @@ -134,57 +133,42 @@ def test_max_concurrent_requests_caps_in_flight_upstream_calls( control = client.create_server(McpServerCreateBody(alias=control_alias, url=MCP_STUB_URL, allow_all_keys=True)) resources.defer(lambda: client.delete_server(control.server_id)) - assert client.server_info(capped.server_id).max_concurrent_requests == MAX_CONCURRENT + assert client.server_info(capped.server_id).max_concurrent_requests == max_concurrent assert client.server_info(control.server_id).max_concurrent_requests is None _ = client.poll_tool_names(capped_alias, auth) _ = client.poll_tool_names(control_alias, auth) + def burst_of_slow_calls(alias: str, text: str, marker: str) -> list[McpToolText]: + arguments = {"text": text, "marker": marker, "sleep_seconds": slow_call_seconds} + with ThreadPoolExecutor(max_workers=burst_size) as pool: + futures = [ + pool.submit(client.call_tool, alias, auth, f"{alias}-slow_echo", arguments) + for _ in range(burst_size) + ] + return [future.result() for future in futures] + capped_marker = unique_marker() - with ThreadPoolExecutor(max_workers=BURST) as pool: - futures = [ - pool.submit( - client.call_tool, - capped_alias, - auth, - f"{capped_alias}-slow_echo", - {"text": "capped", "marker": capped_marker, "sleep_seconds": SLOW_CALL_SECONDS}, - ) - for _ in range(BURST) - ] - capped_results = [future.result() for future in futures] - - assert len(capped_results) == BURST + capped_results = burst_of_slow_calls(capped_alias, "capped", capped_marker) + assert len(capped_results) == burst_size assert all(result.is_error is False and result.text == "capped" for result in capped_results), ( f"queued calls must all still succeed under the cap: {capped_results}" ) capped_stats = client.stub_stats(capped_alias, auth, f"{capped_alias}-stats", capped_marker) - assert capped_stats.completed == BURST - assert capped_stats.max_in_flight == MAX_CONCURRENT, ( - f"stub saw {capped_stats.max_in_flight} overlapping calls; the cap of {MAX_CONCURRENT} " - f"must be the exact ceiling AND be reached ({BURST} queued calls saturate it)" + assert capped_stats.completed == burst_size + assert capped_stats.max_in_flight == max_concurrent, ( + f"stub saw {capped_stats.max_in_flight} overlapping calls; the cap of {max_concurrent} " + f"must be the exact ceiling AND be reached ({burst_size} queued calls saturate it)" ) control_marker = unique_marker() - with ThreadPoolExecutor(max_workers=BURST) as pool: - futures = [ - pool.submit( - client.call_tool, - control_alias, - auth, - f"{control_alias}-slow_echo", - {"text": "control", "marker": control_marker, "sleep_seconds": SLOW_CALL_SECONDS}, - ) - for _ in range(BURST) - ] - control_results = [future.result() for future in futures] - + control_results = burst_of_slow_calls(control_alias, "control", control_marker) assert all(result.is_error is False and result.text == "control" for result in control_results) control_stats = client.stub_stats(control_alias, auth, f"{control_alias}-stats", control_marker) - assert control_stats.completed == BURST - assert control_stats.max_in_flight == BURST, ( - f"uncapped control saw {control_stats.max_in_flight} overlapping calls, expected all {BURST}; " + assert control_stats.completed == burst_size + assert control_stats.max_in_flight == burst_size, ( + f"uncapped control saw {control_stats.max_in_flight} overlapping calls, expected all {burst_size}; " f"if this fails the instrument cannot detect over-cap concurrency and the capped assertion is vacuous" ) From 9ff988d7efb6d22e0c307c58c402fc7e456cd0ab Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Tue, 14 Jul 2026 19:27:17 -0700 Subject: [PATCH 06/17] refactor(e2e): split the mcp gateway suite into feature-scoped specs with a parametrized auth-header matrix --- tests/e2e/coverage_registry/mcp.yaml | 16 ++ tests/e2e/mcp/test_mcp_concurrency_e2e.py | 104 +++++++++++++ tests/e2e/mcp/test_mcp_gateway_e2e.py | 174 ---------------------- tests/e2e/mcp/test_mcp_tool_access_e2e.py | 116 +++++++++++++++ 4 files changed, 236 insertions(+), 174 deletions(-) create mode 100644 tests/e2e/mcp/test_mcp_concurrency_e2e.py delete mode 100644 tests/e2e/mcp/test_mcp_gateway_e2e.py create mode 100644 tests/e2e/mcp/test_mcp_tool_access_e2e.py diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml index e7d028136c32..4a8854660b6a 100644 --- a/tests/e2e/coverage_registry/mcp.yaml +++ b/tests/e2e/coverage_registry/mcp.yaml @@ -47,6 +47,22 @@ assertions: [succeeds] source: "server.py:886" rationale: Bearer token forwarding for tool invocation +- id: mcp.list_tools.api_key.rejects_unknown_key + module: mcp + tier: P1 + operation: list_tools + auth_family: api_key + assertions: [rejects_unknown_key] + source: "auth/user_api_key_auth_mcp.py:141 process_mcp_request" + rationale: An unrecognized virtual key must be refused with 401 at session establishment, before any upstream traffic +- id: mcp.list_tools.bearer.rejects_unknown_key + module: mcp + tier: P1 + operation: list_tools + auth_family: bearer + assertions: [rejects_unknown_key] + source: "auth/user_api_key_auth_mcp.py:141 process_mcp_request" + rationale: The Authorization header form must be refused identically to x-litellm-api-key; the two ingress styles share one contract - id: mcp.list_tools.oauth.succeeds module: mcp tier: P1 diff --git a/tests/e2e/mcp/test_mcp_concurrency_e2e.py b/tests/e2e/mcp/test_mcp_concurrency_e2e.py new file mode 100644 index 000000000000..9c1f87ded18e --- /dev/null +++ b/tests/e2e/mcp/test_mcp_concurrency_e2e.py @@ -0,0 +1,104 @@ +"""Live e2e: the per-server MCP concurrency cap. + +Covers mcp.call_tool.api_key.caps_concurrency (`max_concurrent_requests`) +against the deterministic mcp-stub compose service (tests/e2e/mcp/stub/). + +The observable is the stub's own per-marker in-flight counter, read back +through the proxy via the stub's `stats` tool, so the test needs no +side-channel port into the upstream. The proxy-side semaphore queues excess +tool calls instead of rejecting them, so under a cap every call in a +simultaneous burst must still succeed while the stub never sees more than the +cap overlap. The uncapped control server drives the identical burst through +the identical machinery and must see the whole burst overlap; that is the +fail-before-fix evidence built into the test, since a broken (or skipped) +semaphore makes the capped server record the full burst exactly like the +control and the equality assertion fail. +""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor + +import pytest + +from e2e_config import MCP_STUB_URL, unique_marker +from lifecycle import ResourceManager +from mcp_client import McpAuth, McpClient, McpToolText +from models import McpServerCreateBody + +pytestmark = pytest.mark.e2e + + +class TestMcpServerMaxConcurrency: + """`max_concurrent_requests` bounds how many tool calls the gateway lets + reach one server at a time; excess calls queue and still succeed.""" + + @pytest.mark.covers("mcp.call_tool.api_key.caps_concurrency") + def test_max_concurrent_requests_caps_in_flight_upstream_calls( + self, client: McpClient, resources: ResourceManager, scoped_key: str + ) -> None: + """Two servers against the same stub: one capped at 2 concurrent + requests, one uncapped control. The tools/list polls are the settle + step; they hold until the just-created records are servable on the + gateway (and the fresh key has cleared the auth cache) so the bursts + measure the semaphore, not propagation. Each burst is 6 simultaneous + slow_echo calls, one per thread, each over its own MCP session.""" + max_concurrent = 2 + burst_size = 6 + slow_call_seconds = 2.0 + auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) + + capped_alias = f"e2emcpcap{unique_marker()}" + capped = client.create_server( + McpServerCreateBody( + alias=capped_alias, + url=MCP_STUB_URL, + allow_all_keys=True, + max_concurrent_requests=max_concurrent, + ) + ) + resources.defer(lambda: client.delete_server(capped.server_id)) + + control_alias = f"e2emcpfree{unique_marker()}" + control = client.create_server(McpServerCreateBody(alias=control_alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(control.server_id)) + + assert client.server_info(capped.server_id).max_concurrent_requests == max_concurrent + assert client.server_info(control.server_id).max_concurrent_requests is None + + _ = client.poll_tool_names(capped_alias, auth) + _ = client.poll_tool_names(control_alias, auth) + + def burst_of_slow_calls(alias: str, text: str, marker: str) -> list[McpToolText]: + arguments = {"text": text, "marker": marker, "sleep_seconds": slow_call_seconds} + with ThreadPoolExecutor(max_workers=burst_size) as pool: + futures = [ + pool.submit(client.call_tool, alias, auth, f"{alias}-slow_echo", arguments) + for _ in range(burst_size) + ] + return [future.result() for future in futures] + + capped_marker = unique_marker() + capped_results = burst_of_slow_calls(capped_alias, "capped", capped_marker) + assert len(capped_results) == burst_size + assert all(result.is_error is False and result.text == "capped" for result in capped_results), ( + f"queued calls must all still succeed under the cap: {capped_results}" + ) + + capped_stats = client.stub_stats(capped_alias, auth, f"{capped_alias}-stats", capped_marker) + assert capped_stats.completed == burst_size + assert capped_stats.max_in_flight == max_concurrent, ( + f"stub saw {capped_stats.max_in_flight} overlapping calls; the cap of {max_concurrent} " + f"must be the exact ceiling AND be reached ({burst_size} queued calls saturate it)" + ) + + control_marker = unique_marker() + control_results = burst_of_slow_calls(control_alias, "control", control_marker) + assert all(result.is_error is False and result.text == "control" for result in control_results) + + control_stats = client.stub_stats(control_alias, auth, f"{control_alias}-stats", control_marker) + assert control_stats.completed == burst_size + assert control_stats.max_in_flight == burst_size, ( + f"uncapped control saw {control_stats.max_in_flight} overlapping calls, expected all {burst_size}; " + f"if this fails the instrument cannot detect over-cap concurrency and the capped assertion is vacuous" + ) diff --git a/tests/e2e/mcp/test_mcp_gateway_e2e.py b/tests/e2e/mcp/test_mcp_gateway_e2e.py deleted file mode 100644 index a45295cd2f8f..000000000000 --- a/tests/e2e/mcp/test_mcp_gateway_e2e.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Live e2e: MCP gateway tool access and the per-server concurrency cap. - -Covers mcp.list_tools.api_key.succeeds + mcp.call_tool.api_key.succeeds (the -`x-litellm-api-key` header), mcp.list_tools.bearer.succeeds + -mcp.call_tool.bearer.succeeds (the `Authorization` header), and -mcp.call_tool.api_key.caps_concurrency (`max_concurrent_requests`), all -against the deterministic mcp-stub compose service (tests/e2e/mcp/stub/). - -Each test walks the full lifecycle: register the server over the management -API and defer its deletion, assert the recorded state round-trips -(GET /v1/mcp/server/{id} echoes what was configured), then drive the real MCP -protocol through the gateway the way a production MCP host does (initialize, -tools/list, tools/call over streamable HTTP at {PROXY}/{alias}/mcp) and -assert the enforced behavior. Both auth headers carry `Bearer `; that is -the documented contract on the MCP routes (a bare key in `x-litellm-api-key` -is accepted on LLM routes but 401s here). - -The concurrency test's observable is the stub's own per-marker in-flight -counter, read back through the proxy via the stub's `stats` tool. The -proxy-side semaphore queues excess tool calls instead of rejecting them, so -under a cap every call in a simultaneous burst must still succeed while the -stub never sees more than the cap overlap. The uncapped control server drives -the identical burst through the identical machinery and must see the whole -burst overlap; that is the fail-before-fix evidence built into the test, -since a broken (or skipped) semaphore makes the capped server record the full -burst exactly like the control and the equality assertion fail. -""" - -from __future__ import annotations - -from concurrent.futures import ThreadPoolExecutor - -import pytest - -from e2e_config import MCP_STUB_URL, unique_marker -from lifecycle import ResourceManager -from mcp_client import McpAuth, McpClient, McpDenied, McpToolText -from models import McpServerCreateBody - -pytestmark = pytest.mark.e2e - -STUB_TOOLS = ("echo", "slow_echo", "stats") - - -class TestMcpToolAccess: - """Any virtual key reaches an allow_all_keys server through either - documented auth header; a key the proxy does not recognize is turned away - at the door.""" - - @pytest.mark.covers("mcp.list_tools.api_key.succeeds") - @pytest.mark.covers("mcp.call_tool.api_key.succeeds") - def test_list_and_call_tools_with_x_litellm_api_key_header( - self, client: McpClient, resources: ResourceManager, scoped_key: str - ) -> None: - alias = f"e2emcp{unique_marker()}" - created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) - resources.defer(lambda: client.delete_server(created.server_id)) - - stored = client.server_info(created.server_id) - assert stored.alias == alias - assert stored.url == MCP_STUB_URL - assert stored.allow_all_keys is True - - auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) - names = client.poll_tool_names(alias, auth) - expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) - assert names == expected, f"gateway listed {names}, expected exactly {expected}" - - payload = f"e2e-{unique_marker()}" - result = client.call_tool(alias, auth, f"{alias}-echo", {"text": payload}) - assert result.is_error is False, f"echo call errored: {result.text[:300]}" - assert result.text == payload - - denied = client.list_tools_once(alias, McpAuth(header_name="x-litellm-api-key", key="sk-not-a-real-key")) - assert isinstance(denied, McpDenied), f"unrecognized key was served tools: {denied}" - assert denied.status_code == 401, f"expected 401 for an unrecognized key, got {denied}" - - @pytest.mark.covers("mcp.list_tools.bearer.succeeds") - @pytest.mark.covers("mcp.call_tool.bearer.succeeds") - def test_list_and_call_tools_with_authorization_bearer_header( - self, client: McpClient, resources: ResourceManager, scoped_key: str - ) -> None: - alias = f"e2emcp{unique_marker()}" - created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) - resources.defer(lambda: client.delete_server(created.server_id)) - - stored = client.server_info(created.server_id) - assert stored.alias == alias - assert stored.url == MCP_STUB_URL - - auth = McpAuth(header_name="Authorization", key=scoped_key) - names = client.poll_tool_names(alias, auth) - expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) - assert names == expected, f"gateway listed {names}, expected exactly {expected}" - - payload = f"e2e-{unique_marker()}" - result = client.call_tool(alias, auth, f"{alias}-echo", {"text": payload}) - assert result.is_error is False, f"echo call errored: {result.text[:300]}" - assert result.text == payload - - -class TestMcpServerMaxConcurrency: - """`max_concurrent_requests` bounds how many tool calls the gateway lets - reach one server at a time; excess calls queue and still succeed.""" - - @pytest.mark.covers("mcp.call_tool.api_key.caps_concurrency") - def test_max_concurrent_requests_caps_in_flight_upstream_calls( - self, client: McpClient, resources: ResourceManager, scoped_key: str - ) -> None: - """Two servers against the same stub: one capped at 2 concurrent - requests, one uncapped control. The tools/list polls are the settle - step; they hold until the just-created records are servable on the - gateway (and the fresh key has cleared the auth cache) so the bursts - measure the semaphore, not propagation. Each burst is 6 simultaneous - slow_echo calls, one per thread, each over its own MCP session.""" - max_concurrent = 2 - burst_size = 6 - slow_call_seconds = 2.0 - auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) - - capped_alias = f"e2emcpcap{unique_marker()}" - capped = client.create_server( - McpServerCreateBody( - alias=capped_alias, - url=MCP_STUB_URL, - allow_all_keys=True, - max_concurrent_requests=max_concurrent, - ) - ) - resources.defer(lambda: client.delete_server(capped.server_id)) - - control_alias = f"e2emcpfree{unique_marker()}" - control = client.create_server(McpServerCreateBody(alias=control_alias, url=MCP_STUB_URL, allow_all_keys=True)) - resources.defer(lambda: client.delete_server(control.server_id)) - - assert client.server_info(capped.server_id).max_concurrent_requests == max_concurrent - assert client.server_info(control.server_id).max_concurrent_requests is None - - _ = client.poll_tool_names(capped_alias, auth) - _ = client.poll_tool_names(control_alias, auth) - - def burst_of_slow_calls(alias: str, text: str, marker: str) -> list[McpToolText]: - arguments = {"text": text, "marker": marker, "sleep_seconds": slow_call_seconds} - with ThreadPoolExecutor(max_workers=burst_size) as pool: - futures = [ - pool.submit(client.call_tool, alias, auth, f"{alias}-slow_echo", arguments) - for _ in range(burst_size) - ] - return [future.result() for future in futures] - - capped_marker = unique_marker() - capped_results = burst_of_slow_calls(capped_alias, "capped", capped_marker) - assert len(capped_results) == burst_size - assert all(result.is_error is False and result.text == "capped" for result in capped_results), ( - f"queued calls must all still succeed under the cap: {capped_results}" - ) - - capped_stats = client.stub_stats(capped_alias, auth, f"{capped_alias}-stats", capped_marker) - assert capped_stats.completed == burst_size - assert capped_stats.max_in_flight == max_concurrent, ( - f"stub saw {capped_stats.max_in_flight} overlapping calls; the cap of {max_concurrent} " - f"must be the exact ceiling AND be reached ({burst_size} queued calls saturate it)" - ) - - control_marker = unique_marker() - control_results = burst_of_slow_calls(control_alias, "control", control_marker) - assert all(result.is_error is False and result.text == "control" for result in control_results) - - control_stats = client.stub_stats(control_alias, auth, f"{control_alias}-stats", control_marker) - assert control_stats.completed == burst_size - assert control_stats.max_in_flight == burst_size, ( - f"uncapped control saw {control_stats.max_in_flight} overlapping calls, expected all {burst_size}; " - f"if this fails the instrument cannot detect over-cap concurrency and the capped assertion is vacuous" - ) diff --git a/tests/e2e/mcp/test_mcp_tool_access_e2e.py b/tests/e2e/mcp/test_mcp_tool_access_e2e.py new file mode 100644 index 000000000000..e15c95001554 --- /dev/null +++ b/tests/e2e/mcp/test_mcp_tool_access_e2e.py @@ -0,0 +1,116 @@ +"""Live e2e: MCP gateway tool access under both documented auth headers. + +Covers mcp.list_tools.api_key.succeeds + mcp.call_tool.api_key.succeeds (the +`x-litellm-api-key` header), mcp.list_tools.bearer.succeeds + +mcp.call_tool.bearer.succeeds (the `Authorization` header), and +mcp.list_tools.{api_key,bearer}.rejects_unknown_key (the ingress gate), +all against the deterministic mcp-stub compose service (tests/e2e/mcp/stub/). + +Each test walks the full lifecycle: register the server over the management +API and defer its deletion, assert the recorded state round-trips +(GET /v1/mcp/server/{id} echoes what was configured), then drive the real MCP +protocol through the gateway the way a production MCP host does (initialize, +tools/list, tools/call over streamable HTTP at {PROXY}/{alias}/mcp) and +assert the enforced behavior. Both auth headers carry `Bearer `; that is +the documented contract on the MCP routes (a bare key in `x-litellm-api-key` +is accepted on LLM routes but 401s here). + +The two header styles are one behavior matrix, not two behaviors: the same +test body runs once per header via parametrize, so the specs cannot drift +apart, and each parametrization claims its own registry cells through +param-level `covers` marks. The unknown-key rejection is its own test (also +run per header) and settles the server with a real key first, so its 401 can +only be the gateway's ingress auth refusing the key, never record propagation. +""" + +from __future__ import annotations + +import pytest + +from e2e_config import MCP_STUB_URL, unique_marker +from lifecycle import ResourceManager +from mcp_client import McpAuth, McpClient, McpDenied, McpHeaderName +from models import McpServerCreateBody + +pytestmark = pytest.mark.e2e + +STUB_TOOLS = ("echo", "slow_echo", "stats") + +AUTH_HEADER_MATRIX = ( + pytest.param( + "x-litellm-api-key", + id="x-litellm-api-key", + marks=( + pytest.mark.covers("mcp.list_tools.api_key.succeeds"), + pytest.mark.covers("mcp.call_tool.api_key.succeeds"), + ), + ), + pytest.param( + "Authorization", + id="authorization-bearer", + marks=( + pytest.mark.covers("mcp.list_tools.bearer.succeeds"), + pytest.mark.covers("mcp.call_tool.bearer.succeeds"), + ), + ), +) + +REJECTION_MATRIX = ( + pytest.param( + "x-litellm-api-key", + id="x-litellm-api-key", + marks=pytest.mark.covers("mcp.list_tools.api_key.rejects_unknown_key"), + ), + pytest.param( + "Authorization", + id="authorization-bearer", + marks=pytest.mark.covers("mcp.list_tools.bearer.rejects_unknown_key"), + ), +) + + +class TestMcpToolAccess: + """Any virtual key reaches an allow_all_keys server through either + documented auth header; a key the proxy does not recognize is turned away + at the door.""" + + @pytest.mark.parametrize("header_name", AUTH_HEADER_MATRIX) + def test_list_and_call_tools( + self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager, scoped_key: str + ) -> None: + alias = f"e2emcp{unique_marker()}" + created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_URL + assert stored.allow_all_keys is True + + auth = McpAuth(header_name=header_name, key=scoped_key) + names = client.poll_tool_names(alias, auth) + expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) + assert names == expected, f"gateway listed {names}, expected exactly {expected}" + + payload = f"e2e-{unique_marker()}" + result = client.call_tool(alias, auth, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo call errored: {result.text[:300]}" + assert result.text == payload + + @pytest.mark.parametrize("header_name", REJECTION_MATRIX) + def test_unrecognized_key_is_turned_away( + self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager, scoped_key: str + ) -> None: + """Settle the server with a real key first, then present an unknown + key over the same header: the refusal must be an explicit 401 from + session establishment, and can only be the ingress auth because the + server was just proven servable.""" + alias = f"e2emcp{unique_marker()}" + created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(created.server_id)) + + _ = client.poll_tool_names(alias, McpAuth(header_name=header_name, key=scoped_key)) + + denied = client.list_tools_once(alias, McpAuth(header_name=header_name, key="sk-not-a-real-key")) + assert isinstance(denied, McpDenied), f"unrecognized key was served tools: {denied}" + assert denied.status_code == 401, f"expected 401 for an unrecognized key, got {denied}" From d32974c2820e313e38e688e631eb8a85a8bf37f7 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Tue, 14 Jul 2026 20:06:12 -0700 Subject: [PATCH 07/17] refactor(e2e): build wire headers and mint keys inline in the mcp test bodies --- tests/e2e/mcp/mcp_client.py | 37 +++++++++----------- tests/e2e/mcp/test_mcp_concurrency_e2e.py | 21 +++++++----- tests/e2e/mcp/test_mcp_tool_access_e2e.py | 41 +++++++++++++---------- 3 files changed, 51 insertions(+), 48 deletions(-) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index c6bb720eecc4..46ae99a3d641 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -4,10 +4,14 @@ transport. The MCP protocol itself (initialize, tools/list, tools/call over streamable HTTP) goes through the official mcp SDK, the same client library production MCP hosts use, aimed at the gateway's per-server URL namespace -{PROXY}/{alias}/mcp. The gateway accepts the LiteLLM virtual key as either +{PROXY}/{alias}/mcp. + +Every protocol method takes the request headers as a plain dict, built inside +the test body, so the exact wire format is visible where it is asserted. The +gateway accepts the LiteLLM virtual key as either `x-litellm-api-key: Bearer sk-...` or `Authorization: Bearer sk-...` (both -Bearer-prefixed on the MCP routes, matching the docs); `McpAuth` models the -two header styles so each test states which one it drives. +Bearer-prefixed on the MCP routes, matching the docs); `McpHeaderName` names +those two documented header styles for the tests' parametrized matrices. """ from __future__ import annotations @@ -34,17 +38,6 @@ ToolArguments = Mapping[str, str | float] -@dataclass(frozen=True, slots=True) -class McpAuth: - """One of the two documented ways to present a LiteLLM key to the MCP gateway.""" - - header_name: McpHeaderName - key: str - - def headers(self) -> dict[str, str]: - return {self.header_name: f"Bearer {self.key}"} - - @dataclass(frozen=True, slots=True) class McpToolNames: names: tuple[str, ...] @@ -155,20 +148,20 @@ def delete_server(self, server_id: str) -> None: response_type=NoBody, ) - def list_tools_once(self, alias: str, auth: McpAuth) -> ListToolsOutcome: + def list_tools_once(self, alias: str, headers: dict[str, str]) -> ListToolsOutcome: try: - return McpToolNames(names=asyncio.run(_list_tool_names(_mcp_url(alias), auth.headers()))) + return McpToolNames(names=asyncio.run(_list_tool_names(_mcp_url(alias), headers))) except Exception as exc: # noqa: BLE001 - the SDK raises ExceptionGroup-wrapped transport errors; modelled as a value return McpDenied(status_code=_http_status(exc), message=str(exc)) - def poll_tool_names(self, alias: str, auth: McpAuth) -> tuple[str, ...]: + def poll_tool_names(self, alias: str, headers: dict[str, str]) -> tuple[str, ...]: """tools/list to the shared deadline: a just-created server record propagates to the gateway asynchronously and a just-created key can lag the auth cache, so the first attempts may 401 or list nothing.""" deadline = time.monotonic() + self.gateway.poll_timeout outcome: ListToolsOutcome = McpDenied(status_code=None, message="never attempted") while time.monotonic() < deadline: - outcome = self.list_tools_once(alias, auth) + outcome = self.list_tools_once(alias, headers) match outcome: case McpToolNames(names=names) if names: return names @@ -178,13 +171,13 @@ def poll_tool_names(self, alias: str, auth: McpAuth) -> tuple[str, ...]: f"MCP tools for {alias!r} never listed within {self.gateway.poll_timeout}s; last outcome: {outcome}" ) - def call_tool(self, alias: str, auth: McpAuth, tool: str, arguments: ToolArguments) -> McpToolText: + def call_tool(self, alias: str, headers: dict[str, str], tool: str, arguments: ToolArguments) -> McpToolText: """One tools/call over its own fresh MCP session, so concurrent callers behave like independent clients.""" - return asyncio.run(_call_tool(_mcp_url(alias), auth.headers(), tool, arguments)) + return asyncio.run(_call_tool(_mcp_url(alias), headers, tool, arguments)) - def stub_stats(self, alias: str, auth: McpAuth, stats_tool: str, marker: str) -> StubToolStats: - outcome = self.call_tool(alias, auth, stats_tool, {"marker": marker}) + def stub_stats(self, alias: str, headers: dict[str, str], stats_tool: str, marker: str) -> StubToolStats: + outcome = self.call_tool(alias, headers, stats_tool, {"marker": marker}) return StubToolStats.model_validate_json(outcome.text) diff --git a/tests/e2e/mcp/test_mcp_concurrency_e2e.py b/tests/e2e/mcp/test_mcp_concurrency_e2e.py index 9c1f87ded18e..ccff22d5414d 100644 --- a/tests/e2e/mcp/test_mcp_concurrency_e2e.py +++ b/tests/e2e/mcp/test_mcp_concurrency_e2e.py @@ -23,8 +23,8 @@ from e2e_config import MCP_STUB_URL, unique_marker from lifecycle import ResourceManager -from mcp_client import McpAuth, McpClient, McpToolText -from models import McpServerCreateBody +from mcp_client import McpClient, McpToolText +from models import KeyGenerateBody, McpServerCreateBody pytestmark = pytest.mark.e2e @@ -35,7 +35,7 @@ class TestMcpServerMaxConcurrency: @pytest.mark.covers("mcp.call_tool.api_key.caps_concurrency") def test_max_concurrent_requests_caps_in_flight_upstream_calls( - self, client: McpClient, resources: ResourceManager, scoped_key: str + self, client: McpClient, resources: ResourceManager ) -> None: """Two servers against the same stub: one capped at 2 concurrent requests, one uncapped control. The tools/list polls are the settle @@ -46,7 +46,10 @@ def test_max_concurrent_requests_caps_in_flight_upstream_calls( max_concurrent = 2 burst_size = 6 slow_call_seconds = 2.0 - auth = McpAuth(header_name="x-litellm-api-key", key=scoped_key) + + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + headers = {"x-litellm-api-key": f"Bearer {key}"} capped_alias = f"e2emcpcap{unique_marker()}" capped = client.create_server( @@ -66,14 +69,14 @@ def test_max_concurrent_requests_caps_in_flight_upstream_calls( assert client.server_info(capped.server_id).max_concurrent_requests == max_concurrent assert client.server_info(control.server_id).max_concurrent_requests is None - _ = client.poll_tool_names(capped_alias, auth) - _ = client.poll_tool_names(control_alias, auth) + _ = client.poll_tool_names(capped_alias, headers) + _ = client.poll_tool_names(control_alias, headers) def burst_of_slow_calls(alias: str, text: str, marker: str) -> list[McpToolText]: arguments = {"text": text, "marker": marker, "sleep_seconds": slow_call_seconds} with ThreadPoolExecutor(max_workers=burst_size) as pool: futures = [ - pool.submit(client.call_tool, alias, auth, f"{alias}-slow_echo", arguments) + pool.submit(client.call_tool, alias, headers, f"{alias}-slow_echo", arguments) for _ in range(burst_size) ] return [future.result() for future in futures] @@ -85,7 +88,7 @@ def burst_of_slow_calls(alias: str, text: str, marker: str) -> list[McpToolText] f"queued calls must all still succeed under the cap: {capped_results}" ) - capped_stats = client.stub_stats(capped_alias, auth, f"{capped_alias}-stats", capped_marker) + capped_stats = client.stub_stats(capped_alias, headers, f"{capped_alias}-stats", capped_marker) assert capped_stats.completed == burst_size assert capped_stats.max_in_flight == max_concurrent, ( f"stub saw {capped_stats.max_in_flight} overlapping calls; the cap of {max_concurrent} " @@ -96,7 +99,7 @@ def burst_of_slow_calls(alias: str, text: str, marker: str) -> list[McpToolText] control_results = burst_of_slow_calls(control_alias, "control", control_marker) assert all(result.is_error is False and result.text == "control" for result in control_results) - control_stats = client.stub_stats(control_alias, auth, f"{control_alias}-stats", control_marker) + control_stats = client.stub_stats(control_alias, headers, f"{control_alias}-stats", control_marker) assert control_stats.completed == burst_size assert control_stats.max_in_flight == burst_size, ( f"uncapped control saw {control_stats.max_in_flight} overlapping calls, expected all {burst_size}; " diff --git a/tests/e2e/mcp/test_mcp_tool_access_e2e.py b/tests/e2e/mcp/test_mcp_tool_access_e2e.py index e15c95001554..9a1090e8bdfb 100644 --- a/tests/e2e/mcp/test_mcp_tool_access_e2e.py +++ b/tests/e2e/mcp/test_mcp_tool_access_e2e.py @@ -6,14 +6,16 @@ mcp.list_tools.{api_key,bearer}.rejects_unknown_key (the ingress gate), all against the deterministic mcp-stub compose service (tests/e2e/mcp/stub/). -Each test walks the full lifecycle: register the server over the management -API and defer its deletion, assert the recorded state round-trips -(GET /v1/mcp/server/{id} echoes what was configured), then drive the real MCP -protocol through the gateway the way a production MCP host does (initialize, -tools/list, tools/call over streamable HTTP at {PROXY}/{alias}/mcp) and -assert the enforced behavior. Both auth headers carry `Bearer `; that is -the documented contract on the MCP routes (a bare key in `x-litellm-api-key` -is accepted on LLM routes but 401s here). +Each test body spells out every step a human QA run would take, in order: +create the server over the management API, read the record back, mint a +virtual key over /key/generate, build the exact wire header +(`
: Bearer sk-...`, the documented contract on the MCP routes; a bare +key in `x-litellm-api-key` is accepted on LLM routes but 401s here), then +drive the real MCP protocol through the gateway the way a production MCP host +does (initialize, tools/list, tools/call over streamable HTTP at +{PROXY}/{alias}/mcp) and assert the enforced behavior. Teardown is the only +thing delegated (resources.defer), because it must run even when an +assertion fails. The two header styles are one behavior matrix, not two behaviors: the same test body runs once per header via parametrize, so the specs cannot drift @@ -29,8 +31,8 @@ from e2e_config import MCP_STUB_URL, unique_marker from lifecycle import ResourceManager -from mcp_client import McpAuth, McpClient, McpDenied, McpHeaderName -from models import McpServerCreateBody +from mcp_client import McpClient, McpDenied, McpHeaderName +from models import KeyGenerateBody, McpServerCreateBody pytestmark = pytest.mark.e2e @@ -76,7 +78,7 @@ class TestMcpToolAccess: @pytest.mark.parametrize("header_name", AUTH_HEADER_MATRIX) def test_list_and_call_tools( - self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager, scoped_key: str + self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager ) -> None: alias = f"e2emcp{unique_marker()}" created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) @@ -87,19 +89,22 @@ def test_list_and_call_tools( assert stored.url == MCP_STUB_URL assert stored.allow_all_keys is True - auth = McpAuth(header_name=header_name, key=scoped_key) - names = client.poll_tool_names(alias, auth) + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + + headers = {header_name: f"Bearer {key}"} + names = client.poll_tool_names(alias, headers) expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) assert names == expected, f"gateway listed {names}, expected exactly {expected}" payload = f"e2e-{unique_marker()}" - result = client.call_tool(alias, auth, f"{alias}-echo", {"text": payload}) + result = client.call_tool(alias, headers, f"{alias}-echo", {"text": payload}) assert result.is_error is False, f"echo call errored: {result.text[:300]}" assert result.text == payload @pytest.mark.parametrize("header_name", REJECTION_MATRIX) def test_unrecognized_key_is_turned_away( - self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager, scoped_key: str + self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager ) -> None: """Settle the server with a real key first, then present an unknown key over the same header: the refusal must be an explicit 401 from @@ -109,8 +114,10 @@ def test_unrecognized_key_is_turned_away( created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) resources.defer(lambda: client.delete_server(created.server_id)) - _ = client.poll_tool_names(alias, McpAuth(header_name=header_name, key=scoped_key)) + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + _ = client.poll_tool_names(alias, {header_name: f"Bearer {key}"}) - denied = client.list_tools_once(alias, McpAuth(header_name=header_name, key="sk-not-a-real-key")) + denied = client.list_tools_once(alias, {header_name: "Bearer sk-not-a-real-key"}) assert isinstance(denied, McpDenied), f"unrecognized key was served tools: {denied}" assert denied.status_code == 401, f"expected 401 for an unrecognized key, got {denied}" From b1442d0398b0333890837bbf97b1d8bd6303d115 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Tue, 14 Jul 2026 20:21:26 -0700 Subject: [PATCH 08/17] refactor(e2e): unroll the auth-header matrix into explicitly named per-header tests --- tests/e2e/mcp/mcp_client.py | 7 +- tests/e2e/mcp/test_mcp_tool_access_e2e.py | 120 ++++++++++++---------- 2 files changed, 69 insertions(+), 58 deletions(-) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index 46ae99a3d641..a6ac16fb3e9a 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -10,8 +10,7 @@ the test body, so the exact wire format is visible where it is asserted. The gateway accepts the LiteLLM virtual key as either `x-litellm-api-key: Bearer sk-...` or `Authorization: Bearer sk-...` (both -Bearer-prefixed on the MCP routes, matching the docs); `McpHeaderName` names -those two documented header styles for the tests' parametrized matrices. +Bearer-prefixed on the MCP routes, matching the docs). """ from __future__ import annotations @@ -19,7 +18,7 @@ import asyncio import time from dataclasses import dataclass -from typing import Literal, Mapping, cast +from typing import Mapping, cast import httpx import pytest @@ -33,8 +32,6 @@ from e2e_http import NoBody, unwrap from models import McpServerCreateBody, McpServerInfo -McpHeaderName = Literal["x-litellm-api-key", "Authorization"] - ToolArguments = Mapping[str, str | float] diff --git a/tests/e2e/mcp/test_mcp_tool_access_e2e.py b/tests/e2e/mcp/test_mcp_tool_access_e2e.py index 9a1090e8bdfb..2602425d2189 100644 --- a/tests/e2e/mcp/test_mcp_tool_access_e2e.py +++ b/tests/e2e/mcp/test_mcp_tool_access_e2e.py @@ -8,21 +8,21 @@ Each test body spells out every step a human QA run would take, in order: create the server over the management API, read the record back, mint a -virtual key over /key/generate, build the exact wire header -(`
: Bearer sk-...`, the documented contract on the MCP routes; a bare -key in `x-litellm-api-key` is accepted on LLM routes but 401s here), then -drive the real MCP protocol through the gateway the way a production MCP host -does (initialize, tools/list, tools/call over streamable HTTP at +virtual key over /key/generate, build the exact wire header, then drive the +real MCP protocol through the gateway the way a production MCP host does +(initialize, tools/list, tools/call over streamable HTTP at {PROXY}/{alias}/mcp) and assert the enforced behavior. Teardown is the only thing delegated (resources.defer), because it must run even when an assertion fails. -The two header styles are one behavior matrix, not two behaviors: the same -test body runs once per header via parametrize, so the specs cannot drift -apart, and each parametrization claims its own registry cells through -param-level `covers` marks. The unknown-key rejection is its own test (also -run per header) and settles the server with a real key first, so its 401 can -only be the gateway's ingress auth refusing the key, never record propagation. +The two documented header styles are deliberately separate, explicitly named +tests rather than one parametrized body, so the literal header each one sends +(`x-litellm-api-key: Bearer sk-...` / `Authorization: Bearer sk-...`) is +visible in its own body. Both are Bearer-prefixed on the MCP routes, matching +the docs; a bare key in `x-litellm-api-key` is accepted on LLM routes but +401s here. The unknown-key rejection tests settle the server with a real key +first, so their 401 can only be the gateway's ingress auth refusing the key, +never record propagation. """ from __future__ import annotations @@ -31,54 +31,50 @@ from e2e_config import MCP_STUB_URL, unique_marker from lifecycle import ResourceManager -from mcp_client import McpClient, McpDenied, McpHeaderName +from mcp_client import McpClient, McpDenied from models import KeyGenerateBody, McpServerCreateBody pytestmark = pytest.mark.e2e STUB_TOOLS = ("echo", "slow_echo", "stats") -AUTH_HEADER_MATRIX = ( - pytest.param( - "x-litellm-api-key", - id="x-litellm-api-key", - marks=( - pytest.mark.covers("mcp.list_tools.api_key.succeeds"), - pytest.mark.covers("mcp.call_tool.api_key.succeeds"), - ), - ), - pytest.param( - "Authorization", - id="authorization-bearer", - marks=( - pytest.mark.covers("mcp.list_tools.bearer.succeeds"), - pytest.mark.covers("mcp.call_tool.bearer.succeeds"), - ), - ), -) - -REJECTION_MATRIX = ( - pytest.param( - "x-litellm-api-key", - id="x-litellm-api-key", - marks=pytest.mark.covers("mcp.list_tools.api_key.rejects_unknown_key"), - ), - pytest.param( - "Authorization", - id="authorization-bearer", - marks=pytest.mark.covers("mcp.list_tools.bearer.rejects_unknown_key"), - ), -) - class TestMcpToolAccess: """Any virtual key reaches an allow_all_keys server through either documented auth header; a key the proxy does not recognize is turned away at the door.""" - @pytest.mark.parametrize("header_name", AUTH_HEADER_MATRIX) - def test_list_and_call_tools( - self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager + @pytest.mark.covers("mcp.list_tools.api_key.succeeds") + @pytest.mark.covers("mcp.call_tool.api_key.succeeds") + def test_list_and_call_tools_with_x_litellm_api_key_header( + self, client: McpClient, resources: ResourceManager + ) -> None: + alias = f"e2emcp{unique_marker()}" + created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_URL + assert stored.allow_all_keys is True + + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + + headers = {"x-litellm-api-key": f"Bearer {key}"} + names = client.poll_tool_names(alias, headers) + expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) + assert names == expected, f"gateway listed {names}, expected exactly {expected}" + + payload = f"e2e-{unique_marker()}" + result = client.call_tool(alias, headers, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo call errored: {result.text[:300]}" + assert result.text == payload + + @pytest.mark.covers("mcp.list_tools.bearer.succeeds") + @pytest.mark.covers("mcp.call_tool.bearer.succeeds") + def test_list_and_call_tools_with_authorization_bearer_header( + self, client: McpClient, resources: ResourceManager ) -> None: alias = f"e2emcp{unique_marker()}" created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) @@ -92,7 +88,7 @@ def test_list_and_call_tools( key = client.gateway.generate_key(KeyGenerateBody()) resources.defer(lambda: client.gateway.delete_key(key)) - headers = {header_name: f"Bearer {key}"} + headers = {"Authorization": f"Bearer {key}"} names = client.poll_tool_names(alias, headers) expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) assert names == expected, f"gateway listed {names}, expected exactly {expected}" @@ -102,9 +98,9 @@ def test_list_and_call_tools( assert result.is_error is False, f"echo call errored: {result.text[:300]}" assert result.text == payload - @pytest.mark.parametrize("header_name", REJECTION_MATRIX) - def test_unrecognized_key_is_turned_away( - self, header_name: McpHeaderName, client: McpClient, resources: ResourceManager + @pytest.mark.covers("mcp.list_tools.api_key.rejects_unknown_key") + def test_unrecognized_key_in_x_litellm_api_key_header_is_turned_away( + self, client: McpClient, resources: ResourceManager ) -> None: """Settle the server with a real key first, then present an unknown key over the same header: the refusal must be an explicit 401 from @@ -116,8 +112,26 @@ def test_unrecognized_key_is_turned_away( key = client.gateway.generate_key(KeyGenerateBody()) resources.defer(lambda: client.gateway.delete_key(key)) - _ = client.poll_tool_names(alias, {header_name: f"Bearer {key}"}) + _ = client.poll_tool_names(alias, {"x-litellm-api-key": f"Bearer {key}"}) + + denied = client.list_tools_once(alias, {"x-litellm-api-key": "Bearer sk-not-a-real-key"}) + assert isinstance(denied, McpDenied), f"unrecognized key was served tools: {denied}" + assert denied.status_code == 401, f"expected 401 for an unrecognized key, got {denied}" + + @pytest.mark.covers("mcp.list_tools.bearer.rejects_unknown_key") + def test_unrecognized_key_in_authorization_bearer_header_is_turned_away( + self, client: McpClient, resources: ResourceManager + ) -> None: + """The Authorization form of the same rejection: an unknown key sent + as `Authorization: Bearer ...` must be refused identically.""" + alias = f"e2emcp{unique_marker()}" + created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) + resources.defer(lambda: client.delete_server(created.server_id)) + + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + _ = client.poll_tool_names(alias, {"Authorization": f"Bearer {key}"}) - denied = client.list_tools_once(alias, {header_name: "Bearer sk-not-a-real-key"}) + denied = client.list_tools_once(alias, {"Authorization": "Bearer sk-not-a-real-key"}) assert isinstance(denied, McpDenied), f"unrecognized key was served tools: {denied}" assert denied.status_code == 401, f"expected 401 for an unrecognized key, got {denied}" From 1b42f655b3199c3ead883b067ccfd877c1d40198 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Tue, 14 Jul 2026 21:01:52 -0700 Subject: [PATCH 09/17] test(e2e): cover the interactive authorization_code MCP OAuth flow end to end --- tests/e2e/CLAUDE.md | 2 +- tests/e2e/coverage_registry/mcp.yaml | 16 ++ tests/e2e/docker-compose.yml | 2 + tests/e2e/e2e_config.py | 20 ++ tests/e2e/mcp/mcp_client.py | 184 ++++++++++++++- tests/e2e/mcp/stub/stub_server.py | 220 ++++++++++++++++-- .../e2e/mcp/test_mcp_oauth_interactive_e2e.py | 117 ++++++++++ tests/e2e/models.py | 22 ++ 8 files changed, 560 insertions(+), 23 deletions(-) create mode 100644 tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py diff --git a/tests/e2e/CLAUDE.md b/tests/e2e/CLAUDE.md index e2d13c80e35e..aa05208dd8c1 100644 --- a/tests/e2e/CLAUDE.md +++ b/tests/e2e/CLAUDE.md @@ -13,7 +13,7 @@ Each subdirectory under `tests/e2e/` is one suite, scoped to an endpoint family - `realtime/` - realtime websocket sessions, including the pipecat audio path - `quota_management/` - quota enforcement and accounting, one subfolder per behavior: `ratelimit/` (rpm/tpm blocks, window reset, pacing headers on live traffic), `budgets/` (budget definition, enforcement, and reset windows: key, team, tag, soft, multi-window), and `spend_tracking/` (spend logging and cost attribution on `/spend/*`) - `management/` - key/team/user/organization management routes: create/update/delete persistence via the info routes, team membership, and llm-only-key route denials; also the dashboard UI behavior on top of them, driven through the proxy-served UI at /ui with playwright (optional dep behind importorskip) -- `mcp/` - the MCP gateway: server registration via `/v1/mcp/server`, tool listing/calling over the streamable-http protocol under both auth headers, and per-server enforcement such as `max_concurrent_requests`; `stub/` holds the deterministic upstream MCP server the compose stack runs for it +- `mcp/` - the MCP gateway: server registration via `/v1/mcp/server`, tool listing/calling over the streamable-http protocol under both auth headers, the interactive (authorization_code) OAuth flow driven with the mcp SDK's own OAuth client, and per-server enforcement such as `max_concurrent_requests`; `stub/` holds the deterministic upstream MCP mounts and stub OAuth2 IdP the compose stack runs for it - `logging/` - logging-integration delivery (datadog and friends) - `security/` - secret handling and log-leak protection - `router/` - routing and reliability behavior (fallbacks, cooldowns) diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml index 4a8854660b6a..1233abe83df6 100644 --- a/tests/e2e/coverage_registry/mcp.yaml +++ b/tests/e2e/coverage_registry/mcp.yaml @@ -135,3 +135,19 @@ assertions: [succeeds] source: "server.py:1089" rationale: Smoke; rarely used; same auth model as tools +- id: mcp.list_tools.oauth.completes_authorization_code_flow + module: mcp + tier: P0 + operation: list_tools + auth_family: oauth + assertions: [completes_authorization_code_flow] + source: "auth/user_api_key_auth_mcp.py preemptive 401 challenge + discoverable_endpoints.py gateway AS" + rationale: The interactive per-user flow real MCP hosts run (401 challenge, discovery, DCR, PKCE authorize dance, token exchange); the path desktop-client re-auth incidents live on +- id: mcp.call_tool.oauth.uses_per_user_token + module: mcp + tier: P0 + operation: call_tool + auth_family: oauth + assertions: [uses_per_user_token] + source: "v2 authorization_code egress arm (per-user DB token)" + rationale: Calls on an interactive server must present the user's upstream token, never the caller's virtual key or IdP JWT diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml index 89430c9b7586..1f5f196d75a6 100644 --- a/tests/e2e/docker-compose.yml +++ b/tests/e2e/docker-compose.yml @@ -170,6 +170,8 @@ services: mcp-stub: build: ./mcp/stub + ports: + - "8765:8765" healthcheck: test: ["CMD", "python", "-c", "import socket; socket.create_connection(('localhost', 8765), timeout=2)"] interval: 3s diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.py index 8864efd752fa..85f735c9002e 100644 --- a/tests/e2e/e2e_config.py +++ b/tests/e2e/e2e_config.py @@ -42,6 +42,26 @@ # test runs somewhere the compose stub is not visible from. MCP_STUB_URL = os.environ.get("E2E_MCP_STUB_URL", "http://mcp-stub:8765/mcp") +# The stub's sibling surfaces (see mcp/stub/stub_server.py): a Bearer-guarded +# upstream for the interactive OAuth flow, plus the stub IdP's token endpoint. +# Derived from MCP_STUB_URL so one override relocates the whole stub. +_MCP_STUB_BASE = MCP_STUB_URL.removesuffix("/mcp") +MCP_STUB_OAUTHUSER_URL = f"{_MCP_STUB_BASE}/oauthuser/mcp" +MCP_STUB_TOKEN_URL = f"{_MCP_STUB_BASE}/oauth/token" + +# The stub's authorization endpoint is dereferenced by the browser (pytest +# playing that role from the host), never by the proxy, so unlike the URLs +# above it needs the host-visible address of the stub: the compose file +# publishes mcp-stub on host port 8765 for exactly this hop. +MCP_STUB_AUTHORIZE_BROWSER_URL = os.environ.get( + "E2E_MCP_STUB_AUTHORIZE_BROWSER_URL", "http://localhost:8765/oauth/authorize" +) + +# Deterministic test-only credentials; must mirror mcp/stub/stub_server.py. +MCP_STUB_OAUTH_USER_CLIENT_ID = "e2e-stub-user-client-id" +MCP_STUB_OAUTH_USER_CLIENT_SECRET = "e2e-stub-user-client-secret" +MCP_STUB_OAUTH_USER_ACCESS_TOKEN = "e2e-stub-user-access-token" + # Writes on the proxy are eventually consistent (e.g. spend rows flush on # proxy_batch_write_at, ~60s). Read-backs poll to this deadline, never sleep-once. POLL_TIMEOUT = float(os.environ.get("E2E_POLL_TIMEOUT", "120")) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index a6ac16fb3e9a..6efea3016dc4 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -7,10 +7,10 @@ {PROXY}/{alias}/mcp. Every protocol method takes the request headers as a plain dict, built inside -the test body, so the exact wire format is visible where it is asserted. The -gateway accepts the LiteLLM virtual key as either -`x-litellm-api-key: Bearer sk-...` or `Authorization: Bearer sk-...` (both -Bearer-prefixed on the MCP routes, matching the docs). +the test body, so the exact wire format is visible where it is asserted. The gateway accepts the LiteLLM +virtual key as either `x-litellm-api-key: Bearer sk-...` or +`Authorization: Bearer sk-...` (both Bearer-prefixed on the MCP routes, +matching the docs). """ from __future__ import annotations @@ -19,13 +19,16 @@ import time from dataclasses import dataclass from typing import Mapping, cast +from urllib.parse import parse_qsl, urljoin import httpx import pytest from mcp import ClientSession +from mcp.client.auth import OAuthClientProvider from mcp.client.streamable_http import streamable_http_client +from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken from mcp.types import CallToolResult, TextContent -from pydantic import BaseModel +from pydantic import BaseModel, RootModel from e2e_config import PROXY_BASE_URL, REQUEST_TIMEOUT from e2e_gateway import Gateway, build_gateway @@ -67,6 +70,11 @@ class StubToolStats(BaseModel): completed: int +class StubRecordedHeaders(RootModel[dict[str, str]]): + """JSON the stub's `recorded_headers` tool returns: the (lowercased) header + map of the most recent request its auth guard let through.""" + + def _mcp_url(alias: str) -> str: return f"{PROXY_BASE_URL}/{alias}/mcp" @@ -113,6 +121,137 @@ async def _call_tool(url: str, headers: dict[str, str], tool: str, arguments: To return McpToolText(text=_first_text(result), is_error=bool(result.isError)) +# ---------- interactive (authorization_code) OAuth: the MCP-host side ---------- + +# Where the "browser" lands at the end of the authorize dance. Nothing listens +# here on purpose: the redirect chaser stops as soon as the chain points at this +# URL and reads the code/state off the query string, exactly like a desktop MCP +# host that intercepts its loopback redirect. +OAUTH_CLIENT_REDIRECT_URI = "http://127.0.0.1:53682/e2e/callback" + + +class InMemoryTokenStorage: + """The mcp SDK's TokenStorage protocol, held in memory for one test: the + DCR-registered client and the tokens the gateway minted for it.""" + + def __init__(self) -> None: + self._tokens: OAuthToken | None = None + self._client_info: OAuthClientInformationFull | None = None + + async def get_tokens(self) -> OAuthToken | None: + return self._tokens + + async def set_tokens(self, tokens: OAuthToken) -> None: + self._tokens = tokens + + async def get_client_info(self) -> OAuthClientInformationFull | None: + return self._client_info + + async def set_client_info(self, client_info: OAuthClientInformationFull) -> None: + self._client_info = client_info + + +async def _follow_authorize_redirects(start_url: str) -> tuple[str, str | None]: + """Play the browser's role in the authorize dance: chase the redirect chain + (gateway authorize -> upstream IdP authorize -> gateway callback -> MCP + host redirect_uri) with plain GETs, and return the code/state from the + final hop's query string without dereferencing it.""" + async with httpx.AsyncClient(timeout=httpx.Timeout(REQUEST_TIMEOUT), follow_redirects=False) as browser: + url = start_url + for _ in range(10): + if url.startswith(OAUTH_CLIENT_REDIRECT_URI): + params = dict(parse_qsl(httpx.URL(url).query.decode())) + assert "code" in params, f"authorize chain reached the client redirect_uri without a code: {url}" + return params["code"], params.get("state") + response = await browser.get(url) + assert response.status_code in (302, 303, 307), ( + f"authorize chain broke at {url}: {response.status_code} {response.text[:300]}" + ) + url = urljoin(url, response.headers["location"]) + raise AssertionError(f"authorize chain never reached {OAUTH_CLIENT_REDIRECT_URI}; last url: {url}") + + +def _oauth_provider(url: str, storage: InMemoryTokenStorage) -> OAuthClientProvider: + """The SDK's real OAuth machinery (RFC 9728/8414 discovery, RFC 7591 DCR, + PKCE, token exchange) with the browser leg replaced by the redirect chaser.""" + code_holder: dict[str, str | None] = {} # mutable-ok: hand-off between the two SDK callbacks + + async def redirect_handler(authorize_url: str) -> None: + code, state = await _follow_authorize_redirects(authorize_url) + code_holder["code"] = code + code_holder["state"] = state + + async def callback_handler() -> tuple[str, str | None]: + code = code_holder.get("code") + assert code is not None, "callback_handler ran before the authorize redirect completed" + return code, code_holder.get("state") + + return OAuthClientProvider( + server_url=url, + client_metadata=OAuthClientMetadata.model_validate( + { + "redirect_uris": [OAUTH_CLIENT_REDIRECT_URI], + "token_endpoint_auth_method": "none", + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "client_name": "e2e-mcp-host", + } + ), + storage=storage, + redirect_handler=redirect_handler, + callback_handler=callback_handler, + ) + + +class _HeaderInjectingTransport(httpx.AsyncBaseTransport): + """Adds the caller's LiteLLM key header to every outgoing request, + including the ones the SDK's OAuth machinery builds internally (discovery, + DCR, token exchange). Those bypass httpx client-default headers, but the + gateway resolves which user to store the upstream token for from the key + on the token exchange, exactly like a production MCP host configured with + a LiteLLM key header on the server URL.""" + + def __init__(self, inner: httpx.AsyncBaseTransport, headers: dict[str, str]) -> None: + self._inner = inner + self._headers = headers + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + for name, value in self._headers.items(): + if name not in request.headers: + request.headers[name] = value + return await self._inner.handle_async_request(request) + + +def _oauth_http_client(headers: dict[str, str], auth: OAuthClientProvider) -> httpx.AsyncClient: + return httpx.AsyncClient( + headers=headers, + auth=auth, + timeout=httpx.Timeout(REQUEST_TIMEOUT), + follow_redirects=True, + transport=_HeaderInjectingTransport(httpx.AsyncHTTPTransport(), headers), + ) + + +async def _oauth_list_tool_names(url: str, headers: dict[str, str], storage: InMemoryTokenStorage) -> tuple[str, ...]: + async with _oauth_http_client(headers, _oauth_provider(url, storage)) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + listed = await session.list_tools() + return tuple(sorted(tool.name for tool in listed.tools)) + + +async def _oauth_call_tool( + url: str, headers: dict[str, str], storage: InMemoryTokenStorage, tool: str, arguments: ToolArguments +) -> McpToolText: + async with _oauth_http_client(headers, _oauth_provider(url, storage)) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + result = await session.call_tool(tool, dict(arguments)) + return McpToolText(text=_first_text(result), is_error=bool(result.isError)) + + @dataclass(frozen=True, slots=True) class McpClient: gateway: Gateway @@ -173,10 +312,45 @@ def call_tool(self, alias: str, headers: dict[str, str], tool: str, arguments: T behave like independent clients.""" return asyncio.run(_call_tool(_mcp_url(alias), headers, tool, arguments)) + def poll_oauth_tool_names( + self, alias: str, headers: dict[str, str], storage: InMemoryTokenStorage + ) -> tuple[str, ...]: + """The full interactive flow (discovery, DCR, authorize dance, token + exchange, then tools/list) retried to the shared deadline, since the + just-created server record and key propagate asynchronously. Tokens + land in `storage`, so later calls skip the dance like a real host.""" + deadline = time.monotonic() + self.gateway.poll_timeout + last_error: Exception | None = None + while time.monotonic() < deadline: + try: + return asyncio.run(_oauth_list_tool_names(_mcp_url(alias), headers, storage)) + except Exception as exc: # noqa: BLE001 - retried to the deadline; the last error is surfaced below + last_error = exc + time.sleep(self.gateway.poll_interval) + pytest.fail( + f"interactive OAuth flow for {alias!r} never completed within " + f"{self.gateway.poll_timeout}s; last error: {last_error!r}" + ) + + def oauth_call_tool( + self, alias: str, headers: dict[str, str], storage: InMemoryTokenStorage, tool: str, arguments: ToolArguments + ) -> McpToolText: + """One tools/call authenticated by the tokens in `storage` (minted by a + prior poll_oauth_tool_names dance), over its own fresh MCP session.""" + return asyncio.run(_oauth_call_tool(_mcp_url(alias), headers, storage, tool, arguments)) + def stub_stats(self, alias: str, headers: dict[str, str], stats_tool: str, marker: str) -> StubToolStats: outcome = self.call_tool(alias, headers, stats_tool, {"marker": marker}) return StubToolStats.model_validate_json(outcome.text) + def stub_recorded_headers(self, alias: str, headers: dict[str, str], headers_tool: str) -> dict[str, str]: + """The headers the stub's auth guard recorded for its most recent + authorized request: by construction, the tools/call this method just + made, i.e. exactly what the gateway sent upstream on the caller's behalf.""" + outcome = self.call_tool(alias, headers, headers_tool, {}) + assert outcome.is_error is False, f"recorded_headers call errored: {outcome.text[:300]}" + return StubRecordedHeaders.model_validate_json(outcome.text).root + def build_client() -> McpClient: return McpClient(gateway=build_gateway()) diff --git a/tests/e2e/mcp/stub/stub_server.py b/tests/e2e/mcp/stub/stub_server.py index 89d44a365661..36d1079a4f4d 100644 --- a/tests/e2e/mcp/stub/stub_server.py +++ b/tests/e2e/mcp/stub/stub_server.py @@ -1,27 +1,67 @@ -"""Deterministic MCP upstream for the mcp e2e suite. - -Serves the streamable-http MCP protocol with three tools. `echo` answers -immediately so auth tests can assert an exact round-trip. `slow_echo` holds the -request open for `sleep_seconds` while per-`marker` in-flight and max-in-flight -counters track how many calls the proxy let through simultaneously; that is the -observable a per-server `max_concurrent_requests` cap must bound. `stats` reads -those counters back, so tests observe upstream concurrency through the proxy -itself and the stub needs no side-channel port. - -Counter updates are plain attribute mutations between awaits, so asyncio's -single-threaded scheduling makes them atomic; markers come from +"""Deterministic MCP upstreams for the mcp e2e suite. + +One process, one port, two streamable-http MCP mounts plus a deterministic +OAuth2 IdP, so the compose stack keeps a single `mcp-stub` service: + +- `/mcp` — anonymous. `echo` answers immediately so auth tests can assert an + exact round-trip; `slow_echo` holds the request open for `sleep_seconds` + while per-`marker` in-flight and max-in-flight counters track how many calls + the proxy let through simultaneously (the observable a per-server + `max_concurrent_requests` cap must bound); `stats` reads those counters back, + so tests observe upstream concurrency through the proxy itself and the stub + needs no side-channel port. +- `/oauthuser/mcp` — the interactive (authorization_code) upstream: rejects + anything but `Bearer OAUTH_USER_ACCESS_TOKEN`, which only the + authorization_code grant hands out, so a served request proves the whole + browser dance (authorize redirect, code, PKCE-verified token exchange) ran. +- `/oauth/authorize` — the auto-approving authorization endpoint: validates + client_id/response_type, records the one-time code with its PKCE challenge, + and 302s straight back to the caller's redirect_uri with code and state (the + "user" of this IdP always consents instantly). +- `/oauth/token` — the token endpoint: authorization_code validates the code, + redirect_uri, client credentials, and (when a challenge was recorded) the + S256 code_verifier, then answers with OAUTH_USER_ACCESS_TOKEN + + OAUTH_USER_REFRESH_TOKEN; refresh_token re-issues OAUTH_USER_ACCESS_TOKEN + for the known refresh token. + +The guarded mount records the headers of the most recent authorized request; +its `recorded_headers` tool reads them back through the proxy, so tests can +assert exactly which credentials the gateway attached upstream (and that the +caller's LiteLLM virtual key never left the gateway). + +The credential constants are mirrored in tests/e2e/e2e_config.py; keep the two +in sync. Counter updates are plain attribute mutations between awaits, so +asyncio's single-threaded scheduling makes them atomic; markers come from `unique_marker()` so concurrent test runs never share a counter. """ from __future__ import annotations import asyncio +import base64 +import contextlib +import hashlib import json +import uuid +from collections.abc import AsyncGenerator from dataclasses import dataclass +import uvicorn from mcp.server.fastmcp import FastMCP +from starlette.applications import Starlette +from starlette.datastructures import FormData, Headers +from starlette.requests import Request +from starlette.responses import JSONResponse, RedirectResponse, Response +from starlette.routing import Mount, Route +from starlette.types import ASGIApp, Receive, Scope, Send + +OAUTH_USER_CLIENT_ID = "e2e-stub-user-client-id" +OAUTH_USER_CLIENT_SECRET = "e2e-stub-user-client-secret" +OAUTH_USER_ACCESS_TOKEN = "e2e-stub-user-access-token" +OAUTH_USER_REFRESH_TOKEN = "e2e-stub-user-refresh-token" -mcp = FastMCP("e2e-stub", host="0.0.0.0", port=8765, stateless_http=True) +main_mcp = FastMCP("e2e-stub", host="0.0.0.0", port=8765, stateless_http=True) +oauthuser_mcp = FastMCP("e2e-stub-oauthuser", host="0.0.0.0", port=8765, stateless_http=True) @dataclass @@ -33,14 +73,16 @@ class _MarkerStats: _stats: dict[str, _MarkerStats] = {} +_last_authorized_headers: dict[str, dict[str, str]] = {} -@mcp.tool() + +@main_mcp.tool() def echo(text: str) -> str: """Return `text` unchanged.""" return text -@mcp.tool() +@main_mcp.tool() async def slow_echo(text: str, marker: str, sleep_seconds: float) -> str: """Return `text` after `sleep_seconds`, recording concurrency under `marker`.""" stats = _stats.setdefault(marker, _MarkerStats()) @@ -54,7 +96,7 @@ async def slow_echo(text: str, marker: str, sleep_seconds: float) -> str: return text -@mcp.tool() +@main_mcp.tool() def stats(marker: str) -> str: """Return the JSON stats recorded for `marker`.""" recorded = _stats.get(marker, _MarkerStats()) @@ -67,5 +109,149 @@ def stats(marker: str) -> str: ) +def _register_guarded_tools(server: FastMCP, mount: str) -> None: + def echo(text: str) -> str: + """Return `text` unchanged.""" + return text + + def recorded_headers() -> str: + """Return the headers of the most recent authorized request as JSON.""" + return json.dumps(_last_authorized_headers.get(mount, {})) + + _ = server.tool()(echo) + _ = server.tool()(recorded_headers) + + +_register_guarded_tools(oauthuser_mcp, "oauthuser") + + +def _require_header(app: ASGIApp, *, mount: str, header: str, expected: str) -> ASGIApp: + """Serve `app` only to requests carrying `header: expected`; 401 otherwise. + Authorized requests have their full header map recorded under `mount`.""" + + async def guard(scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await app(scope, receive, send) + return + headers = Headers(scope=scope) + if headers.get(header) != expected: + response = JSONResponse({"error": "unauthorized", "detail": f"missing or wrong {header}"}, status_code=401) + await response(scope, receive, send) + return + _last_authorized_headers[mount] = dict(headers.items()) + await app(scope, receive, send) + + return guard + + +_issued_codes: dict[str, dict[str, str]] = {} + + +async def oauth_authorize(request: Request) -> Response: + """The auto-approving authorization endpoint: the resource owner of this + IdP consents instantly, so a headless test can drive the browser leg of + the authorization_code flow with plain HTTP redirects.""" + params = request.query_params + redirect_uri = params.get("redirect_uri", "") + valid = params.get("response_type") == "code" and params.get("client_id") == OAUTH_USER_CLIENT_ID and redirect_uri + if not valid: + return JSONResponse( + {"error": "invalid_request", "detail": "need response_type=code, the user client_id, and a redirect_uri"}, + status_code=400, + ) + code = f"e2e-stub-code-{uuid.uuid4().hex}" + _issued_codes[code] = { + "redirect_uri": redirect_uri, + "code_challenge": params.get("code_challenge", ""), + } + state = params.get("state", "") + separator = "&" if "?" in redirect_uri else "?" + location = f"{redirect_uri}{separator}code={code}" + (f"&state={state}" if state else "") + return RedirectResponse(location, status_code=302) + + +def _s256(code_verifier: str) -> str: + return base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b"=").decode() + + +def _authorization_code_grant(form: FormData) -> JSONResponse: + code_value = form.get("code") + record = _issued_codes.pop(code_value, None) if isinstance(code_value, str) else None + granted = ( + record is not None + and form.get("client_id") == OAUTH_USER_CLIENT_ID + and form.get("client_secret") == OAUTH_USER_CLIENT_SECRET + and form.get("redirect_uri") == record["redirect_uri"] + ) + if not granted: + return JSONResponse({"error": "invalid_grant"}, status_code=400) + assert record is not None + if record["code_challenge"]: + verifier = form.get("code_verifier") + if not isinstance(verifier, str) or _s256(verifier) != record["code_challenge"]: + return JSONResponse({"error": "invalid_grant", "detail": "PKCE verification failed"}, status_code=400) + return JSONResponse( + { + "access_token": OAUTH_USER_ACCESS_TOKEN, + "token_type": "Bearer", + "expires_in": 3600, + "refresh_token": OAUTH_USER_REFRESH_TOKEN, + } + ) + + +def _refresh_token_grant(form: FormData) -> JSONResponse: + granted = ( + form.get("refresh_token") == OAUTH_USER_REFRESH_TOKEN + and form.get("client_id") == OAUTH_USER_CLIENT_ID + and form.get("client_secret") == OAUTH_USER_CLIENT_SECRET + ) + if not granted: + return JSONResponse({"error": "invalid_grant"}, status_code=400) + return JSONResponse({"access_token": OAUTH_USER_ACCESS_TOKEN, "token_type": "Bearer", "expires_in": 3600}) + + +async def oauth_token(request: Request) -> JSONResponse: + """The token endpoint for all three grants. Every form field is matched + exactly so a failure points at the precise field the proxy sent wrong.""" + form = await request.form() + grant_type = form.get("grant_type") + if grant_type == "authorization_code": + return _authorization_code_grant(form) + if grant_type == "refresh_token": + return _refresh_token_grant(form) + return JSONResponse({"error": "unsupported_grant_type"}, status_code=400) + + +def build_app() -> Starlette: + servers = (main_mcp, oauthuser_mcp) + apps = {server.name: server.streamable_http_app() for server in servers} + + @contextlib.asynccontextmanager + async def lifespan(_: Starlette) -> AsyncGenerator[None]: + async with contextlib.AsyncExitStack() as stack: + for server in servers: + await stack.enter_async_context(server.session_manager.run()) + yield + + return Starlette( + routes=[ + Route("/oauth/token", oauth_token, methods=["POST"]), + Route("/oauth/authorize", oauth_authorize, methods=["GET"]), + Mount( + "/oauthuser", + app=_require_header( + apps["e2e-stub-oauthuser"], + mount="oauthuser", + header="authorization", + expected=f"Bearer {OAUTH_USER_ACCESS_TOKEN}", + ), + ), + Mount("/", app=apps["e2e-stub"]), + ], + lifespan=lifespan, + ) + + if __name__ == "__main__": - mcp.run(transport="streamable-http") + uvicorn.run(build_app(), host="0.0.0.0", port=8765) diff --git a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py new file mode 100644 index 000000000000..92ce7a8b0370 --- /dev/null +++ b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py @@ -0,0 +1,117 @@ +"""Live e2e: the interactive (authorization_code) OAuth MCP flow. + +Covers mcp.list_tools.oauth.completes_authorization_code_flow and +mcp.call_tool.oauth.uses_per_user_token: a gateway-managed oauth2 server in +the authorization_code flow must challenge an unauthorized MCP session with +401 + WWW-Authenticate, let a real MCP host complete the whole interactive +dance (RFC 9728/8414 discovery against the gateway, RFC 7591 dynamic client +registration, the authorize redirect through the upstream IdP, the +PKCE-verified token exchange), and then serve tools/list and tools/call using +the per-user upstream token the gateway obtained; the caller's virtual key +must never leave the gateway. + +The MCP-host side is the official mcp SDK's own OAuth machinery +(OAuthClientProvider), the same code path desktop MCP hosts run; only the +browser leg is replaced by a redirect chaser that follows the authorize chain +(gateway -> stub IdP -> gateway callback -> host redirect_uri) with plain +GETs. The upstream is the /oauthuser stub mount, which 401s anything but the +exact access token the stub IdP's authorization_code grant hands out, so a +served call proves the gateway completed the code exchange (the stub verifies +client credentials, redirect_uri, one-time code, and the S256 code_verifier) +rather than forwarding anything it already had. The recorded_headers +read-back then makes the injected token explicit and adds the leak check. +""" + +from __future__ import annotations + +import pytest + +from e2e_config import ( + MCP_STUB_AUTHORIZE_BROWSER_URL, + MCP_STUB_OAUTH_USER_ACCESS_TOKEN, + MCP_STUB_OAUTH_USER_CLIENT_ID, + MCP_STUB_OAUTH_USER_CLIENT_SECRET, + MCP_STUB_OAUTHUSER_URL, + MCP_STUB_TOKEN_URL, + MCP_STUB_URL, + unique_marker, +) +from lifecycle import ResourceManager +from mcp_client import InMemoryTokenStorage, McpClient, McpDenied, StubRecordedHeaders +from models import KeyGenerateBody, McpServerCreateBody, McpServerCredentials + +pytestmark = pytest.mark.e2e + +GUARDED_STUB_TOOLS = ("echo", "recorded_headers") + + +class TestMcpOauthAuthorizationCode: + """An authorization_code server challenges unauthenticated sessions, runs + the full interactive dance with a real MCP host, and serves tools with the + per-user token the gateway obtained from the IdP.""" + + @pytest.mark.covers("mcp.list_tools.oauth.completes_authorization_code_flow") + @pytest.mark.covers("mcp.call_tool.oauth.uses_per_user_token") + def test_challenge_then_authorization_code_dance_reaches_tools( + self, client: McpClient, resources: ResourceManager + ) -> None: + marker = unique_marker() + alias = f"e2emcpauthcode{marker}" + created = client.create_server( + McpServerCreateBody( + alias=alias, + url=MCP_STUB_OAUTHUSER_URL, + allow_all_keys=True, + auth_type="oauth2", + oauth2_flow="authorization_code", + authorization_url=MCP_STUB_AUTHORIZE_BROWSER_URL, + token_url=MCP_STUB_TOKEN_URL, + credentials=McpServerCredentials( + client_id=MCP_STUB_OAUTH_USER_CLIENT_ID, + client_secret=MCP_STUB_OAUTH_USER_CLIENT_SECRET, + ), + ) + ) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.auth_type == "oauth2" + assert stored.oauth2_flow == "authorization_code" + assert stored.authorization_url == MCP_STUB_AUTHORIZE_BROWSER_URL + assert stored.token_url == MCP_STUB_TOKEN_URL + assert stored.credentials is None, f"client secret must be redacted on read-back, got {stored.credentials}" + + key = client.gateway.generate_key(KeyGenerateBody(user_id="e2e-test-user")) + resources.defer(lambda: client.gateway.delete_key(key)) + headers = {"x-litellm-api-key": f"Bearer {key}"} + + control_alias = f"e2emcpauthcodectl{marker}" + control = client.create_server( + McpServerCreateBody(alias=control_alias, url=MCP_STUB_URL, allow_all_keys=True) + ) + resources.defer(lambda: client.delete_server(control.server_id)) + _ = client.poll_tool_names(control_alias, headers) + + challenged = client.list_tools_once(alias, headers) + assert isinstance(challenged, McpDenied), f"session without a user token was served tools: {challenged}" + assert challenged.status_code == 401, f"expected the 401 OAuth challenge, got {challenged}" + + storage = InMemoryTokenStorage() + names = client.poll_oauth_tool_names(alias, headers, storage) + expected = tuple(sorted(f"{alias}-{tool}" for tool in GUARDED_STUB_TOOLS)) + assert names == expected, f"post-dance listing was {names}, expected exactly {expected}" + + payload = f"e2e-{marker}" + result = client.oauth_call_tool(alias, headers, storage, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo through the user-token upstream errored: {result.text[:300]}" + assert result.text == payload + + recorded = client.oauth_call_tool(alias, headers, storage, f"{alias}-recorded_headers", {}) + assert recorded.is_error is False, f"recorded_headers call errored: {recorded.text[:300]}" + upstream_headers = StubRecordedHeaders.model_validate_json(recorded.text).root + assert upstream_headers.get("authorization") == f"Bearer {MCP_STUB_OAUTH_USER_ACCESS_TOKEN}", ( + "upstream must receive exactly the per-user token the stub IdP hands out for the code exchange, " + f"got {upstream_headers.get('authorization')!r}" + ) + leaked = sorted(name for name, value in upstream_headers.items() if key in value) + assert leaked == [], f"caller's virtual key crossed the gateway boundary in header(s) {leaked}" diff --git a/tests/e2e/models.py b/tests/e2e/models.py index 4a0981c4d6db..f54674515f18 100644 --- a/tests/e2e/models.py +++ b/tests/e2e/models.py @@ -98,6 +98,18 @@ class KeyInfoResponse(BaseModel): # ---------- mcp servers ---------- +class McpServerCredentials(BaseModel): + """The `credentials` blob on /v1/mcp/server: `auth_value` is the static + secret for the shared-key auth types (api_key, bearer_token, ...); + `client_id`/`client_secret`/`scopes` drive the OAuth2 client_credentials + exchange. Stored encrypted and redacted (nulled) in every read-back.""" + + auth_value: str | None = None + client_id: str | None = None + client_secret: str | None = None + scopes: list[str] | None = None + + class McpServerCreateBody(BaseModel): """POST /v1/mcp/server. `allow_all_keys` opts the server out of per-key object_permission grants so any virtual key on the proxy may use it.""" @@ -107,6 +119,11 @@ class McpServerCreateBody(BaseModel): transport: str = "http" allow_all_keys: bool = True max_concurrent_requests: int | None = None + auth_type: str | None = None + credentials: McpServerCredentials | None = None + authorization_url: str | None = None + token_url: str | None = None + oauth2_flow: Literal["client_credentials", "authorization_code"] | None = None class McpServerInfo(BaseModel): @@ -118,6 +135,11 @@ class McpServerInfo(BaseModel): transport: str | None = None allow_all_keys: bool | None = None max_concurrent_requests: int | None = None + auth_type: str | None = None + credentials: McpServerCredentials | None = None + authorization_url: str | None = None + token_url: str | None = None + oauth2_flow: str | None = None # ---------- customers ---------- From c1e5ca785be1df5a0a1a3a00b9ef2b6ba577cfe9 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Wed, 15 Jul 2026 12:57:33 -0700 Subject: [PATCH 10/17] test(e2e): run the official MCP conformance suite through the gateway and cover prompt/resource primitives --- tests/e2e/coverage_registry/mcp.yaml | 8 ++ tests/e2e/e2e_config.py | 1 + tests/e2e/mcp/auth_forwarder.py | 88 +++++++++++++ tests/e2e/mcp/mcp_client.py | 70 ++++++++++ tests/e2e/mcp/stub/stub_server.py | 57 ++++++++- tests/e2e/mcp/test_mcp_conformance_e2e.py | 121 ++++++++++++++++++ .../e2e/mcp/test_mcp_prompts_resources_e2e.py | 99 ++++++++++++++ 7 files changed, 442 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/mcp/auth_forwarder.py create mode 100644 tests/e2e/mcp/test_mcp_conformance_e2e.py create mode 100644 tests/e2e/mcp/test_mcp_prompts_resources_e2e.py diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml index 1233abe83df6..c2c2f59e76a1 100644 --- a/tests/e2e/coverage_registry/mcp.yaml +++ b/tests/e2e/coverage_registry/mcp.yaml @@ -151,3 +151,11 @@ assertions: [uses_per_user_token] source: "v2 authorization_code egress arm (per-user DB token)" rationale: Calls on an interactive server must present the user's upstream token, never the caller's virtual key or IdP JWT +- id: mcp.protocol.api_key.passes_official_conformance + module: mcp + tier: P0 + operation: protocol + auth_family: api_key + assertions: [passes_official_conformance] + source: "@modelcontextprotocol/conformance server scenarios via tests/e2e/mcp/test_mcp_conformance_e2e.py" + rationale: The gateway re-serves the MCP protocol to hosts, so it must stay spec-conformant as a server; the official suite catches lifecycle/error-shape regressions our behavior tests do not encode diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.py index 85f735c9002e..a5d682807d4a 100644 --- a/tests/e2e/e2e_config.py +++ b/tests/e2e/e2e_config.py @@ -46,6 +46,7 @@ # upstream for the interactive OAuth flow, plus the stub IdP's token endpoint. # Derived from MCP_STUB_URL so one override relocates the whole stub. _MCP_STUB_BASE = MCP_STUB_URL.removesuffix("/mcp") +MCP_STUB_CONFORMANCE_URL = f"{_MCP_STUB_BASE}/conformance/mcp" MCP_STUB_OAUTHUSER_URL = f"{_MCP_STUB_BASE}/oauthuser/mcp" MCP_STUB_TOKEN_URL = f"{_MCP_STUB_BASE}/oauth/token" diff --git a/tests/e2e/mcp/auth_forwarder.py b/tests/e2e/mcp/auth_forwarder.py new file mode 100644 index 000000000000..951da72ec8c0 --- /dev/null +++ b/tests/e2e/mcp/auth_forwarder.py @@ -0,0 +1,88 @@ +"""In-process reverse proxy that stamps the LiteLLM key onto every request. + +The official conformance suite's client offers no way to send custom headers, +but the gateway's MCP routes require the virtual key. This forwarder plays the +role of an MCP host's HTTP layer configured with the key header: it listens on +a loopback port, injects `x-litellm-api-key: Bearer `, and relays +everything (including SSE streams, unbuffered) to the proxy under test. + +Runs inside the pytest process on a background uvicorn thread; tests get the +local base URL from `serve()` and hand `{base}/{alias}/mcp` to the conformance +CLI as the server under test. +""" + +from __future__ import annotations + +import socket +import threading +import time +from collections.abc import Generator +from contextlib import contextmanager +from typing import cast + +import httpx +import uvicorn +from starlette.applications import Starlette +from starlette.background import BackgroundTask +from starlette.requests import Request +from starlette.responses import StreamingResponse +from starlette.routing import Route + +from e2e_config import PROXY_BASE_URL, REQUEST_TIMEOUT + +_HOP_BY_HOP_REQUEST_HEADERS = frozenset({"host", "content-length"}) +_HOP_BY_HOP_RESPONSE_HEADERS = frozenset({"content-length", "transfer-encoding", "content-encoding"}) + + +def _build_app(upstream: httpx.AsyncClient, litellm_key: str) -> Starlette: + async def forward(request: Request) -> StreamingResponse: + url = httpx.URL(path=request.url.path, query=request.url.query.encode()) + headers = { + name: value + for name, value in request.headers.items() + if name.lower() not in _HOP_BY_HOP_REQUEST_HEADERS + } + headers["x-litellm-api-key"] = f"Bearer {litellm_key}" + proxied = upstream.build_request(request.method, url, headers=headers, content=await request.body()) + response = await upstream.send(proxied, stream=True) + response_headers = { + name: value + for name, value in response.headers.items() + if name.lower() not in _HOP_BY_HOP_RESPONSE_HEADERS + } + return StreamingResponse( + response.aiter_raw(), + status_code=response.status_code, + headers=response_headers, + background=BackgroundTask(response.aclose), + ) + + methods = ["GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS"] + return Starlette(routes=[Route("/{path:path}", forward, methods=methods)]) + + +def _free_loopback_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return cast("int", sock.getsockname()[1]) + + +@contextmanager +def serve(litellm_key: str) -> Generator[str]: + """Serve the forwarder for the block's duration; yields its base URL.""" + upstream = httpx.AsyncClient(base_url=PROXY_BASE_URL, timeout=httpx.Timeout(REQUEST_TIMEOUT)) + port = _free_loopback_port() + server = uvicorn.Server( + uvicorn.Config(_build_app(upstream, litellm_key), host="127.0.0.1", port=port, log_level="warning") + ) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + deadline = time.monotonic() + 15 + while not server.started: + assert time.monotonic() < deadline, "auth forwarder never started" + time.sleep(0.05) + try: + yield f"http://127.0.0.1:{port}" + finally: + server.should_exit = True + thread.join(timeout=10) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index 6efea3016dc4..29bf8819d8b6 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -121,6 +121,60 @@ async def _call_tool(url: str, headers: dict[str, str], tool: str, arguments: To return McpToolText(text=_first_text(result), is_error=bool(result.isError)) +async def _list_prompts(url: str, headers: dict[str, str]) -> tuple[tuple[str, tuple[str, ...]], ...]: + """(name, argument names) per prompt, sorted by name.""" + async with _http_client(headers) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + listed = await session.list_prompts() + return tuple( + sorted( + (prompt.name, tuple(arg.name for arg in (prompt.arguments or []))) + for prompt in listed.prompts + ) + ) + + +async def _get_prompt(url: str, headers: dict[str, str], name: str, arguments: dict[str, str]) -> str: + """The text of the rendered prompt's first message.""" + async with _http_client(headers) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + result = await session.get_prompt(name, arguments) + first = result.messages[0].content if result.messages else None + if isinstance(first, TextContent): + return first.text + return f"" + + +async def _list_resources(url: str, headers: dict[str, str]) -> tuple[tuple[str, str], ...]: + """(uri, name) per resource, sorted by uri.""" + async with _http_client(headers) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + listed = await session.list_resources() + return tuple(sorted((str(resource.uri), resource.name) for resource in listed.resources)) + + +async def _read_resource(url: str, headers: dict[str, str], uri: str) -> str: + """The text of the resource's first content block.""" + from pydantic import AnyUrl + + async with _http_client(headers) as http_client: + async with streamable_http_client(url, http_client=http_client) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + result = await session.read_resource(AnyUrl(uri)) + first = result.contents[0] if result.contents else None + text = getattr(first, "text", None) + if isinstance(text, str): + return text + return f"" + + # ---------- interactive (authorization_code) OAuth: the MCP-host side ---------- # Where the "browser" lands at the end of the authorize dance. Nothing listens @@ -339,6 +393,22 @@ def oauth_call_tool( prior poll_oauth_tool_names dance), over its own fresh MCP session.""" return asyncio.run(_oauth_call_tool(_mcp_url(alias), headers, storage, tool, arguments)) + def list_prompts(self, alias: str, headers: dict[str, str]) -> tuple[tuple[str, tuple[str, ...]], ...]: + """prompts/list over its own fresh MCP session: (name, argument names) sorted by name.""" + return asyncio.run(_list_prompts(_mcp_url(alias), headers)) + + def get_prompt(self, alias: str, headers: dict[str, str], name: str, arguments: dict[str, str]) -> str: + """prompts/get over its own fresh MCP session: the rendered first message's text.""" + return asyncio.run(_get_prompt(_mcp_url(alias), headers, name, arguments)) + + def list_resources(self, alias: str, headers: dict[str, str]) -> tuple[tuple[str, str], ...]: + """resources/list over its own fresh MCP session: (uri, name) sorted by uri.""" + return asyncio.run(_list_resources(_mcp_url(alias), headers)) + + def read_resource(self, alias: str, headers: dict[str, str], uri: str) -> str: + """resources/read over its own fresh MCP session: the first content block's text.""" + return asyncio.run(_read_resource(_mcp_url(alias), headers, uri)) + def stub_stats(self, alias: str, headers: dict[str, str], stats_tool: str, marker: str) -> StubToolStats: outcome = self.call_tool(alias, headers, stats_tool, {"marker": marker}) return StubToolStats.model_validate_json(outcome.text) diff --git a/tests/e2e/mcp/stub/stub_server.py b/tests/e2e/mcp/stub/stub_server.py index 36d1079a4f4d..8879fdf7edf3 100644 --- a/tests/e2e/mcp/stub/stub_server.py +++ b/tests/e2e/mcp/stub/stub_server.py @@ -1,6 +1,6 @@ """Deterministic MCP upstreams for the mcp e2e suite. -One process, one port, two streamable-http MCP mounts plus a deterministic +One process, one port, three streamable-http MCP mounts plus a deterministic OAuth2 IdP, so the compose stack keeps a single `mcp-stub` service: - `/mcp` — anonymous. `echo` answers immediately so auth tests can assert an @@ -10,6 +10,13 @@ `max_concurrent_requests` cap must bound); `stats` reads those counters back, so tests observe upstream concurrency through the proxy itself and the stub needs no side-channel port. +- `/conformance/mcp` — anonymous, serving the official + @modelcontextprotocol/conformance suite's hardcoded fixture contract + (test_simple_text / test_error_handling tools, test://static-text, + test://static-binary and the test://template/{id}/data resources, + test_simple_prompt / test_prompt_with_arguments prompts), so the gateway can + be conformance-tested end to end and the suite's own prompt/resource tests + have a deterministic upstream that serves all three MCP primitives. - `/oauthuser/mcp` — the interactive (authorization_code) upstream: rejects anything but `Bearer OAUTH_USER_ACCESS_TOKEN`, which only the authorization_code grant hands out, so a served request proves the whole @@ -61,6 +68,7 @@ OAUTH_USER_REFRESH_TOKEN = "e2e-stub-user-refresh-token" main_mcp = FastMCP("e2e-stub", host="0.0.0.0", port=8765, stateless_http=True) +conformance_mcp = FastMCP("e2e-stub-conformance", host="0.0.0.0", port=8765, stateless_http=True) oauthuser_mcp = FastMCP("e2e-stub-oauthuser", host="0.0.0.0", port=8765, stateless_http=True) @@ -109,6 +117,50 @@ def stats(marker: str) -> str: ) +@conformance_mcp.tool() +def test_simple_text() -> str: + """Return a plain text result (the conformance suite's simple-text fixture).""" + return "Hello from the e2e conformance stub" + + +@conformance_mcp.tool() +def test_error_handling(should_error: bool = True) -> str: + """Raise so the result carries isError (the conformance suite's error fixture).""" + if should_error: + raise ValueError("Intentional error from the e2e conformance stub") + return "no error" + + +@conformance_mcp.resource("test://static-text") +def static_text_resource() -> str: + """The conformance suite's static text resource fixture.""" + return "Static text resource from the e2e conformance stub" + + +@conformance_mcp.resource("test://static-binary") +def static_binary_resource() -> bytes: + """The conformance suite's static binary resource fixture.""" + return b"\x89binary-fixture-bytes\x00\x01" + + +@conformance_mcp.resource("test://template/{id}/data") +def template_resource(id: str) -> str: + """The conformance suite's resource template fixture: {id} must substitute.""" + return f"Template resource data for id={id}" + + +@conformance_mcp.prompt() +def test_simple_prompt() -> str: + """The conformance suite's no-argument prompt fixture.""" + return "This is a simple prompt from the e2e conformance stub" + + +@conformance_mcp.prompt() +def test_prompt_with_arguments(arg1: str, arg2: str) -> str: + """The conformance suite's argument-substitution prompt fixture.""" + return f"Prompt rendered with arg1={arg1} and arg2={arg2}" + + def _register_guarded_tools(server: FastMCP, mount: str) -> None: def echo(text: str) -> str: """Return `text` unchanged.""" @@ -224,7 +276,7 @@ async def oauth_token(request: Request) -> JSONResponse: def build_app() -> Starlette: - servers = (main_mcp, oauthuser_mcp) + servers = (main_mcp, conformance_mcp, oauthuser_mcp) apps = {server.name: server.streamable_http_app() for server in servers} @contextlib.asynccontextmanager @@ -247,6 +299,7 @@ async def lifespan(_: Starlette) -> AsyncGenerator[None]: expected=f"Bearer {OAUTH_USER_ACCESS_TOKEN}", ), ), + Mount("/conformance", app=apps["e2e-stub-conformance"]), Mount("/", app=apps["e2e-stub"]), ], lifespan=lifespan, diff --git a/tests/e2e/mcp/test_mcp_conformance_e2e.py b/tests/e2e/mcp/test_mcp_conformance_e2e.py new file mode 100644 index 000000000000..28a4c795a115 --- /dev/null +++ b/tests/e2e/mcp/test_mcp_conformance_e2e.py @@ -0,0 +1,121 @@ +"""Live e2e: the official MCP conformance suite, run through the gateway. + +Covers mcp.protocol.api_key.passes_official_conformance: the gateway is a +protocol middlebox, so beyond this suite's behavior tests it must stay +conformant to the MCP spec as re-served to hosts. This test drives the +official @modelcontextprotocol/conformance server scenarios (the same suite +the SDKs gate their CI on) against a gateway-registered server backed by the +stub's /conformance mount, which implements the suite's hardcoded fixture +contract (test_simple_text, test://static-text, test_simple_prompt, ...). + +The conformance CLI cannot send custom headers, so the run goes through +auth_forwarder.serve(), an in-process reverse proxy that stamps the virtual +key onto every request the way a configured MCP host's HTTP layer would; the +gateway path itself stays fully authenticated and unmodified. + +EXPECTED_GAPS is the checked-in baseline, exact in both directions: a +scenario failing that is not listed fails this test (a regression), and a +listed scenario that starts passing also fails it (so the baseline ratchets +down instead of going stale). The current entries are real gateway findings, +verified by hand: logging/setLevel and completion/complete are not relayed +(-32601), prompts/get resolves alias-prefixed names only (the unprefixed +fallback that tools/call has is missing, so the suite's hardcoded prompt +names 403), and binary resource read-through drops the base64 blob field +(the stub serves it; the gateway's answer has no blob). + +Scenarios needing client capabilities the gateway does not advertise for its +callers (sampling, elicitation) and SSE-timing scenarios are intentionally +not run; the curated list below is the subset a gateway can honestly own. +""" + +from __future__ import annotations + +import shutil +import subprocess +from collections.abc import Iterator +from pathlib import Path + +import pytest + +import auth_forwarder +from e2e_config import MCP_STUB_CONFORMANCE_URL, unique_marker +from mcp_client import McpClient +from models import KeyGenerateBody, McpServerCreateBody + +pytestmark = pytest.mark.e2e + +CONFORMANCE_PACKAGE = "@modelcontextprotocol/conformance@0.1.11" + +SCENARIOS = ( + "server-initialize", + "ping", + "logging-set-level", + "completion-complete", + "tools-list", + "tools-call-simple-text", + "tools-call-error", + "resources-list", + "resources-read-text", + "resources-read-binary", + "resources-templates-read", + "prompts-list", + "prompts-get-simple", + "prompts-get-with-args", +) + +EXPECTED_GAPS = { + "logging-set-level": "gateway answers logging/setLevel with -32601 Method not found instead of relaying it", + "completion-complete": "gateway answers completion/complete with -32601 Method not found instead of relaying it", + "prompts-get-simple": "prompts/get lacks the unprefixed-name fallback tools/call has; unprefixed names 403", + "prompts-get-with-args": "prompts/get lacks the unprefixed-name fallback tools/call has; unprefixed names 403", + "resources-read-binary": "gateway drops the base64 blob field on binary resource read-through", +} + + +@pytest.fixture(scope="module") +def conformance_target(client: McpClient) -> Iterator[str]: + """A conformance-fixture server registered on the gateway, fronted by the + key-stamping forwarder; yields the URL the conformance CLI tests. Module + scoped so all scenarios share one server, one key, and one forwarder.""" + if shutil.which("npx") is None: + pytest.skip("npx not available; the official conformance suite runs on Node") + alias = f"e2emcpconf{unique_marker()}" + created = client.create_server( + McpServerCreateBody(alias=alias, url=MCP_STUB_CONFORMANCE_URL, allow_all_keys=True) + ) + key = client.gateway.generate_key(KeyGenerateBody()) + try: + _ = client.poll_tool_names(alias, {"x-litellm-api-key": f"Bearer {key}"}) + with auth_forwarder.serve(key) as forwarder_base: + yield f"{forwarder_base}/{alias}/mcp" + finally: + client.delete_server(created.server_id) + client.gateway.delete_key(key) + + +class TestMcpOfficialConformance: + """Each curated official scenario passes through the gateway, except the + exact set of known gaps pinned in EXPECTED_GAPS.""" + + @pytest.mark.covers("mcp.protocol.api_key.passes_official_conformance") + @pytest.mark.parametrize("scenario", SCENARIOS) + def test_official_scenario(self, scenario: str, conformance_target: str, tmp_path: Path) -> None: + run = subprocess.run( + ["npx", "-y", CONFORMANCE_PACKAGE, "server", "--url", conformance_target, "--scenario", scenario], + capture_output=True, + text=True, + timeout=300, + cwd=tmp_path, + ) + failed = run.returncode != 0 + expected_reason = EXPECTED_GAPS.get(scenario) + if expected_reason is not None: + assert failed, ( + f"conformance scenario {scenario!r} now PASSES; the gateway gap " + f"({expected_reason}) appears fixed, so remove it from EXPECTED_GAPS to ratchet the baseline" + ) + return + assert not failed, ( + f"conformance scenario {scenario!r} failed through the gateway (exit {run.returncode}); " + f"output tail:\n{run.stdout[-1500:]}" + ) diff --git a/tests/e2e/mcp/test_mcp_prompts_resources_e2e.py b/tests/e2e/mcp/test_mcp_prompts_resources_e2e.py new file mode 100644 index 000000000000..26b7c5201932 --- /dev/null +++ b/tests/e2e/mcp/test_mcp_prompts_resources_e2e.py @@ -0,0 +1,99 @@ +"""Live e2e: the MCP gateway's prompt and resource primitives. + +Covers mcp.list_prompts.api_key.succeeds, mcp.get_prompt.api_key.succeeds, +mcp.list_resources.api_key.succeeds, and mcp.read_resource.api_key.succeeds, +against the stub's /conformance mount (tests/e2e/mcp/stub/), the one upstream +that serves all three MCP primitives. + +The gateway's namespacing contract differs per primitive, and the assertions +pin it exactly as observed live: prompt names are alias-prefixed like tool +names (and must be fetched by the prefixed name), while resource URIs pass +through unprefixed (only the resource's display name gains the prefix). The +prompt-rendering assertion feeds unique per-run argument values through +prompts/get and requires them back verbatim in the rendered text, so a cached +or canned response cannot pass; the resource assertion requires the exact +fixture body. + +The binary-resource read (test://static-binary) is deliberately NOT asserted +here: the gateway currently drops the base64 blob field on read-through +(verified against the stub directly, which serves it), and that gap is pinned +in the conformance suite baseline (test_mcp_conformance_e2e.py) instead. +""" + +from __future__ import annotations + +import pytest + +from e2e_config import MCP_STUB_CONFORMANCE_URL, unique_marker +from lifecycle import ResourceManager +from mcp_client import McpClient +from models import KeyGenerateBody, McpServerCreateBody + +pytestmark = pytest.mark.e2e + + +class TestMcpPromptsAndResources: + """A registered server's prompts and resources are listed, fetched, and + read through the gateway with the same lifecycle contract as tools.""" + + @pytest.mark.covers("mcp.list_prompts.api_key.succeeds") + @pytest.mark.covers("mcp.get_prompt.api_key.succeeds") + def test_prompts_list_and_render_with_arguments( + self, client: McpClient, resources: ResourceManager + ) -> None: + alias = f"e2emcpprompts{unique_marker()}" + created = client.create_server( + McpServerCreateBody(alias=alias, url=MCP_STUB_CONFORMANCE_URL, allow_all_keys=True) + ) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_CONFORMANCE_URL + + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + headers = {"x-litellm-api-key": f"Bearer {key}"} + _ = client.poll_tool_names(alias, headers) + + listed = client.list_prompts(alias, headers) + expected = ( + (f"{alias}-test_prompt_with_arguments", ("arg1", "arg2")), + (f"{alias}-test_simple_prompt", ()), + ) + assert listed == expected, f"gateway listed prompts {listed}, expected exactly {expected}" + + first_value = f"e2e-{unique_marker()}" + second_value = f"e2e-{unique_marker()}" + rendered = client.get_prompt( + alias, headers, f"{alias}-test_prompt_with_arguments", {"arg1": first_value, "arg2": second_value} + ) + assert rendered == f"Prompt rendered with arg1={first_value} and arg2={second_value}" + + @pytest.mark.covers("mcp.list_resources.api_key.succeeds") + @pytest.mark.covers("mcp.read_resource.api_key.succeeds") + def test_resources_list_and_read_text(self, client: McpClient, resources: ResourceManager) -> None: + alias = f"e2emcpresources{unique_marker()}" + created = client.create_server( + McpServerCreateBody(alias=alias, url=MCP_STUB_CONFORMANCE_URL, allow_all_keys=True) + ) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_CONFORMANCE_URL + + key = client.gateway.generate_key(KeyGenerateBody()) + resources.defer(lambda: client.gateway.delete_key(key)) + headers = {"x-litellm-api-key": f"Bearer {key}"} + _ = client.poll_tool_names(alias, headers) + + listed = client.list_resources(alias, headers) + expected = ( + ("test://static-binary", f"{alias}-static_binary_resource"), + ("test://static-text", f"{alias}-static_text_resource"), + ) + assert listed == expected, f"gateway listed resources {listed}, expected exactly {expected}" + + body = client.read_resource(alias, headers, "test://static-text") + assert body == "Static text resource from the e2e conformance stub" From 6c0d405ef471e8736226b4a78b4eb57572d88069 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Wed, 15 Jul 2026 13:04:11 -0700 Subject: [PATCH 11/17] refactor(e2e): scope the mcp suite to the core happy paths, keeping the conformance-ready foundation --- tests/e2e/mcp/test_mcp_conformance_e2e.py | 121 ------------------ .../e2e/mcp/test_mcp_prompts_resources_e2e.py | 99 -------------- 2 files changed, 220 deletions(-) delete mode 100644 tests/e2e/mcp/test_mcp_conformance_e2e.py delete mode 100644 tests/e2e/mcp/test_mcp_prompts_resources_e2e.py diff --git a/tests/e2e/mcp/test_mcp_conformance_e2e.py b/tests/e2e/mcp/test_mcp_conformance_e2e.py deleted file mode 100644 index 28a4c795a115..000000000000 --- a/tests/e2e/mcp/test_mcp_conformance_e2e.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Live e2e: the official MCP conformance suite, run through the gateway. - -Covers mcp.protocol.api_key.passes_official_conformance: the gateway is a -protocol middlebox, so beyond this suite's behavior tests it must stay -conformant to the MCP spec as re-served to hosts. This test drives the -official @modelcontextprotocol/conformance server scenarios (the same suite -the SDKs gate their CI on) against a gateway-registered server backed by the -stub's /conformance mount, which implements the suite's hardcoded fixture -contract (test_simple_text, test://static-text, test_simple_prompt, ...). - -The conformance CLI cannot send custom headers, so the run goes through -auth_forwarder.serve(), an in-process reverse proxy that stamps the virtual -key onto every request the way a configured MCP host's HTTP layer would; the -gateway path itself stays fully authenticated and unmodified. - -EXPECTED_GAPS is the checked-in baseline, exact in both directions: a -scenario failing that is not listed fails this test (a regression), and a -listed scenario that starts passing also fails it (so the baseline ratchets -down instead of going stale). The current entries are real gateway findings, -verified by hand: logging/setLevel and completion/complete are not relayed -(-32601), prompts/get resolves alias-prefixed names only (the unprefixed -fallback that tools/call has is missing, so the suite's hardcoded prompt -names 403), and binary resource read-through drops the base64 blob field -(the stub serves it; the gateway's answer has no blob). - -Scenarios needing client capabilities the gateway does not advertise for its -callers (sampling, elicitation) and SSE-timing scenarios are intentionally -not run; the curated list below is the subset a gateway can honestly own. -""" - -from __future__ import annotations - -import shutil -import subprocess -from collections.abc import Iterator -from pathlib import Path - -import pytest - -import auth_forwarder -from e2e_config import MCP_STUB_CONFORMANCE_URL, unique_marker -from mcp_client import McpClient -from models import KeyGenerateBody, McpServerCreateBody - -pytestmark = pytest.mark.e2e - -CONFORMANCE_PACKAGE = "@modelcontextprotocol/conformance@0.1.11" - -SCENARIOS = ( - "server-initialize", - "ping", - "logging-set-level", - "completion-complete", - "tools-list", - "tools-call-simple-text", - "tools-call-error", - "resources-list", - "resources-read-text", - "resources-read-binary", - "resources-templates-read", - "prompts-list", - "prompts-get-simple", - "prompts-get-with-args", -) - -EXPECTED_GAPS = { - "logging-set-level": "gateway answers logging/setLevel with -32601 Method not found instead of relaying it", - "completion-complete": "gateway answers completion/complete with -32601 Method not found instead of relaying it", - "prompts-get-simple": "prompts/get lacks the unprefixed-name fallback tools/call has; unprefixed names 403", - "prompts-get-with-args": "prompts/get lacks the unprefixed-name fallback tools/call has; unprefixed names 403", - "resources-read-binary": "gateway drops the base64 blob field on binary resource read-through", -} - - -@pytest.fixture(scope="module") -def conformance_target(client: McpClient) -> Iterator[str]: - """A conformance-fixture server registered on the gateway, fronted by the - key-stamping forwarder; yields the URL the conformance CLI tests. Module - scoped so all scenarios share one server, one key, and one forwarder.""" - if shutil.which("npx") is None: - pytest.skip("npx not available; the official conformance suite runs on Node") - alias = f"e2emcpconf{unique_marker()}" - created = client.create_server( - McpServerCreateBody(alias=alias, url=MCP_STUB_CONFORMANCE_URL, allow_all_keys=True) - ) - key = client.gateway.generate_key(KeyGenerateBody()) - try: - _ = client.poll_tool_names(alias, {"x-litellm-api-key": f"Bearer {key}"}) - with auth_forwarder.serve(key) as forwarder_base: - yield f"{forwarder_base}/{alias}/mcp" - finally: - client.delete_server(created.server_id) - client.gateway.delete_key(key) - - -class TestMcpOfficialConformance: - """Each curated official scenario passes through the gateway, except the - exact set of known gaps pinned in EXPECTED_GAPS.""" - - @pytest.mark.covers("mcp.protocol.api_key.passes_official_conformance") - @pytest.mark.parametrize("scenario", SCENARIOS) - def test_official_scenario(self, scenario: str, conformance_target: str, tmp_path: Path) -> None: - run = subprocess.run( - ["npx", "-y", CONFORMANCE_PACKAGE, "server", "--url", conformance_target, "--scenario", scenario], - capture_output=True, - text=True, - timeout=300, - cwd=tmp_path, - ) - failed = run.returncode != 0 - expected_reason = EXPECTED_GAPS.get(scenario) - if expected_reason is not None: - assert failed, ( - f"conformance scenario {scenario!r} now PASSES; the gateway gap " - f"({expected_reason}) appears fixed, so remove it from EXPECTED_GAPS to ratchet the baseline" - ) - return - assert not failed, ( - f"conformance scenario {scenario!r} failed through the gateway (exit {run.returncode}); " - f"output tail:\n{run.stdout[-1500:]}" - ) diff --git a/tests/e2e/mcp/test_mcp_prompts_resources_e2e.py b/tests/e2e/mcp/test_mcp_prompts_resources_e2e.py deleted file mode 100644 index 26b7c5201932..000000000000 --- a/tests/e2e/mcp/test_mcp_prompts_resources_e2e.py +++ /dev/null @@ -1,99 +0,0 @@ -"""Live e2e: the MCP gateway's prompt and resource primitives. - -Covers mcp.list_prompts.api_key.succeeds, mcp.get_prompt.api_key.succeeds, -mcp.list_resources.api_key.succeeds, and mcp.read_resource.api_key.succeeds, -against the stub's /conformance mount (tests/e2e/mcp/stub/), the one upstream -that serves all three MCP primitives. - -The gateway's namespacing contract differs per primitive, and the assertions -pin it exactly as observed live: prompt names are alias-prefixed like tool -names (and must be fetched by the prefixed name), while resource URIs pass -through unprefixed (only the resource's display name gains the prefix). The -prompt-rendering assertion feeds unique per-run argument values through -prompts/get and requires them back verbatim in the rendered text, so a cached -or canned response cannot pass; the resource assertion requires the exact -fixture body. - -The binary-resource read (test://static-binary) is deliberately NOT asserted -here: the gateway currently drops the base64 blob field on read-through -(verified against the stub directly, which serves it), and that gap is pinned -in the conformance suite baseline (test_mcp_conformance_e2e.py) instead. -""" - -from __future__ import annotations - -import pytest - -from e2e_config import MCP_STUB_CONFORMANCE_URL, unique_marker -from lifecycle import ResourceManager -from mcp_client import McpClient -from models import KeyGenerateBody, McpServerCreateBody - -pytestmark = pytest.mark.e2e - - -class TestMcpPromptsAndResources: - """A registered server's prompts and resources are listed, fetched, and - read through the gateway with the same lifecycle contract as tools.""" - - @pytest.mark.covers("mcp.list_prompts.api_key.succeeds") - @pytest.mark.covers("mcp.get_prompt.api_key.succeeds") - def test_prompts_list_and_render_with_arguments( - self, client: McpClient, resources: ResourceManager - ) -> None: - alias = f"e2emcpprompts{unique_marker()}" - created = client.create_server( - McpServerCreateBody(alias=alias, url=MCP_STUB_CONFORMANCE_URL, allow_all_keys=True) - ) - resources.defer(lambda: client.delete_server(created.server_id)) - - stored = client.server_info(created.server_id) - assert stored.alias == alias - assert stored.url == MCP_STUB_CONFORMANCE_URL - - key = client.gateway.generate_key(KeyGenerateBody()) - resources.defer(lambda: client.gateway.delete_key(key)) - headers = {"x-litellm-api-key": f"Bearer {key}"} - _ = client.poll_tool_names(alias, headers) - - listed = client.list_prompts(alias, headers) - expected = ( - (f"{alias}-test_prompt_with_arguments", ("arg1", "arg2")), - (f"{alias}-test_simple_prompt", ()), - ) - assert listed == expected, f"gateway listed prompts {listed}, expected exactly {expected}" - - first_value = f"e2e-{unique_marker()}" - second_value = f"e2e-{unique_marker()}" - rendered = client.get_prompt( - alias, headers, f"{alias}-test_prompt_with_arguments", {"arg1": first_value, "arg2": second_value} - ) - assert rendered == f"Prompt rendered with arg1={first_value} and arg2={second_value}" - - @pytest.mark.covers("mcp.list_resources.api_key.succeeds") - @pytest.mark.covers("mcp.read_resource.api_key.succeeds") - def test_resources_list_and_read_text(self, client: McpClient, resources: ResourceManager) -> None: - alias = f"e2emcpresources{unique_marker()}" - created = client.create_server( - McpServerCreateBody(alias=alias, url=MCP_STUB_CONFORMANCE_URL, allow_all_keys=True) - ) - resources.defer(lambda: client.delete_server(created.server_id)) - - stored = client.server_info(created.server_id) - assert stored.alias == alias - assert stored.url == MCP_STUB_CONFORMANCE_URL - - key = client.gateway.generate_key(KeyGenerateBody()) - resources.defer(lambda: client.gateway.delete_key(key)) - headers = {"x-litellm-api-key": f"Bearer {key}"} - _ = client.poll_tool_names(alias, headers) - - listed = client.list_resources(alias, headers) - expected = ( - ("test://static-binary", f"{alias}-static_binary_resource"), - ("test://static-text", f"{alias}-static_text_resource"), - ) - assert listed == expected, f"gateway listed resources {listed}, expected exactly {expected}" - - body = client.read_resource(alias, headers, "test://static-text") - assert body == "Static text resource from the e2e conformance stub" From 9fb7271ac64436a140889b43d9bd083dd7c5e484 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Wed, 15 Jul 2026 13:35:38 -0700 Subject: [PATCH 12/17] refactor(e2e): name the interactive OAuth test as the list-and-call happy path it exercises --- tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py index 92ce7a8b0370..00b855c3676a 100644 --- a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py +++ b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py @@ -48,11 +48,20 @@ class TestMcpOauthAuthorizationCode: """An authorization_code server challenges unauthenticated sessions, runs the full interactive dance with a real MCP host, and serves tools with the - per-user token the gateway obtained from the IdP.""" + per-user token the gateway obtained from the IdP. + + There is deliberately no authorization-bearer twin of this test: the OAuth + token owns the `Authorization` header on MCP traffic, so the virtual key + must ride `x-litellm-api-key`. A key presented in `Authorization` instead + never even reaches the dance on current gateways: any bearer there skips + the pre-session 401 challenge and the session is served a masked, empty + tool list, so an OAuth-capable host (which engages on 401) never starts + authorizing. That gap is a known product issue, reproduced live while + building this test; when it is fixed, the twin belongs here.""" @pytest.mark.covers("mcp.list_tools.oauth.completes_authorization_code_flow") @pytest.mark.covers("mcp.call_tool.oauth.uses_per_user_token") - def test_challenge_then_authorization_code_dance_reaches_tools( + def test_list_and_call_tools_with_x_litellm_api_key_header( self, client: McpClient, resources: ResourceManager ) -> None: marker = unique_marker() From 9b144f131142abe89389ea09e9e72c447d631244 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Wed, 15 Jul 2026 16:00:09 -0700 Subject: [PATCH 13/17] test(e2e): run the list-and-call happy path through the interactive OAuth flow under both ingress headers --- .../e2e/mcp/test_mcp_oauth_interactive_e2e.py | 131 ++++++++++++++---- tests/e2e/mcp/test_mcp_tool_access_e2e.py | 98 +++---------- tests/e2e/models.py | 8 ++ 3 files changed, 128 insertions(+), 109 deletions(-) diff --git a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py index 00b855c3676a..9dc28a7a48d3 100644 --- a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py +++ b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py @@ -1,6 +1,8 @@ -"""Live e2e: the interactive (authorization_code) OAuth MCP flow. +"""Live e2e: list-and-call through the interactive (authorization_code) OAuth flow. -Covers mcp.list_tools.oauth.completes_authorization_code_flow and +Covers the core list_tools/call_tool happy path against a real OAuth MCP +server, once per documented ingress header, plus +mcp.list_tools.oauth.completes_authorization_code_flow and mcp.call_tool.oauth.uses_per_user_token: a gateway-managed oauth2 server in the authorization_code flow must challenge an unauthorized MCP session with 401 + WWW-Authenticate, let a real MCP host complete the whole interactive @@ -10,16 +12,27 @@ the per-user upstream token the gateway obtained; the caller's virtual key must never leave the gateway. -The MCP-host side is the official mcp SDK's own OAuth machinery -(OAuthClientProvider), the same code path desktop MCP hosts run; only the -browser leg is replaced by a redirect chaser that follows the authorize chain -(gateway -> stub IdP -> gateway callback -> host redirect_uri) with plain -GETs. The upstream is the /oauthuser stub mount, which 401s anything but the -exact access token the stub IdP's authorization_code grant hands out, so a -served call proves the gateway completed the code exchange (the stub verifies -client credentials, redirect_uri, one-time code, and the S256 code_verifier) -rather than forwarding anything it already had. The recorded_headers -read-back then makes the injected token explicit and adds the leak check. +The caller is a real scoped internal user, not a wildcard: the virtual key is +user-bound and granted the oauth server through object_permission (the server +is not allow_all_keys), so the flow tested is exactly what a permissioned +customer key experiences. The MCP-host side is the official mcp SDK's own +OAuth machinery (OAuthClientProvider), the same code path desktop MCP hosts +run; only the browser leg is replaced by a redirect chaser that follows the +authorize chain (gateway -> stub IdP -> gateway callback -> host +redirect_uri) with plain GETs. The upstream is the /oauthuser stub mount, +which 401s anything but the exact access token the stub IdP's +authorization_code grant hands out, so a served call proves the gateway +completed the code exchange rather than forwarding anything it already had; +the recorded_headers read-back makes the injected token explicit and adds the +leak check. + +The two header styles are deliberately separate, explicitly named tests, and +they assert the same contract: which header carries the key must not change +what the OAuth flow does. Once the dance completes, the SDK carries the +gateway-minted OAuth token in `Authorization` on MCP traffic (overwriting a +key placed there), which is why the x-litellm-api-key form is what production +hosts configure; the Authorization form pins that a key presented the other +documented way is still challenged into the same working flow. """ from __future__ import annotations @@ -38,7 +51,7 @@ ) from lifecycle import ResourceManager from mcp_client import InMemoryTokenStorage, McpClient, McpDenied, StubRecordedHeaders -from models import KeyGenerateBody, McpServerCreateBody, McpServerCredentials +from models import KeyGenerateBody, KeyObjectPermission, McpServerCreateBody, McpServerCredentials pytestmark = pytest.mark.e2e @@ -46,19 +59,12 @@ class TestMcpOauthAuthorizationCode: - """An authorization_code server challenges unauthenticated sessions, runs - the full interactive dance with a real MCP host, and serves tools with the - per-user token the gateway obtained from the IdP. - - There is deliberately no authorization-bearer twin of this test: the OAuth - token owns the `Authorization` header on MCP traffic, so the virtual key - must ride `x-litellm-api-key`. A key presented in `Authorization` instead - never even reaches the dance on current gateways: any bearer there skips - the pre-session 401 challenge and the session is served a masked, empty - tool list, so an OAuth-capable host (which engages on 401) never starts - authorizing. That gap is a known product issue, reproduced live while - building this test; when it is fixed, the twin belongs here.""" + """A scoped internal-user key on an authorization_code server is + challenged, completes the interactive dance, and lists and calls tools + with the per-user token the gateway obtained from the IdP.""" + @pytest.mark.covers("mcp.list_tools.api_key.succeeds") + @pytest.mark.covers("mcp.call_tool.api_key.succeeds") @pytest.mark.covers("mcp.list_tools.oauth.completes_authorization_code_flow") @pytest.mark.covers("mcp.call_tool.oauth.uses_per_user_token") def test_list_and_call_tools_with_x_litellm_api_key_header( @@ -70,7 +76,7 @@ def test_list_and_call_tools_with_x_litellm_api_key_header( McpServerCreateBody( alias=alias, url=MCP_STUB_OAUTHUSER_URL, - allow_all_keys=True, + allow_all_keys=False, auth_type="oauth2", oauth2_flow="authorization_code", authorization_url=MCP_STUB_AUTHORIZE_BROWSER_URL, @@ -88,9 +94,15 @@ def test_list_and_call_tools_with_x_litellm_api_key_header( assert stored.oauth2_flow == "authorization_code" assert stored.authorization_url == MCP_STUB_AUTHORIZE_BROWSER_URL assert stored.token_url == MCP_STUB_TOKEN_URL + assert stored.allow_all_keys is False assert stored.credentials is None, f"client secret must be redacted on read-back, got {stored.credentials}" - key = client.gateway.generate_key(KeyGenerateBody(user_id="e2e-test-user")) + key = client.gateway.generate_key( + KeyGenerateBody( + user_id="e2e-test-user", + object_permission=KeyObjectPermission(mcp_servers=[created.server_id]), + ) + ) resources.defer(lambda: client.gateway.delete_key(key)) headers = {"x-litellm-api-key": f"Bearer {key}"} @@ -124,3 +136,68 @@ def test_list_and_call_tools_with_x_litellm_api_key_header( ) leaked = sorted(name for name, value in upstream_headers.items() if key in value) assert leaked == [], f"caller's virtual key crossed the gateway boundary in header(s) {leaked}" + + @pytest.mark.covers("mcp.list_tools.bearer.succeeds") + @pytest.mark.covers("mcp.call_tool.bearer.succeeds") + def test_list_and_call_tools_with_authorization_bearer_header( + self, client: McpClient, resources: ResourceManager + ) -> None: + """The identical contract with the key presented as + `Authorization: Bearer ` instead: the gateway must challenge the + pre-dance session with 401 exactly like the x-litellm-api-key form, + and the completed dance must serve the same tools.""" + marker = unique_marker() + alias = f"e2emcpauthcodez{marker}" + created = client.create_server( + McpServerCreateBody( + alias=alias, + url=MCP_STUB_OAUTHUSER_URL, + allow_all_keys=False, + auth_type="oauth2", + oauth2_flow="authorization_code", + authorization_url=MCP_STUB_AUTHORIZE_BROWSER_URL, + token_url=MCP_STUB_TOKEN_URL, + credentials=McpServerCredentials( + client_id=MCP_STUB_OAUTH_USER_CLIENT_ID, + client_secret=MCP_STUB_OAUTH_USER_CLIENT_SECRET, + ), + ) + ) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.auth_type == "oauth2" + assert stored.oauth2_flow == "authorization_code" + assert stored.allow_all_keys is False + + key = client.gateway.generate_key( + KeyGenerateBody( + user_id="e2e-test-user", + object_permission=KeyObjectPermission(mcp_servers=[created.server_id]), + ) + ) + resources.defer(lambda: client.gateway.delete_key(key)) + headers = {"Authorization": f"Bearer {key}"} + + control_alias = f"e2emcpauthcodezctl{marker}" + control = client.create_server( + McpServerCreateBody(alias=control_alias, url=MCP_STUB_URL, allow_all_keys=True) + ) + resources.defer(lambda: client.delete_server(control.server_id)) + _ = client.poll_tool_names(control_alias, headers) + + challenged = client.list_tools_once(alias, headers) + assert isinstance(challenged, McpDenied), ( + f"session without a user token was served tools instead of the OAuth challenge: {challenged}" + ) + assert challenged.status_code == 401, f"expected the 401 OAuth challenge, got {challenged}" + + storage = InMemoryTokenStorage() + names = client.poll_oauth_tool_names(alias, headers, storage) + expected = tuple(sorted(f"{alias}-{tool}" for tool in GUARDED_STUB_TOOLS)) + assert names == expected, f"post-dance listing was {names}, expected exactly {expected}" + + payload = f"e2e-{marker}" + result = client.oauth_call_tool(alias, headers, storage, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo through the user-token upstream errored: {result.text[:300]}" + assert result.text == payload diff --git a/tests/e2e/mcp/test_mcp_tool_access_e2e.py b/tests/e2e/mcp/test_mcp_tool_access_e2e.py index 2602425d2189..44bb7cf7741c 100644 --- a/tests/e2e/mcp/test_mcp_tool_access_e2e.py +++ b/tests/e2e/mcp/test_mcp_tool_access_e2e.py @@ -1,28 +1,20 @@ -"""Live e2e: MCP gateway tool access under both documented auth headers. +"""Live e2e: the MCP gateway's ingress key gate under both documented headers. -Covers mcp.list_tools.api_key.succeeds + mcp.call_tool.api_key.succeeds (the -`x-litellm-api-key` header), mcp.list_tools.bearer.succeeds + -mcp.call_tool.bearer.succeeds (the `Authorization` header), and -mcp.list_tools.{api_key,bearer}.rejects_unknown_key (the ingress gate), -all against the deterministic mcp-stub compose service (tests/e2e/mcp/stub/). +Covers mcp.list_tools.{api_key,bearer}.rejects_unknown_key against the +deterministic mcp-stub compose service (tests/e2e/mcp/stub/): a key the proxy +does not recognize must be refused with an explicit 401 at session +establishment, whichever documented header carries it. The list-and-call +happy path itself lives in test_mcp_oauth_interactive_e2e.py, where it runs +against a real OAuth server; these tests keep the plain ingress gate pinned +with a deliberately minimal setup. Each test body spells out every step a human QA run would take, in order: -create the server over the management API, read the record back, mint a -virtual key over /key/generate, build the exact wire header, then drive the -real MCP protocol through the gateway the way a production MCP host does -(initialize, tools/list, tools/call over streamable HTTP at -{PROXY}/{alias}/mcp) and assert the enforced behavior. Teardown is the only -thing delegated (resources.defer), because it must run even when an -assertion fails. - -The two documented header styles are deliberately separate, explicitly named -tests rather than one parametrized body, so the literal header each one sends -(`x-litellm-api-key: Bearer sk-...` / `Authorization: Bearer sk-...`) is -visible in its own body. Both are Bearer-prefixed on the MCP routes, matching -the docs; a bare key in `x-litellm-api-key` is accepted on LLM routes but -401s here. The unknown-key rejection tests settle the server with a real key -first, so their 401 can only be the gateway's ingress auth refusing the key, -never record propagation. +create the server over the management API, mint a virtual key over +/key/generate, build the exact wire header, settle the server with the real +key (so the later refusal can only be the ingress auth, never record +propagation), then present an unknown key over the same header and require +the explicit 401. Teardown is the only thing delegated (resources.defer), +because it must run even when an assertion fails. """ from __future__ import annotations @@ -36,67 +28,9 @@ pytestmark = pytest.mark.e2e -STUB_TOOLS = ("echo", "slow_echo", "stats") - - class TestMcpToolAccess: - """Any virtual key reaches an allow_all_keys server through either - documented auth header; a key the proxy does not recognize is turned away - at the door.""" - - @pytest.mark.covers("mcp.list_tools.api_key.succeeds") - @pytest.mark.covers("mcp.call_tool.api_key.succeeds") - def test_list_and_call_tools_with_x_litellm_api_key_header( - self, client: McpClient, resources: ResourceManager - ) -> None: - alias = f"e2emcp{unique_marker()}" - created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) - resources.defer(lambda: client.delete_server(created.server_id)) - - stored = client.server_info(created.server_id) - assert stored.alias == alias - assert stored.url == MCP_STUB_URL - assert stored.allow_all_keys is True - - key = client.gateway.generate_key(KeyGenerateBody()) - resources.defer(lambda: client.gateway.delete_key(key)) - - headers = {"x-litellm-api-key": f"Bearer {key}"} - names = client.poll_tool_names(alias, headers) - expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) - assert names == expected, f"gateway listed {names}, expected exactly {expected}" - - payload = f"e2e-{unique_marker()}" - result = client.call_tool(alias, headers, f"{alias}-echo", {"text": payload}) - assert result.is_error is False, f"echo call errored: {result.text[:300]}" - assert result.text == payload - - @pytest.mark.covers("mcp.list_tools.bearer.succeeds") - @pytest.mark.covers("mcp.call_tool.bearer.succeeds") - def test_list_and_call_tools_with_authorization_bearer_header( - self, client: McpClient, resources: ResourceManager - ) -> None: - alias = f"e2emcp{unique_marker()}" - created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) - resources.defer(lambda: client.delete_server(created.server_id)) - - stored = client.server_info(created.server_id) - assert stored.alias == alias - assert stored.url == MCP_STUB_URL - assert stored.allow_all_keys is True - - key = client.gateway.generate_key(KeyGenerateBody()) - resources.defer(lambda: client.gateway.delete_key(key)) - - headers = {"Authorization": f"Bearer {key}"} - names = client.poll_tool_names(alias, headers) - expected = tuple(sorted(f"{alias}-{tool}" for tool in STUB_TOOLS)) - assert names == expected, f"gateway listed {names}, expected exactly {expected}" - - payload = f"e2e-{unique_marker()}" - result = client.call_tool(alias, headers, f"{alias}-echo", {"text": payload}) - assert result.is_error is False, f"echo call errored: {result.text[:300]}" - assert result.text == payload + """A key the proxy does not recognize is turned away at the door, under + either documented auth header.""" @pytest.mark.covers("mcp.list_tools.api_key.rejects_unknown_key") def test_unrecognized_key_in_x_litellm_api_key_header_is_turned_away( diff --git a/tests/e2e/models.py b/tests/e2e/models.py index f54674515f18..40b667add05e 100644 --- a/tests/e2e/models.py +++ b/tests/e2e/models.py @@ -39,6 +39,13 @@ class KeyMetadata(BaseModel): logging: list[KeyLoggingCallback] | None = None +class KeyObjectPermission(BaseModel): + """object_permission on /key/generate: the MCP servers (by server_id) a key + may list and call. A key without one only reaches allow_all_keys servers.""" + + mcp_servers: list[str] | None = None + + class KeyGenerateBody(BaseModel): models: list[str] = [] duration: str | None = None @@ -57,6 +64,7 @@ class KeyGenerateBody(BaseModel): rpm_limit: int | None = None allowed_routes: list[str] | None = None metadata: KeyMetadata | None = None + object_permission: KeyObjectPermission | None = None class KeyGenerateResponse(BaseModel): From 58801354182412d0f00f9c44aa4fb0b6c218831a Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Thu, 16 Jul 2026 13:03:24 -0700 Subject: [PATCH 14/17] test(e2e): assert the server record round-trips in the ingress rejection tests --- tests/e2e/mcp/test_mcp_tool_access_e2e.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/e2e/mcp/test_mcp_tool_access_e2e.py b/tests/e2e/mcp/test_mcp_tool_access_e2e.py index 44bb7cf7741c..3b548a1a5b40 100644 --- a/tests/e2e/mcp/test_mcp_tool_access_e2e.py +++ b/tests/e2e/mcp/test_mcp_tool_access_e2e.py @@ -44,6 +44,11 @@ def test_unrecognized_key_in_x_litellm_api_key_header_is_turned_away( created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) resources.defer(lambda: client.delete_server(created.server_id)) + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_URL + assert stored.allow_all_keys is True + key = client.gateway.generate_key(KeyGenerateBody()) resources.defer(lambda: client.gateway.delete_key(key)) _ = client.poll_tool_names(alias, {"x-litellm-api-key": f"Bearer {key}"}) @@ -62,6 +67,11 @@ def test_unrecognized_key_in_authorization_bearer_header_is_turned_away( created = client.create_server(McpServerCreateBody(alias=alias, url=MCP_STUB_URL, allow_all_keys=True)) resources.defer(lambda: client.delete_server(created.server_id)) + stored = client.server_info(created.server_id) + assert stored.alias == alias + assert stored.url == MCP_STUB_URL + assert stored.allow_all_keys is True + key = client.gateway.generate_key(KeyGenerateBody()) resources.defer(lambda: client.gateway.delete_key(key)) _ = client.poll_tool_names(alias, {"Authorization": f"Bearer {key}"}) From 4fba2f440f90816fab651b6c15560a7150ca1fdf Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Thu, 16 Jul 2026 15:39:06 -0700 Subject: [PATCH 15/17] refactor(e2e): make the Authorization-header OAuth test a challenge-guard, not a full dance The Authorization-header variant cannot complete the interactive round-trip: once the host finishes the OAuth dance the SDK carries the minted upstream token in Authorization, evicting the LiteLLM key the gateway needs to resolve the per-user token. Assert the achievable, correct contract instead: a key in Authorization on a gateway-managed oauth2 server gets the 401 challenge, not a masked empty tool list. Full list-and-call stays on the x-litellm-api-key variant. Red on stock main (masking); flips green with the mode-aware gateway challenge fix. --- tests/e2e/coverage_registry/mcp.yaml | 8 +++ .../e2e/mcp/test_mcp_oauth_interactive_e2e.py | 61 ++++++++++--------- 2 files changed, 41 insertions(+), 28 deletions(-) diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml index c2c2f59e76a1..c3c9c5b52997 100644 --- a/tests/e2e/coverage_registry/mcp.yaml +++ b/tests/e2e/coverage_registry/mcp.yaml @@ -159,3 +159,11 @@ assertions: [passes_official_conformance] source: "@modelcontextprotocol/conformance server scenarios via tests/e2e/mcp/test_mcp_conformance_e2e.py" rationale: The gateway re-serves the MCP protocol to hosts, so it must stay spec-conformant as a server; the official suite catches lifecycle/error-shape regressions our behavior tests do not encode +- id: mcp.list_tools.oauth.challenges_bearer_key_not_masked + module: mcp + tier: P0 + operation: list_tools + auth_family: oauth + assertions: [challenges_bearer_key_not_masked] + source: "server.py _raise_preemptive_401_for_unauthenticated_servers (mode-aware oauth2 gate)" + rationale: A virtual key in the Authorization header on a gateway-managed authorization_code server must get the 401 OAuth challenge, not a masked 200+empty tool list; the full round-trip is unreachable via this header (the OAuth token claims the slot) so the challenge is the guardable contract, and the masking regression (fixed by the mode-aware gate) is the bug it pins diff --git a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py index 9dc28a7a48d3..fe4b19143fdb 100644 --- a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py +++ b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py @@ -26,13 +26,16 @@ the recorded_headers read-back makes the injected token explicit and adds the leak check. -The two header styles are deliberately separate, explicitly named tests, and -they assert the same contract: which header carries the key must not change -what the OAuth flow does. Once the dance completes, the SDK carries the -gateway-minted OAuth token in `Authorization` on MCP traffic (overwriting a -key placed there), which is why the x-litellm-api-key form is what production -hosts configure; the Authorization form pins that a key presented the other -documented way is still challenged into the same working flow. +The two documented header placements are covered by two deliberately separate +tests that assert different, achievable contracts. The x-litellm-api-key form +runs the full round-trip, because that header stays free for the LiteLLM key +while the SDK owns `Authorization` for the minted OAuth token. The +Authorization form is a challenge-guard only: putting the LiteLLM key in the +same header the OAuth token must occupy cannot complete the dance (the token +evicts the key on the post-dance retry, so the gateway loses the identity it +needs to resolve the per-user token), so the contract there is that the +gateway fails closed and loudly with the 401 challenge rather than silently +masking the session as an empty tool list. """ from __future__ import annotations @@ -59,9 +62,11 @@ class TestMcpOauthAuthorizationCode: - """A scoped internal-user key on an authorization_code server is - challenged, completes the interactive dance, and lists and calls tools - with the per-user token the gateway obtained from the IdP.""" + """A scoped internal-user key on an authorization_code server: the + x-litellm-api-key form is challenged, completes the interactive dance, and + lists and calls tools with the per-user token the gateway obtained; the + Authorization form is challenged (not masked) but cannot complete the + round-trip, since the OAuth token claims the Authorization slot.""" @pytest.mark.covers("mcp.list_tools.api_key.succeeds") @pytest.mark.covers("mcp.call_tool.api_key.succeeds") @@ -137,15 +142,25 @@ def test_list_and_call_tools_with_x_litellm_api_key_header( leaked = sorted(name for name, value in upstream_headers.items() if key in value) assert leaked == [], f"caller's virtual key crossed the gateway boundary in header(s) {leaked}" - @pytest.mark.covers("mcp.list_tools.bearer.succeeds") - @pytest.mark.covers("mcp.call_tool.bearer.succeeds") - def test_list_and_call_tools_with_authorization_bearer_header( + @pytest.mark.covers("mcp.list_tools.oauth.challenges_bearer_key_not_masked") + def test_key_in_authorization_header_is_challenged_not_masked( self, client: McpClient, resources: ResourceManager ) -> None: - """The identical contract with the key presented as - `Authorization: Bearer ` instead: the gateway must challenge the - pre-dance session with 401 exactly like the x-litellm-api-key form, - and the completed dance must serve the same tools.""" + """A virtual key presented in `Authorization: Bearer ` on a + gateway-managed authorization_code server, with no stored per-user + token, must get the 401 OAuth challenge, not a masked empty tool list. + + This is deliberately a challenge-guard, not a full list-and-call: the + full interactive round-trip is unreachable via this header, because + once the host completes the OAuth dance the SDK carries the minted + upstream token in `Authorization`, evicting the LiteLLM key the gateway + needs to resolve the per-user token. So the only supported way to + complete the flow is the x-litellm-api-key form (covered above); the + contract this pins is that the Authorization form fails closed and + loudly (challenge) rather than silently (200 + empty tools). Before the + gateway classified the challenge per oauth2 sub-mode, a bearer in + Authorization suppressed the challenge and the session opened masked; + this test is the regression guard for that.""" marker = unique_marker() alias = f"e2emcpauthcodez{marker}" created = client.create_server( @@ -188,16 +203,6 @@ def test_list_and_call_tools_with_authorization_bearer_header( challenged = client.list_tools_once(alias, headers) assert isinstance(challenged, McpDenied), ( - f"session without a user token was served tools instead of the OAuth challenge: {challenged}" + f"key in Authorization was served a (masked) tool list instead of the OAuth challenge: {challenged}" ) assert challenged.status_code == 401, f"expected the 401 OAuth challenge, got {challenged}" - - storage = InMemoryTokenStorage() - names = client.poll_oauth_tool_names(alias, headers, storage) - expected = tuple(sorted(f"{alias}-{tool}" for tool in GUARDED_STUB_TOOLS)) - assert names == expected, f"post-dance listing was {names}, expected exactly {expected}" - - payload = f"e2e-{marker}" - result = client.oauth_call_tool(alias, headers, storage, f"{alias}-echo", {"text": payload}) - assert result.is_error is False, f"echo through the user-token upstream errored: {result.text[:300]}" - assert result.text == payload From 644d1ec28f2a0182ccb92f20f3c28bb92790f1d2 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Thu, 16 Jul 2026 17:41:34 -0700 Subject: [PATCH 16/17] test(e2e): a stored per-user token lets the key in Authorization list and call tools Positive companion to the Authorization challenge-guard: once a user has authorized (per-user token stored via the x-litellm-api-key dance), a plain Authorization: Bearer session needs no dance and the gateway serves tools using the stored token. Seeds the token via the dance, then lists and calls over an Authorization-key session, and asserts the upstream received the stored per-user token (not the key) with no key leak. Claims the previously unclaimed mcp.{list_tools,call_tool}.bearer.succeeds cells. Green on stock. --- .../e2e/mcp/test_mcp_oauth_interactive_e2e.py | 107 +++++++++++++++--- 1 file changed, 93 insertions(+), 14 deletions(-) diff --git a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py index fe4b19143fdb..6fdab5742d4f 100644 --- a/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py +++ b/tests/e2e/mcp/test_mcp_oauth_interactive_e2e.py @@ -26,16 +26,17 @@ the recorded_headers read-back makes the injected token explicit and adds the leak check. -The two documented header placements are covered by two deliberately separate -tests that assert different, achievable contracts. The x-litellm-api-key form -runs the full round-trip, because that header stays free for the LiteLLM key +The documented header placements are covered by separate tests asserting +different, achievable contracts. The x-litellm-api-key form runs the full +interactive round-trip, because that header stays free for the LiteLLM key while the SDK owns `Authorization` for the minted OAuth token. The -Authorization form is a challenge-guard only: putting the LiteLLM key in the -same header the OAuth token must occupy cannot complete the dance (the token -evicts the key on the post-dance retry, so the gateway loses the identity it -needs to resolve the per-user token), so the contract there is that the -gateway fails closed and loudly with the 401 challenge rather than silently -masking the session as an empty tool list. +Authorization form is split by whether a per-user token already exists: with +no stored token, the LiteLLM key in Authorization cannot complete the dance +(the token would evict the key on the post-dance retry, so the gateway loses +the identity it needs), so the contract is that the gateway fails closed and +loudly with the 401 challenge rather than silently masking an empty tool list; +with a stored token, no dance is needed, so a plain Authorization-key session +lists and calls using the token the gateway already holds for that user. """ from __future__ import annotations @@ -62,11 +63,13 @@ class TestMcpOauthAuthorizationCode: - """A scoped internal-user key on an authorization_code server: the - x-litellm-api-key form is challenged, completes the interactive dance, and - lists and calls tools with the per-user token the gateway obtained; the - Authorization form is challenged (not masked) but cannot complete the - round-trip, since the OAuth token claims the Authorization slot.""" + """A scoped internal-user key on an authorization_code server, across three + behaviors: the x-litellm-api-key form is challenged, completes the + interactive dance, and lists/calls with the per-user token the gateway + obtained; a key in Authorization with no stored token yet is challenged + (not masked), since the OAuth token would claim the Authorization slot and + the dance cannot complete there; and once a per-user token is stored, a + plain Authorization-key session lists/calls using that stored token.""" @pytest.mark.covers("mcp.list_tools.api_key.succeeds") @pytest.mark.covers("mcp.call_tool.api_key.succeeds") @@ -206,3 +209,79 @@ def test_key_in_authorization_header_is_challenged_not_masked( f"key in Authorization was served a (masked) tool list instead of the OAuth challenge: {challenged}" ) assert challenged.status_code == 401, f"expected the 401 OAuth challenge, got {challenged}" + + @pytest.mark.covers("mcp.list_tools.bearer.succeeds") + @pytest.mark.covers("mcp.call_tool.bearer.succeeds") + def test_stored_token_serves_list_and_call_with_key_in_authorization_header( + self, client: McpClient, resources: ResourceManager + ) -> None: + """A returning user who has already authorized presents the LiteLLM key + in `Authorization: Bearer ` and the gateway lists and calls tools + using the stored per-user token. + + This is the positive counterpart to the challenge-guard above. It works + because no interactive dance is needed once a per-user token exists: the + gateway resolves the user from the LiteLLM key in Authorization and + injects the stored upstream token at egress. (The dance itself cannot be + completed with the key in Authorization, since the SDK would overwrite + that header with the minted token; that is why the token is seeded here + via the x-litellm-api-key dance first, then the plain Authorization-key + session is what serves.) The recorded_headers read-back proves the + upstream received the stored per-user token, not the LiteLLM key, and + the key crosses the gateway boundary in no header.""" + marker = unique_marker() + alias = f"e2emcpauthcodestored{marker}" + created = client.create_server( + McpServerCreateBody( + alias=alias, + url=MCP_STUB_OAUTHUSER_URL, + allow_all_keys=False, + auth_type="oauth2", + oauth2_flow="authorization_code", + authorization_url=MCP_STUB_AUTHORIZE_BROWSER_URL, + token_url=MCP_STUB_TOKEN_URL, + credentials=McpServerCredentials( + client_id=MCP_STUB_OAUTH_USER_CLIENT_ID, + client_secret=MCP_STUB_OAUTH_USER_CLIENT_SECRET, + ), + ) + ) + resources.defer(lambda: client.delete_server(created.server_id)) + + stored = client.server_info(created.server_id) + assert stored.auth_type == "oauth2" + assert stored.oauth2_flow == "authorization_code" + assert stored.allow_all_keys is False + assert stored.credentials is None, f"client secret must be redacted on read-back, got {stored.credentials}" + + key = client.gateway.generate_key( + KeyGenerateBody( + user_id="e2e-test-user", + object_permission=KeyObjectPermission(mcp_servers=[created.server_id]), + ) + ) + resources.defer(lambda: client.gateway.delete_key(key)) + + storage = InMemoryTokenStorage() + seeded = client.poll_oauth_tool_names(alias, {"x-litellm-api-key": f"Bearer {key}"}, storage) + expected = tuple(sorted(f"{alias}-{tool}" for tool in GUARDED_STUB_TOOLS)) + assert seeded == expected, f"the authorizing dance listed {seeded}, expected exactly {expected}" + + authorization_headers = {"Authorization": f"Bearer {key}"} + names = client.poll_tool_names(alias, authorization_headers) + assert names == expected, f"Authorization-key listing was {names}, expected exactly {expected}" + + payload = f"e2e-{marker}" + result = client.call_tool(alias, authorization_headers, f"{alias}-echo", {"text": payload}) + assert result.is_error is False, f"echo with the key in Authorization errored: {result.text[:300]}" + assert result.text == payload + + recorded = client.call_tool(alias, authorization_headers, f"{alias}-recorded_headers", {}) + assert recorded.is_error is False, f"recorded_headers call errored: {recorded.text[:300]}" + upstream_headers = StubRecordedHeaders.model_validate_json(recorded.text).root + assert upstream_headers.get("authorization") == f"Bearer {MCP_STUB_OAUTH_USER_ACCESS_TOKEN}", ( + "upstream must receive the stored per-user token the gateway injects, not the LiteLLM key, " + f"got {upstream_headers.get('authorization')!r}" + ) + leaked = sorted(name for name, value in upstream_headers.items() if key in value) + assert leaked == [], f"caller's virtual key crossed the gateway boundary in header(s) {leaked}" From b92b7cc943f8d43d6ab17ffefa4a95df18571dd6 Mon Sep 17 00:00:00 2001 From: Tin Chi Lo Date: Thu, 16 Jul 2026 19:25:52 -0700 Subject: [PATCH 17/17] refactor(e2e): drop the unused conformance/prompts/resources foundation Removes the auth_forwarder key-stamping relay (unused; raw httpx), the stub's /conformance mount and its fixtures, MCP_STUB_CONFORMANCE_URL, the unused prompt/resource client ops, and the unclaimed passes_official_conformance registry cell. None of it was exercised by a test; the suite stays scoped to the core happy paths against the deterministic stub. --- tests/e2e/coverage_registry/mcp.yaml | 8 --- tests/e2e/e2e_config.py | 1 - tests/e2e/mcp/auth_forwarder.py | 88 ---------------------------- tests/e2e/mcp/mcp_client.py | 70 ---------------------- tests/e2e/mcp/stub/stub_server.py | 57 +----------------- 5 files changed, 2 insertions(+), 222 deletions(-) delete mode 100644 tests/e2e/mcp/auth_forwarder.py diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml index c3c9c5b52997..3e333a56b7e4 100644 --- a/tests/e2e/coverage_registry/mcp.yaml +++ b/tests/e2e/coverage_registry/mcp.yaml @@ -151,14 +151,6 @@ assertions: [uses_per_user_token] source: "v2 authorization_code egress arm (per-user DB token)" rationale: Calls on an interactive server must present the user's upstream token, never the caller's virtual key or IdP JWT -- id: mcp.protocol.api_key.passes_official_conformance - module: mcp - tier: P0 - operation: protocol - auth_family: api_key - assertions: [passes_official_conformance] - source: "@modelcontextprotocol/conformance server scenarios via tests/e2e/mcp/test_mcp_conformance_e2e.py" - rationale: The gateway re-serves the MCP protocol to hosts, so it must stay spec-conformant as a server; the official suite catches lifecycle/error-shape regressions our behavior tests do not encode - id: mcp.list_tools.oauth.challenges_bearer_key_not_masked module: mcp tier: P0 diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.py index a5d682807d4a..85f735c9002e 100644 --- a/tests/e2e/e2e_config.py +++ b/tests/e2e/e2e_config.py @@ -46,7 +46,6 @@ # upstream for the interactive OAuth flow, plus the stub IdP's token endpoint. # Derived from MCP_STUB_URL so one override relocates the whole stub. _MCP_STUB_BASE = MCP_STUB_URL.removesuffix("/mcp") -MCP_STUB_CONFORMANCE_URL = f"{_MCP_STUB_BASE}/conformance/mcp" MCP_STUB_OAUTHUSER_URL = f"{_MCP_STUB_BASE}/oauthuser/mcp" MCP_STUB_TOKEN_URL = f"{_MCP_STUB_BASE}/oauth/token" diff --git a/tests/e2e/mcp/auth_forwarder.py b/tests/e2e/mcp/auth_forwarder.py deleted file mode 100644 index 951da72ec8c0..000000000000 --- a/tests/e2e/mcp/auth_forwarder.py +++ /dev/null @@ -1,88 +0,0 @@ -"""In-process reverse proxy that stamps the LiteLLM key onto every request. - -The official conformance suite's client offers no way to send custom headers, -but the gateway's MCP routes require the virtual key. This forwarder plays the -role of an MCP host's HTTP layer configured with the key header: it listens on -a loopback port, injects `x-litellm-api-key: Bearer `, and relays -everything (including SSE streams, unbuffered) to the proxy under test. - -Runs inside the pytest process on a background uvicorn thread; tests get the -local base URL from `serve()` and hand `{base}/{alias}/mcp` to the conformance -CLI as the server under test. -""" - -from __future__ import annotations - -import socket -import threading -import time -from collections.abc import Generator -from contextlib import contextmanager -from typing import cast - -import httpx -import uvicorn -from starlette.applications import Starlette -from starlette.background import BackgroundTask -from starlette.requests import Request -from starlette.responses import StreamingResponse -from starlette.routing import Route - -from e2e_config import PROXY_BASE_URL, REQUEST_TIMEOUT - -_HOP_BY_HOP_REQUEST_HEADERS = frozenset({"host", "content-length"}) -_HOP_BY_HOP_RESPONSE_HEADERS = frozenset({"content-length", "transfer-encoding", "content-encoding"}) - - -def _build_app(upstream: httpx.AsyncClient, litellm_key: str) -> Starlette: - async def forward(request: Request) -> StreamingResponse: - url = httpx.URL(path=request.url.path, query=request.url.query.encode()) - headers = { - name: value - for name, value in request.headers.items() - if name.lower() not in _HOP_BY_HOP_REQUEST_HEADERS - } - headers["x-litellm-api-key"] = f"Bearer {litellm_key}" - proxied = upstream.build_request(request.method, url, headers=headers, content=await request.body()) - response = await upstream.send(proxied, stream=True) - response_headers = { - name: value - for name, value in response.headers.items() - if name.lower() not in _HOP_BY_HOP_RESPONSE_HEADERS - } - return StreamingResponse( - response.aiter_raw(), - status_code=response.status_code, - headers=response_headers, - background=BackgroundTask(response.aclose), - ) - - methods = ["GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS"] - return Starlette(routes=[Route("/{path:path}", forward, methods=methods)]) - - -def _free_loopback_port() -> int: - with socket.socket() as sock: - sock.bind(("127.0.0.1", 0)) - return cast("int", sock.getsockname()[1]) - - -@contextmanager -def serve(litellm_key: str) -> Generator[str]: - """Serve the forwarder for the block's duration; yields its base URL.""" - upstream = httpx.AsyncClient(base_url=PROXY_BASE_URL, timeout=httpx.Timeout(REQUEST_TIMEOUT)) - port = _free_loopback_port() - server = uvicorn.Server( - uvicorn.Config(_build_app(upstream, litellm_key), host="127.0.0.1", port=port, log_level="warning") - ) - thread = threading.Thread(target=server.run, daemon=True) - thread.start() - deadline = time.monotonic() + 15 - while not server.started: - assert time.monotonic() < deadline, "auth forwarder never started" - time.sleep(0.05) - try: - yield f"http://127.0.0.1:{port}" - finally: - server.should_exit = True - thread.join(timeout=10) diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py index 29bf8819d8b6..6efea3016dc4 100644 --- a/tests/e2e/mcp/mcp_client.py +++ b/tests/e2e/mcp/mcp_client.py @@ -121,60 +121,6 @@ async def _call_tool(url: str, headers: dict[str, str], tool: str, arguments: To return McpToolText(text=_first_text(result), is_error=bool(result.isError)) -async def _list_prompts(url: str, headers: dict[str, str]) -> tuple[tuple[str, tuple[str, ...]], ...]: - """(name, argument names) per prompt, sorted by name.""" - async with _http_client(headers) as http_client: - async with streamable_http_client(url, http_client=http_client) as (read, write, _): - async with ClientSession(read, write) as session: - await session.initialize() - listed = await session.list_prompts() - return tuple( - sorted( - (prompt.name, tuple(arg.name for arg in (prompt.arguments or []))) - for prompt in listed.prompts - ) - ) - - -async def _get_prompt(url: str, headers: dict[str, str], name: str, arguments: dict[str, str]) -> str: - """The text of the rendered prompt's first message.""" - async with _http_client(headers) as http_client: - async with streamable_http_client(url, http_client=http_client) as (read, write, _): - async with ClientSession(read, write) as session: - await session.initialize() - result = await session.get_prompt(name, arguments) - first = result.messages[0].content if result.messages else None - if isinstance(first, TextContent): - return first.text - return f"" - - -async def _list_resources(url: str, headers: dict[str, str]) -> tuple[tuple[str, str], ...]: - """(uri, name) per resource, sorted by uri.""" - async with _http_client(headers) as http_client: - async with streamable_http_client(url, http_client=http_client) as (read, write, _): - async with ClientSession(read, write) as session: - await session.initialize() - listed = await session.list_resources() - return tuple(sorted((str(resource.uri), resource.name) for resource in listed.resources)) - - -async def _read_resource(url: str, headers: dict[str, str], uri: str) -> str: - """The text of the resource's first content block.""" - from pydantic import AnyUrl - - async with _http_client(headers) as http_client: - async with streamable_http_client(url, http_client=http_client) as (read, write, _): - async with ClientSession(read, write) as session: - await session.initialize() - result = await session.read_resource(AnyUrl(uri)) - first = result.contents[0] if result.contents else None - text = getattr(first, "text", None) - if isinstance(text, str): - return text - return f"" - - # ---------- interactive (authorization_code) OAuth: the MCP-host side ---------- # Where the "browser" lands at the end of the authorize dance. Nothing listens @@ -393,22 +339,6 @@ def oauth_call_tool( prior poll_oauth_tool_names dance), over its own fresh MCP session.""" return asyncio.run(_oauth_call_tool(_mcp_url(alias), headers, storage, tool, arguments)) - def list_prompts(self, alias: str, headers: dict[str, str]) -> tuple[tuple[str, tuple[str, ...]], ...]: - """prompts/list over its own fresh MCP session: (name, argument names) sorted by name.""" - return asyncio.run(_list_prompts(_mcp_url(alias), headers)) - - def get_prompt(self, alias: str, headers: dict[str, str], name: str, arguments: dict[str, str]) -> str: - """prompts/get over its own fresh MCP session: the rendered first message's text.""" - return asyncio.run(_get_prompt(_mcp_url(alias), headers, name, arguments)) - - def list_resources(self, alias: str, headers: dict[str, str]) -> tuple[tuple[str, str], ...]: - """resources/list over its own fresh MCP session: (uri, name) sorted by uri.""" - return asyncio.run(_list_resources(_mcp_url(alias), headers)) - - def read_resource(self, alias: str, headers: dict[str, str], uri: str) -> str: - """resources/read over its own fresh MCP session: the first content block's text.""" - return asyncio.run(_read_resource(_mcp_url(alias), headers, uri)) - def stub_stats(self, alias: str, headers: dict[str, str], stats_tool: str, marker: str) -> StubToolStats: outcome = self.call_tool(alias, headers, stats_tool, {"marker": marker}) return StubToolStats.model_validate_json(outcome.text) diff --git a/tests/e2e/mcp/stub/stub_server.py b/tests/e2e/mcp/stub/stub_server.py index 8879fdf7edf3..36d1079a4f4d 100644 --- a/tests/e2e/mcp/stub/stub_server.py +++ b/tests/e2e/mcp/stub/stub_server.py @@ -1,6 +1,6 @@ """Deterministic MCP upstreams for the mcp e2e suite. -One process, one port, three streamable-http MCP mounts plus a deterministic +One process, one port, two streamable-http MCP mounts plus a deterministic OAuth2 IdP, so the compose stack keeps a single `mcp-stub` service: - `/mcp` — anonymous. `echo` answers immediately so auth tests can assert an @@ -10,13 +10,6 @@ `max_concurrent_requests` cap must bound); `stats` reads those counters back, so tests observe upstream concurrency through the proxy itself and the stub needs no side-channel port. -- `/conformance/mcp` — anonymous, serving the official - @modelcontextprotocol/conformance suite's hardcoded fixture contract - (test_simple_text / test_error_handling tools, test://static-text, - test://static-binary and the test://template/{id}/data resources, - test_simple_prompt / test_prompt_with_arguments prompts), so the gateway can - be conformance-tested end to end and the suite's own prompt/resource tests - have a deterministic upstream that serves all three MCP primitives. - `/oauthuser/mcp` — the interactive (authorization_code) upstream: rejects anything but `Bearer OAUTH_USER_ACCESS_TOKEN`, which only the authorization_code grant hands out, so a served request proves the whole @@ -68,7 +61,6 @@ OAUTH_USER_REFRESH_TOKEN = "e2e-stub-user-refresh-token" main_mcp = FastMCP("e2e-stub", host="0.0.0.0", port=8765, stateless_http=True) -conformance_mcp = FastMCP("e2e-stub-conformance", host="0.0.0.0", port=8765, stateless_http=True) oauthuser_mcp = FastMCP("e2e-stub-oauthuser", host="0.0.0.0", port=8765, stateless_http=True) @@ -117,50 +109,6 @@ def stats(marker: str) -> str: ) -@conformance_mcp.tool() -def test_simple_text() -> str: - """Return a plain text result (the conformance suite's simple-text fixture).""" - return "Hello from the e2e conformance stub" - - -@conformance_mcp.tool() -def test_error_handling(should_error: bool = True) -> str: - """Raise so the result carries isError (the conformance suite's error fixture).""" - if should_error: - raise ValueError("Intentional error from the e2e conformance stub") - return "no error" - - -@conformance_mcp.resource("test://static-text") -def static_text_resource() -> str: - """The conformance suite's static text resource fixture.""" - return "Static text resource from the e2e conformance stub" - - -@conformance_mcp.resource("test://static-binary") -def static_binary_resource() -> bytes: - """The conformance suite's static binary resource fixture.""" - return b"\x89binary-fixture-bytes\x00\x01" - - -@conformance_mcp.resource("test://template/{id}/data") -def template_resource(id: str) -> str: - """The conformance suite's resource template fixture: {id} must substitute.""" - return f"Template resource data for id={id}" - - -@conformance_mcp.prompt() -def test_simple_prompt() -> str: - """The conformance suite's no-argument prompt fixture.""" - return "This is a simple prompt from the e2e conformance stub" - - -@conformance_mcp.prompt() -def test_prompt_with_arguments(arg1: str, arg2: str) -> str: - """The conformance suite's argument-substitution prompt fixture.""" - return f"Prompt rendered with arg1={arg1} and arg2={arg2}" - - def _register_guarded_tools(server: FastMCP, mount: str) -> None: def echo(text: str) -> str: """Return `text` unchanged.""" @@ -276,7 +224,7 @@ async def oauth_token(request: Request) -> JSONResponse: def build_app() -> Starlette: - servers = (main_mcp, conformance_mcp, oauthuser_mcp) + servers = (main_mcp, oauthuser_mcp) apps = {server.name: server.streamable_http_app() for server in servers} @contextlib.asynccontextmanager @@ -299,7 +247,6 @@ async def lifespan(_: Starlette) -> AsyncGenerator[None]: expected=f"Bearer {OAUTH_USER_ACCESS_TOKEN}", ), ), - Mount("/conformance", app=apps["e2e-stub-conformance"]), Mount("/", app=apps["e2e-stub"]), ], lifespan=lifespan,