Skip to content
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
5edc486
test(e2e): cover MCP gateway auth headers and per-server max concurrency
tin-berri Jul 13, 2026
d74cf13
fix(e2e): restore uv.lock exclude-newer anchor and gate proxy startup…
tin-berri Jul 13, 2026
565a872
refactor(e2e): inline the concurrency burst in the test via a thread …
tin-berri Jul 13, 2026
23dffc7
fix(e2e): use a plain union assignment instead of a PEP 695 type stat…
tin-berri Jul 13, 2026
ff3ef9d
refactor(e2e): keep the concurrency test self-contained with local tu…
tin-berri Jul 13, 2026
9ff988d
refactor(e2e): split the mcp gateway suite into feature-scoped specs …
tin-berri Jul 15, 2026
d32974c
refactor(e2e): build wire headers and mint keys inline in the mcp tes…
tin-berri Jul 15, 2026
b1442d0
refactor(e2e): unroll the auth-header matrix into explicitly named pe…
tin-berri Jul 15, 2026
1b42f65
test(e2e): cover the interactive authorization_code MCP OAuth flow en…
tin-berri Jul 15, 2026
c1e5ca7
test(e2e): run the official MCP conformance suite through the gateway…
tin-berri Jul 15, 2026
6c0d405
refactor(e2e): scope the mcp suite to the core happy paths, keeping t…
tin-berri Jul 15, 2026
9fb7271
refactor(e2e): name the interactive OAuth test as the list-and-call h…
tin-berri Jul 15, 2026
9b144f1
test(e2e): run the list-and-call happy path through the interactive O…
tin-berri Jul 15, 2026
5880135
test(e2e): assert the server record round-trips in the ingress reject…
tin-berri Jul 16, 2026
4fba2f4
refactor(e2e): make the Authorization-header OAuth test a challenge-g…
tin-berri Jul 16, 2026
644d1ec
test(e2e): a stored per-user token lets the key in Authorization list…
tin-berri Jul 17, 2026
b92b7cc
refactor(e2e): drop the unused conformance/prompts/resources foundation
tin-berri Jul 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion tests/e2e/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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)
Expand Down Expand Up @@ -107,7 +108,7 @@ MCPs - endpoint features with the protocol op as the variant
mcp.<operation>.<auth_family>.<assertion>
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
```

Expand Down
56 changes: 56 additions & 0 deletions tests/e2e/coverage_registry/mcp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -79,6 +95,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
Expand Down Expand Up @@ -111,3 +135,35 @@
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
- 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
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
14 changes: 13 additions & 1 deletion tests/e2e/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -166,7 +168,17 @@ services:
target: /app/config.yaml
command: ["--config", "/app/config.yaml", "--port", "4000"]

# throwaway db
mcp-stub:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dont need

build: ./mcp/stub
ports:
- "8765:8765"
healthcheck:
test: ["CMD", "python", "-c", "import socket; socket.create_connection(('localhost', 8765), timeout=2)"]
interval: 3s
timeout: 3s
retries: 20
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

# throwaway db
db:
image: postgres:16
environment:
Expand Down
27 changes: 27 additions & 0 deletions tests/e2e/e2e_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,33 @@
# 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")

# 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_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"

# 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"))
Expand Down
88 changes: 88 additions & 0 deletions tests/e2e/mcp/auth_forwarder.py
Original file line number Diff line number Diff line change
@@ -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 <key>`, 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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no httpx, use the tests/e2e/claude.md

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)
19 changes: 19 additions & 0 deletions tests/e2e/mcp/conftest.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading