Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(e2e): drive a real Linear OAuth MCP through chat completions under both ingress headers

Tin Chi Lo3cdd6ab9a126
diff --git a/pyproject.toml b/pyproject.toml
index 62bd37c3db6..a448ab042b8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -198,6 +198,7 @@ e2e-dev = [
"playwright==1.61.0",
"websockets>=15.0.1,<16.0",
"locust==2.45.0",
+ "mcp>=1.28.1,<2.0",
]
proxy-dev = [
"prisma==0.11.0",
diff --git a/tests/code_coverage_tests/check_e2e_no_raw_requests.py b/tests/code_coverage_tests/check_e2e_no_raw_requests.py
index e70e83652d1..fe6a77fc26c 100644
--- a/tests/code_coverage_tests/check_e2e_no_raw_requests.py
+++ b/tests/code_coverage_tests/check_e2e_no_raw_requests.py
@@ -2,8 +2,10 @@
raw HTTP client imports (requests, urllib.request, httpx, aiohttp, http.client) are
banned in suite code. Importing requests' exception types for catching is fine
anywhere; a small allowlist grandfathers the files that legitimately make raw calls
-(the transport itself, the root conftest liveness probe, and the claude_code version
-resolver's constant registry URL fetch). Referenced by tests/e2e/CLAUDE.md."""
+(the transport itself, the root conftest liveness probe, the claude_code version
+resolver's constant registry URL fetch, and the mcp OAuth client, whose httpx
+client is the object the official mcp SDK's streamable_http_client requires and so
+cannot go through the sync requests transport). Referenced by tests/e2e/CLAUDE.md."""
from __future__ import annotations
@@ -19,6 +21,7 @@ ALLOWED_RAW_CLIENT_FILES = {
"e2e_http.py": ("requests",),
"conftest.py": ("requests",),
"claude_code/pr_gate_version_resolver.py": ("urllib.request",),
+ "mcp/oauth_chat_client.py": ("httpx",),
}
EXCEPTION_ONLY_NAMES = frozenset({"RequestException", "ConnectionError", "Timeout", "HTTPError"})
diff --git a/tests/e2e/CLAUDE.md b/tests/e2e/CLAUDE.md
index 0e39664e358..17aee22560c 100644
--- a/tests/e2e/CLAUDE.md
+++ b/tests/e2e/CLAUDE.md
@@ -14,7 +14,7 @@ Each subdirectory under `tests/e2e/` is one suite, scoped to an endpoint family
- `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 (API surface; not Playwright)
- `a2a/` - the A2A (agent-to-agent) surface: admin registration via `/v1/agents`, proxy-fronted card discovery at `/.well-known/agent-card.json`, and JSON-RPC `message/send` invocation, driving agents backed by the litellm completion bridge (a real provider) and asserting protocol-version normalization (0.3 vs 1.0)
-- `mcp/` - the MCP server surface over api_key auth against the real Datadog remote MCP server only (see "MCP suite: real Datadog only" below)
+- `mcp/` - the MCP server surface over api_key auth against the real Datadog remote MCP server (see "MCP suite: real Datadog only" below); plus the gateway-managed OAuth (authorization_code) path exercised through `/chat/completions`, the one behavior Datadog's static-header auth cannot reach, seeding the per-user upstream token via the interactive authorize dance driven with the mcp SDK's own OAuth client (headless-browser consent from a saved session) and asserting the completion lists and executes the server's tools with the stored per-user token
- `logging/` - logging-integration delivery (datadog and friends)
- `security/` - secret handling and log-leak protection
- `router/` - routing and reliability behavior (fallbacks, cooldowns)
@@ -33,6 +33,7 @@ Every test under `tests/e2e/mcp/` must exercise the proxy against the real Datad
- Prefer calling real Datadog tools that prove the product path (e.g. `search_datadog_logs` for list/call and permission denials). Seed a unique marker (`e2e-datadog-mcp-*`) in a chat completion when you need a log the tool can find; dual-read with `dd_logs` from conftest when delivery matters
- Delete the MCP server (and any keys) through `resources.defer` the same way every other suite tears down
- If a new MCP behavior cannot be covered with Datadog's tool surface, say so in the PR and get agreement before inventing another upstream; the default is always Datadog
+- The one standing exception is `test_mcp_chat_completion_oauth_e2e.py`. Datadog authenticates with the static `DD-API-KEY` / `DD-APPLICATION-KEY` headers and exposes no authorize/token dance at all, so it cannot exercise gateway-managed OAuth or per-user token seeding in any form. That test drives a real Linear MCP server instead; it is still a real remote upstream, so the no-mock, no-fixture rule above holds unchanged
## Lay the pattern down in a class
diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.py
index e7c48690c0a..4ecc215a22d 100644
--- a/tests/e2e/e2e_config.py
+++ b/tests/e2e/e2e_config.py
@@ -38,6 +38,9 @@ UI_BASE_URL = os.environ.get("E2E_UI_BASE_URL", PROXY_BASE_URL).rstrip("/")
CHEAP_ANTHROPIC_MODEL = os.environ.get("E2E_CHEAP_ANTHROPIC_MODEL", "claude-haiku-4-5")
CHEAP_OPENAI_MODEL = os.environ.get("E2E_CHEAP_OPENAI_MODEL", "gpt-5.5")
+LINEAR_MCP_URL = os.environ.get("E2E_LINEAR_MCP_URL", "https://mcp.linear.app/mcp")
+LINEAR_STORAGE_STATE = os.environ.get("E2E_LINEAR_STORAGE_STATE", "")
+
# Jaeger query API of the compose stack's OTEL trace destination (the `jaeger`
# service in docker-compose.yml maps it to host 16686). Trace-completeness tests
# read exported spans back through it.
diff --git a/tests/e2e/mcp/linear_session_capture.py b/tests/e2e/mcp/linear_session_capture.py
new file mode 100644
index 00000000000..1c867e17e22
--- /dev/null
+++ b/tests/e2e/mcp/linear_session_capture.py
@@ -0,0 +1,58 @@
+"""One-time helper to capture a logged-in Linear browser session for the
+real-Linear MCP e2e test.
+
+The real-Linear test drives the genuine gateway-managed authorization_code
+dance against ``mcp.linear.app``. The only step that cannot be scripted is
+Linear's login (magic link / SSO), so a human authenticates once here and the
+resulting session (cookies + local storage) is persisted to disk. The e2e test
+then loads that session in a headless Playwright context and clicks Approve on
+Linear's consent screen every run, with no human and no login automation.
+
+Run it with the e2e venv, log into Linear in the window that opens, then return
+to the terminal and press Enter:
+
+ LITELLM=~/litellm-mcpe2e
+ "$LITELLM"/.venv/bin/python "$LITELLM"/tests/e2e/mcp/linear_session_capture.py
+
+The session is written to ``E2E_LINEAR_STORAGE_STATE`` (default
+``~/.litellm-e2e/linear_storage_state.json``), outside the repo. It is a
+secret: never commit it. Re-run this whenever Linear expires the session.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+DEFAULT_STATE_PATH = Path.home() / ".litellm-e2e" / "linear_storage_state.json"
+
+
+def capture(state_path: Path) -> None:
+ """Open a headed browser at Linear, wait for the human to log in, then save
+ the authenticated session to ``state_path``."""
+ state_path.parent.mkdir(parents=True, exist_ok=True)
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless=False)
+ context = browser.new_context()
+ page = context.new_page()
+ page.goto("https://linear.app/login", wait_until="domcontentloaded")
+ print("\n" + "=" * 72)
+ print("Log into Linear in the browser window that just opened.")
+ print("If Linear emails you a magic link, paste the link into THIS window's")
+ print("address bar (opening it in your default browser won't capture the")
+ print("session). Google SSO works too as long as you complete it here.")
+ print("When your Linear workspace has loaded, come back and press Enter.")
+ print("=" * 72)
+ input("Press Enter once you are logged in... ")
+ page.goto("https://mcp.linear.app/", wait_until="domcontentloaded")
+ context.storage_state(path=str(state_path))
+ browser.close()
+ print(f"\nSaved Linear session to {state_path}")
+ print("Point the e2e test at it with:")
+ print(f' export E2E_LINEAR_STORAGE_STATE="{state_path}"')
+
+
+if __name__ == "__main__":
+ capture(Path(os.environ.get("E2E_LINEAR_STORAGE_STATE", str(DEFAULT_STATE_PATH))))
diff --git a/tests/e2e/mcp/oauth_chat_client.py b/tests/e2e/mcp/oauth_chat_client.py
new file mode 100644
index 00000000000..2eaf512cfa5
--- /dev/null
+++ b/tests/e2e/mcp/oauth_chat_client.py
@@ -0,0 +1,271 @@
+"""Client for the mcp chat-completion OAuth e2e suite.
+
+Registers a gateway-managed OAuth (authorization_code) MCP server, seeds the
+per-user upstream token by driving the interactive authorize dance with the
+official mcp SDK's OAuthClientProvider (the browser leg is a headless Chromium
+primed with a human's saved Linear session), then exercises the server through
+/chat/completions, where the gateway lists and executes its tools with the
+stored per-user token.
+
+Management routes (/v1/mcp/server CRUD, /chat/completions) go through the
+shared ProxyClient transport. The MCP protocol used to seed the token goes through
+the mcp SDK, the same library production MCP hosts run.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+import time
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+from urllib.parse import parse_qsl
+
+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 e2e_config import PROXY_BASE_URL, REQUEST_TIMEOUT
+from proxy_client import ProxyClient
+from e2e_http import AuthHeaders, NoBody, unwrap
+from models import ChatBody, ChatResponse, McpServerCreateBody, McpServerInfo
+
+if TYPE_CHECKING:
+ from playwright.async_api import Route
+
+# Where the "browser" lands at the end of the authorize dance. Nothing listens
+# here: the route interceptor short-circuits the final redirect and reads the
+# code/state off its query string, exactly like a desktop MCP host intercepting
+# its loopback redirect.
+OAUTH_CLIENT_REDIRECT_URI = "http://127.0.0.1:53682/e2e/callback"
+BROWSER_CONSENT_TIMEOUT = 60.0
+
+
+def _mcp_url(alias: str) -> str:
+ return f"{PROXY_BASE_URL}/{alias}/mcp"
+
+
+class InMemoryTokenStorage:
+ """The mcp SDK's TokenStorage protocol, in memory for one dance: the
+ DCR-registered client and the gateway tokens 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 _browser_follow_authorize(start_url: str, storage_state_path: str) -> tuple[str, str | None]:
+ """Play the browser's role for a real upstream whose authorize endpoint
+ serves an interactive consent page (Linear). A headless Chromium primed
+ with a human's saved Linear session opens the gateway authorize URL and
+ clicks through Linear's consent screens (the mcp.linear.app Approve form,
+ then the linear.app workspace-selection page), riding the rest of the chain
+ (Linear -> gateway callback -> host redirect_uri). The final hop is
+ intercepted and short-circuited, since nothing listens there, and its
+ code/state are read off the query string."""
+ from playwright.async_api import async_playwright
+
+ captured: dict[str, str] = {} # mutable-ok: hand-off from the request listener
+ trail: list[str] = [] # mutable-ok: navigation diagnostics for a failed dance
+
+ def _note_request(request: object) -> None:
+ url = getattr(request, "url", "")
+ if url.startswith(OAUTH_CLIENT_REDIRECT_URI) and "url" not in captured:
+ captured["url"] = url
+
+ async def _swallow_redirect(route: "Route") -> None:
+ await route.fulfill(status=200, content_type="text/plain", body="ok")
+
+ async with async_playwright() as playwright:
+ browser = await playwright.chromium.launch(headless=True)
+ context = await browser.new_context(storage_state=storage_state_path)
+ await context.route(re.compile(re.escape(OAUTH_CLIENT_REDIRECT_URI) + r".*"), _swallow_redirect)
+ page = await context.new_page()
+ page.on("request", _note_request)
+ page.on("framenavigated", lambda frame: trail.append(frame.url.split("?", 1)[0]))
+ await page.goto(start_url, wait_until="domcontentloaded")
+ deadline = time.monotonic() + BROWSER_CONSENT_TIMEOUT
+ while "url" not in captured and time.monotonic() < deadline:
+ try:
+ await page.wait_for_load_state("networkidle", timeout=8000)
+ except Exception: # noqa: BLE001 - a busy consent page never idles; fall through and try to advance it
+ pass
+ if "url" in captured:
+ break
+ control = page.locator(
+ 'button[name="action"][value="approve"], button:has-text("Authorize"), '
+ 'button:has-text("Allow"), button:has-text("@"), a:has-text("@")'
+ ).first
+ try:
+ await control.click(timeout=5000)
+ except Exception: # noqa: BLE001 - nothing to advance yet; loop and re-check
+ await asyncio.sleep(0.5)
+ final_url = page.url
+ await browser.close()
+
+ landing = captured.get("url")
+ assert landing is not None, (
+ f"consent flow never reached {OAUTH_CLIENT_REDIRECT_URI}; "
+ f"final={final_url.split('?', 1)[0]!r}; trail={trail[-6:]}"
+ )
+ params = dict(parse_qsl(httpx.URL(landing).query.decode()))
+ assert "code" in params, f"client redirect_uri carried no code: {landing}"
+ return params["code"], params.get("state")
+
+
+def _oauth_provider(url: str, storage: InMemoryTokenStorage, storage_state_path: str) -> OAuthClientProvider:
+ """The SDK's real OAuth machinery (RFC 9728/8414 discovery, RFC 7591 DCR,
+ PKCE, token exchange) with the browser leg driven by Playwright against the
+ upstream's consent screen."""
+ 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 _browser_follow_authorize(authorize_url, storage_state_path)
+ 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 SDK request
+ (discovery, DCR, token exchange), so 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."""
+
+ 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 _seed_via_dance(
+ url: str, headers: dict[str, str], storage: InMemoryTokenStorage, storage_state_path: str
+) -> tuple[str, ...]:
+ async with _oauth_http_client(headers, _oauth_provider(url, storage, storage_state_path)) 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))
+
+
+@dataclass(frozen=True, slots=True)
+class ChatMcpClient:
+ proxy: ProxyClient
+
+ def create_server(self, body: McpServerCreateBody) -> McpServerInfo:
+ return unwrap(
+ self.proxy.transport.post(
+ "/v1/mcp/server",
+ headers=self.proxy.transport.master,
+ json=body,
+ response_type=McpServerInfo,
+ )
+ )
+
+ def server_info(self, server_id: str) -> McpServerInfo:
+ return unwrap(
+ self.proxy.transport.get(
+ f"/v1/mcp/server/{server_id}",
+ headers=self.proxy.transport.master,
+ params=NoBody(),
+ response_type=McpServerInfo,
+ )
+ )
+
+ def delete_server(self, server_id: str) -> None:
+ _ = self.proxy.transport.delete(
+ f"/v1/mcp/server/{server_id}",
+ headers=self.proxy.transport.master,
+ json=NoBody(),
+ response_type=NoBody,
+ )
+
+ def seed_user_token(self, alias: str, key: str, storage_state_path: str) -> tuple[str, ...]:
+ """Drive the interactive authorize dance for `key`'s user so the gateway
+ stores their upstream token, retried to the shared deadline since the
+ just-created server and key propagate asynchronously. The LiteLLM key
+ rides x-litellm-api-key so the gateway binds the token to that user.
+ Returns the upstream tool names the dance listed, proof the token works."""
+ headers = {"x-litellm-api-key": f"Bearer {key}"}
+ storage = InMemoryTokenStorage()
+ deadline = time.monotonic() + self.proxy.poll_timeout
+ last_error: Exception | None = None
+ while time.monotonic() < deadline:
+ try:
+ return asyncio.run(_seed_via_dance(_mcp_url(alias), headers, storage, storage_state_path))
+ except Exception as exc: # noqa: BLE001 - retried to the deadline; the last error surfaces below
+ last_error = exc
+ time.sleep(self.proxy.poll_interval)
+ pytest.fail(
+ f"authorize dance for {alias!r} never completed within {self.proxy.poll_timeout}s; "
+ f"last error: {last_error!r}"
+ )
+
+ def chat_with_mcp(self, headers: AuthHeaders, body: ChatBody) -> ChatResponse:
+ """POST /chat/completions carrying the LiteLLM key in `headers` (either
+ ingress form) with an MCP server attached in `body.tools`. The gateway
+ resolves the user from the key and lists/executes the server's tools
+ with that user's stored upstream token."""
+ return unwrap(
+ self.proxy.transport.post(
+ "/chat/completions",
+ headers=headers,
+ json=body,
+ response_type=ChatResponse,
+ )
+ )
+
+
+def build_chat_client(proxy: ProxyClient) -> ChatMcpClient:
+ return ChatMcpClient(proxy=proxy)
diff --git a/tests/e2e/mcp/test_mcp_chat_completion_oauth_e2e.py b/tests/e2e/mcp/test_mcp_chat_completion_oauth_e2e.py
new file mode 100644
index 00000000000..01e94f7b86f
--- /dev/null
+++ b/tests/e2e/mcp/test_mcp_chat_completion_oauth_e2e.py
@@ -0,0 +1,197 @@
+"""On-demand e2e: a chat completion drives a gateway-managed OAuth MCP server.
+
+The real end-user flow for MCP over an OAuth server: a user registers a Linear
+authorization_code server, authorizes it once so the gateway stores their
+upstream token, then sends a normal /chat/completions request with the Linear
+MCP attached. The gateway resolves the user from the LiteLLM key, lists Linear's
+tools with the stored per-user token, lets the model call one, executes it
+upstream with that token, and returns the answer. This is proven against the
+real Linear MCP server (mcp.linear.app) and a real Anthropic model, once per
+documented ingress header (x-litellm-api-key and Authorization).
+
+The authorize dance is seeded through the mcp SDK's OAuthClientProvider; the one
+step Linear cannot auto-approve is the human consent, so it is captured once out
+of band (mcp/linear_session_capture.py) into a saved browser session and a
+headless Chromium clicks Approve every run. The test therefore skips unless
+E2E_LINEAR_STORAGE_STATE points at that session, so it never runs on the per-PR
+CI path; it is a nightly/on-demand real-server smoke test.
+
+Fail-before-fix: without the stored per-user token the gateway lists no Linear
+tools, so mcp_list_tools comes back empty, nothing is called, and the
+assertions fail; a served, called, non-empty Linear tool proves the gateway
+pulled and used the user's token.
+"""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+
+from e2e_config import CHEAP_ANTHROPIC_MODEL, LINEAR_MCP_URL, LINEAR_STORAGE_STATE, unique_marker
+from e2e_http import AuthHeaders
+from lifecycle import ResourceManager
+from models import ChatBody, ChatMessage, KeyGenerateBody, McpChatTool, McpServerCreateBody, ObjectPermission
+from proxy_client import ProxyClient
+
+pytest.importorskip("mcp", reason="mcp SDK not installed; run `uv sync --inexact --group e2e-dev`")
+pytest.importorskip(
+ "playwright.async_api",
+ reason="playwright not installed; run `uv pip install playwright` and `playwright install chromium`",
+)
+
+from oauth_chat_client import ChatMcpClient, build_chat_client # noqa: E402 # imports follow the importorskip guards
+
+pytestmark = [
+ pytest.mark.e2e,
+ pytest.mark.skipif(
+ not LINEAR_STORAGE_STATE or not os.path.exists(LINEAR_STORAGE_STATE),
+ reason="set E2E_LINEAR_STORAGE_STATE to a Linear session captured via mcp/linear_session_capture.py",
+ ),
+]
+
+# Pinned from a live dance during verification (never guessed); the gateway
+# prefixes every upstream tool name with the server alias. list_teams is a
+# read-only Linear tool that takes no arguments and returns the caller's teams.
+LINEAR_READONLY_TOOL = "list_teams"
+LINEAR_PROMPT = "Use the list_teams tool to list my Linear teams, then reply with the name of one of them."
+
+
[email protected](scope="session")
+def chat_client(proxy: ProxyClient) -> ChatMcpClient:
+ return build_chat_client(proxy)
+
+
+class TestMcpChatCompletionOauth:
+ """A scoped internal-user key on a real Linear authorization_code server,
+ used through /chat/completions once per ingress header: the gateway pulls
+ the user's stored upstream token, lists and executes Linear's tools during
+ the completion, and returns the answer."""
+
+ @pytest.mark.covers("mcp.list_tools.oauth.succeeds")
+ @pytest.mark.covers("mcp.call_tool.oauth.succeeds")
+ def test_chat_completion_uses_linear_with_x_litellm_api_key_header(
+ self, chat_client: ChatMcpClient, resources: ResourceManager
+ ) -> None:
+ marker = unique_marker()
+ alias = f"e2elinear{marker}"
+ created = chat_client.create_server(
+ McpServerCreateBody(
+ alias=alias,
+ url=LINEAR_MCP_URL,
+ allow_all_keys=False,
+ auth_type="oauth2",
+ oauth2_flow="authorization_code",
+ )
+ )
+ resources.defer(lambda: chat_client.delete_server(created.server_id))
+
+ stored = chat_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 = chat_client.proxy.generate_key(
+ KeyGenerateBody(
+ user_id="e2e-test-user",
+ object_permission=ObjectPermission(mcp_servers=[created.server_id]),
+ )
+ )
+ resources.defer(lambda: chat_client.proxy.delete_key(key))
+
+ seeded = chat_client.seed_user_token(alias, key, LINEAR_STORAGE_STATE)
+ assert f"{alias}-{LINEAR_READONLY_TOOL}" in seeded, (
+ f"the authorize dance listed {seeded}, expected it to include {alias}-{LINEAR_READONLY_TOOL}"
+ )
+
+ response = chat_client.chat_with_mcp(
+ AuthHeaders.model_validate({"x-litellm-api-key": f"Bearer {key}"}),
+ ChatBody(
+ model=CHEAP_ANTHROPIC_MODEL,
+ messages=[ChatMessage(role="user", content=LINEAR_PROMPT)],
+ tools=[
+ McpChatTool(
+ server_url=f"litellm_proxy/mcp/{alias}",
+ server_label=alias,
+ require_approval="never",
+ )
+ ],
+ ),
+ )
+
+ message = response.choices[0].message
+ assert message is not None and message.content, f"completion returned no answer: {response}"
+ meta = message.provider_specific_fields
+ assert meta is not None, f"no MCP metadata on the completion: {response}"
+ listed = {t.function.name for t in (meta.mcp_list_tools or []) if t.function}
+ assert f"{alias}-{LINEAR_READONLY_TOOL}" in listed, (
+ f"the gateway listed {sorted(listed)}, expected the stored token to surface {alias}-{LINEAR_READONLY_TOOL}"
+ )
+ results = [r for r in (meta.mcp_call_results or []) if r.name == f"{alias}-{LINEAR_READONLY_TOOL}"]
+ assert results and results[0].result, (
+ f"Linear tool {alias}-{LINEAR_READONLY_TOOL} was not executed with a result: {meta.mcp_call_results}"
+ )
+
+ @pytest.mark.covers("mcp.list_tools.oauth.succeeds")
+ @pytest.mark.covers("mcp.call_tool.oauth.succeeds")
+ def test_chat_completion_uses_linear_with_authorization_bearer_header(
+ self, chat_client: ChatMcpClient, resources: ResourceManager
+ ) -> None:
+ marker = unique_marker()
+ alias = f"e2elinear{marker}"
+ created = chat_client.create_server(
+ McpServerCreateBody(
+ alias=alias,
+ url=LINEAR_MCP_URL,
+ allow_all_keys=False,
+ auth_type="oauth2",
+ oauth2_flow="authorization_code",
+ )
+ )
+ resources.defer(lambda: chat_client.delete_server(created.server_id))
+
+ stored = chat_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 = chat_client.proxy.generate_key(
+ KeyGenerateBody(
+ user_id="e2e-test-user",
+ object_permission=ObjectPermission(mcp_servers=[created.server_id]),
+ )
+ )
+ resources.defer(lambda: chat_client.proxy.delete_key(key))
+
+ seeded = chat_client.seed_user_token(alias, key, LINEAR_STORAGE_STATE)
+ assert f"{alias}-{LINEAR_READONLY_TOOL}" in seeded, (
+ f"the authorize dance listed {seeded}, expected it to include {alias}-{LINEAR_READONLY_TOOL}"
+ )
+
+ response = chat_client.chat_with_mcp(
+ AuthHeaders.model_validate({"authorization": f"Bearer {key}"}),
+ ChatBody(
+ model=CHEAP_ANTHROPIC_MODEL,
+ messages=[ChatMessage(role="user", content=LINEAR_PROMPT)],
+ tools=[
+ McpChatTool(
+ server_url=f"litellm_proxy/mcp/{alias}",
+ server_label=alias,
+ require_approval="never",
+ )
+ ],
+ ),
+ )
+
+ message = response.choices[0].message
+ assert message is not None and message.content, f"completion returned no answer: {response}"
+ meta = message.provider_specific_fields
+ assert meta is not None, f"no MCP metadata on the completion: {response}"
+ listed = {t.function.name for t in (meta.mcp_list_tools or []) if t.function}
+ assert f"{alias}-{LINEAR_READONLY_TOOL}" in listed, (
+ f"the gateway listed {sorted(listed)}, expected the stored token to surface {alias}-{LINEAR_READONLY_TOOL}"
+ )
+ results = [r for r in (meta.mcp_call_results or []) if r.name == f"{alias}-{LINEAR_READONLY_TOOL}"]
+ assert results and results[0].result, (
+ f"Linear tool {alias}-{LINEAR_READONLY_TOOL} was not executed with a result: {meta.mcp_call_results}"
+ )
diff --git a/tests/e2e/models.py b/tests/e2e/models.py
index b3ea9346180..d21920cf848 100644
--- a/tests/e2e/models.py
+++ b/tests/e2e/models.py
@@ -6,6 +6,7 @@ response validates without mirroring every proxy field. No untyped dicts.
from __future__ import annotations
+from collections.abc import Sequence
from datetime import datetime
from typing import Literal
@@ -196,6 +197,19 @@ class ChatTool(BaseModel):
function: ChatToolFunction
+class McpChatTool(BaseModel):
+ """An MCP server attached to a chat completion (OpenAI `type: "mcp"` tool).
+ `server_url` selects the gateway-registered server by its alias suffix; with
+ `require_approval="never"` the gateway lists, calls, and feeds the server's
+ tools back to the model in one agentic turn."""
+
+ type: Literal["mcp"] = "mcp"
+ server_url: str
+ require_approval: str
+ server_label: str | None = None
+ allowed_tools: list[str] | None = None
+
+
class ChatBody(BaseModel):
model: str
messages: list[ChatMessage]
@@ -206,7 +220,7 @@ class ChatBody(BaseModel):
reasoning_effort: str | None = None
thinking: ThinkingParam | None = None
service_tier: str | None = None
- tools: list[ChatTool] | None = None
+ tools: Sequence[ChatTool | McpChatTool] | None = None
tool_choice: str | None = None
guardrails: list[str] | None = None
response_format: dict[str, object] | None = None
@@ -242,10 +256,46 @@ class ToolCall(BaseModel):
function: ToolCallFunction = ToolCallFunction()
+class McpToolFunctionRef(BaseModel):
+ name: str
+
+
+class McpListedTool(BaseModel):
+ """One entry of `mcp_list_tools`: a tool the gateway listed from the
+ attached MCP server and exposed to the model, in OpenAI function shape."""
+
+ function: McpToolFunctionRef | None = None
+
+
+class McpToolCall(BaseModel):
+ """One entry of `mcp_tool_calls`: a tool the model asked the gateway to run."""
+
+ function: McpToolFunctionRef | None = None
+
+
+class McpCallResult(BaseModel):
+ """One entry of `mcp_call_results`: what the gateway got back from executing
+ a tool upstream on the caller's behalf."""
+
+ name: str | None = None
+ result: str | None = None
+
+
+class McpResponseMetadata(BaseModel):
+ """`choices[].message.provider_specific_fields` MCP section: which tools the
+ gateway listed from the attached server, which the model called, and their
+ results. Populated only when the completion drove an MCP server."""
+
+ mcp_list_tools: list[McpListedTool] | None = None
+ mcp_tool_calls: list[McpToolCall] | None = None
+ mcp_call_results: list[McpCallResult] | None = None
+
+
class OutMessage(BaseModel):
content: str | None = None
reasoning_content: str | None = None
tool_calls: list[ToolCall] | None = None
+ provider_specific_fields: McpResponseMetadata | None = None
class ChatChoice(BaseModel):
@@ -355,6 +405,36 @@ class CountTokensResponse(BaseModel):
input_tokens: int
+# ---------- mcp servers ----------
+
+
+class McpServerCreateBody(BaseModel):
+ """POST /v1/mcp/server. For a gateway-managed OAuth server, `auth_type` is
+ `oauth2` and `oauth2_flow` is `authorization_code`; the upstream endpoints
+ are discovered and registered via DCR when left unset. `allow_all_keys`
+ false scopes the server to keys granted it through object_permission."""
+
+ alias: str
+ url: str
+ transport: str = "http"
+ allow_all_keys: bool = True
+ auth_type: str | None = None
+ oauth2_flow: Literal["client_credentials", "authorization_code"] | None = None
+ authorization_url: str | None = None
+ token_url: str | 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
+ auth_type: str | None = None
+ oauth2_flow: str | None = None
+ allow_all_keys: bool | None = None
+
+
class EmbedBody(BaseModel):
model: str
input: str
diff --git a/uv.lock b/uv.lock
index b3d6fccff26..9c60ca1ee48 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4301,6 +4301,7 @@ dev = [
]
e2e-dev = [
{ name = "locust" },
+ { name = "mcp" },
{ name = "playwright" },
{ name = "websockets" },
]
@@ -4478,6 +4479,7 @@ dev = [
]
e2e-dev = [
{ name = "locust", specifier = "==2.45.0" },
+ { name = "mcp", specifier = ">=1.28.1,<2.0" },
{ name = "playwright", specifier = "==1.61.0" },
{ name = "websockets", specifier = ">=15.0.1,<16.0" },
]