Skip to content

Build and run agents you can see, understand and trust.

feat(mcp): support runtime MCP headers in Docker workspaces (#2456)

qbc0b61e4f58211
diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.py
index 744e95b1f..820572314 100644
--- a/src/agentscope/mcp/_mcp_client.py
+++ b/src/agentscope/mcp/_mcp_client.py
@@ -2,15 +2,22 @@
"""Unified MCP client implementation for AgentScope."""
import asyncio
import re
-from contextlib import AsyncExitStack, _AsyncGeneratorContextManager
-from typing import Any, TYPE_CHECKING
+from contextlib import (
+ AbstractAsyncContextManager,
+ asynccontextmanager,
+ AsyncExitStack,
+)
+from typing import Any, AsyncGenerator, ClassVar, TYPE_CHECKING
from urllib.parse import urlsplit
import httpx
import mcp.types
from mcp import ClientSession, stdio_client, StdioServerParameters
from mcp.client.sse import sse_client
-from mcp.client.streamable_http import streamable_http_client
+from mcp.client.streamable_http import (
+ create_mcp_http_client,
+ streamable_http_client,
+)
from pydantic import Field, BaseModel, PrivateAttr
from ._config import StdioMCPConfig, HttpMCPConfig
@@ -38,6 +45,9 @@ class MCPClient(BaseModel):
- _stack: AsyncExitStack for managing connection lifecycle
- _is_connected: Connection state flag
- _cached_tools: Cached list of tools
+ - _http_client: The live HTTP client, while one is open
+ - _static_headers: Its headers before any runtime override
+ - _runtime_headers: See :meth:`set_runtime_headers`
Example:
@@ -68,6 +78,18 @@ class MCPClient(BaseModel):
"""
+ # httpx derives these from the request URL and body with setdefault,
+ # so a client-level value silently wins and breaks routing or framing.
+ # The headers MCP itself sends are set per request and need no guard.
+ _RESERVED_HEADERS: ClassVar[frozenset[str]] = frozenset(
+ {"connection", "content-length", "host", "transfer-encoding"},
+ )
+ # RFC 7230 token, and a field value of visible ASCII plus tab.
+ _HEADER_NAME: ClassVar[re.Pattern[str]] = re.compile(
+ r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+",
+ )
+ _HEADER_VALUE: ClassVar[re.Pattern[str]] = re.compile(r"[\t\x20-\x7e]*")
+
name: str = Field(
title="MCP Name",
description="The MCP name.",
@@ -106,6 +128,9 @@ class MCPClient(BaseModel):
_stack: AsyncExitStack | None = PrivateAttr(default=None)
_is_connected: bool = PrivateAttr(default=False)
_cached_tools: list[mcp.types.Tool] | None = PrivateAttr(default=None)
+ _http_client: httpx.AsyncClient | None = PrivateAttr(default=None)
+ _static_headers: httpx.Headers | None = PrivateAttr(default=None)
+ _runtime_headers: dict[str, str] = PrivateAttr(default_factory=dict)
@property
def is_connected(self) -> bool:
@@ -182,35 +207,112 @@ class MCPClient(BaseModel):
def _create_http_client(
self,
- ) -> _AsyncGeneratorContextManager[Any]:
+ ) -> AbstractAsyncContextManager[Any]:
"""Create an HTTP MCP client (SSE or streamable HTTP)."""
config = self.mcp_config
-
- # Determine transport from the URL *path* only. Inspecting the full
- # URL with endswith would misdetect SSE endpoints whose URL carries
- # a query string (e.g. https://mcp.amap.com/sse?key=API_KEY): such
- # URLs no longer end with '/sse' and would fall through to the
- # streamable HTTP transport, which then fails to handshake against
- # an SSE server with 'Session terminated'.
- path = urlsplit(config.url).path
- if path.endswith("/sse") or path.endswith("/messages/"):
+ if self._is_sse:
return sse_client(
url=config.url,
headers=config.headers,
timeout=config.timeout,
)
- # StreamableHTTP transport
- http_client = None
+ return self._create_streamable_http_client()
+
+ @property
+ def _is_sse(self) -> bool:
+ """Whether the configured URL points at the SSE transport. Only
+ the path is inspected, so a query string (``/sse?key=...``) still
+ resolves to SSE rather than falling through to streamable HTTP.
+ """
+ path = urlsplit(self.mcp_config.url).path
+ return path.endswith("/sse") or path.endswith("/messages/")
+
+ @asynccontextmanager
+ async def _create_streamable_http_client(
+ self,
+ ) -> AsyncGenerator[Any, None]:
+ """Create an owned HTTP client that runtime headers can update."""
+ config = self.mcp_config
if config.headers or config.timeout:
- http_client = httpx.AsyncClient(
+ client = httpx.AsyncClient(
headers=config.headers,
timeout=config.timeout,
)
- return streamable_http_client(
- url=config.url,
- http_client=http_client,
- )
+ else:
+ client = create_mcp_http_client()
+ # Snapshot before overlaying: clearing runtime headers restores it.
+ self._static_headers = httpx.Headers(client.headers)
+ client.headers.update(self._runtime_headers)
+ self._http_client = client
+
+ try:
+ async with client:
+ async with streamable_http_client(
+ url=config.url,
+ http_client=client,
+ ) as transport:
+ yield transport
+ finally:
+ if self._http_client is client:
+ self._http_client = None
+
+ async def set_runtime_headers(
+ self,
+ headers: dict[str, str],
+ ) -> None:
+ """Replace the headers sent with subsequent HTTP requests.
+
+ The map is replaced rather than merged: an empty map drops all
+ runtime overrides, so the static headers from :attr:`mcp_config`
+ apply again. Runtime headers are live instance state, excluded
+ from ``model_dump`` and workspace persistence.
+
+ The update reaches the next outbound request without reconnecting.
+ Two things it cannot reach: a call already under way, which keeps
+ the snapshot it started with, and the long-lived GET stream of a
+ Streamable HTTP session, whose headers are fixed when the stream
+ is established. Headers MCP sends itself (``mcp-session-id``,
+ ``content-type``, ...) are set per request and always win over
+ the ones set here; the few httpx derives from the URL and body
+ are rejected outright.
+
+ Args:
+ headers (`dict[str, str]`):
+ The complete runtime header map. An empty dict clears it.
+
+ Raises:
+ `ValueError`:
+ The client is not Streamable HTTP, or a header is
+ invalid or owned by the HTTP layer.
+ """
+ if self.mcp_config.type != "http_mcp" or self._is_sse:
+ raise ValueError(
+ "Runtime headers require a Streamable HTTP MCP client.",
+ )
+ if not isinstance(headers, dict):
+ raise ValueError("Runtime headers must be a dict.")
+
+ # httpx accepts illegal names and CRLF in values, and only h11
+ # rejects them mid-request, so validate before storing.
+ for name, value in headers.items():
+ if (
+ not isinstance(name, str)
+ or not isinstance(value, str)
+ or not self._HEADER_NAME.fullmatch(name)
+ or not self._HEADER_VALUE.fullmatch(value)
+ ):
+ raise ValueError(f"Runtime header {name!r} is invalid.")
+ if name.lower() in self._RESERVED_HEADERS:
+ raise ValueError(
+ f"Runtime header {name!r} is owned by the HTTP layer.",
+ )
+
+ self._runtime_headers = dict(headers)
+ if self._http_client is not None:
+ merged = httpx.Headers(self._static_headers)
+ merged.update(self._runtime_headers)
+ self._http_client.headers = merged
async def connect(self) -> None:
"""Connect to the MCP server (for stateful connections only).
@@ -310,7 +412,7 @@ class MCPClient(BaseModel):
self._is_connected = False
logger.info("MCP closed: %s", self.name)
- def _get_client_gen(self) -> _AsyncGeneratorContextManager[Any]:
+ def _get_client_gen(self) -> AbstractAsyncContextManager[Any]:
"""Get client generator for stateless connections."""
if self.mcp_config.type == "stdio_mcp":
return self._client
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.py
index e61463912..67f6e0acf 100644
--- a/src/agentscope/tool/_adapters.py
+++ b/src/agentscope/tool/_adapters.py
@@ -3,7 +3,7 @@
import inspect
import json
import re
-from contextlib import _AsyncGeneratorContextManager
+from contextlib import AbstractAsyncContextManager
from datetime import timedelta
from typing import Callable, Any, AsyncGenerator, Generator
@@ -209,7 +209,7 @@ class MCPTool(ToolBase):
self,
mcp_name: str,
tool: mcp.types.Tool,
- client_gen: Callable[..., _AsyncGeneratorContextManager[Any]]
+ client_gen: Callable[..., AbstractAsyncContextManager[Any]]
| None = None,
session: Any | None = None,
timeout: float | None = None,
@@ -222,7 +222,7 @@ class MCPTool(ToolBase):
The name of the MCP server instance.
tool (`mcp.types.Tool`):
The MCP tool definition.
- client_gen (`Callable[..., _AsyncGeneratorContextManager[Any]] \
+ client_gen (`Callable[..., AbstractAsyncContextManager[Any]] \
| None`, optional):
The MCP client generator function for stateless clients.
Either this or ``session`` must be provided.
diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.py
index e2c164cf6..c9b4945df 100644
--- a/src/agentscope/workspace/_gateway_client.py
+++ b/src/agentscope/workspace/_gateway_client.py
@@ -182,6 +182,7 @@ class GatewayMCPClient(MCPClient):
is never called — no stdio context manager is built).
* ``connect`` registers the MCP on the gateway via ``POST /mcps``.
* ``close`` deregisters via ``DELETE /mcps/{name}``.
+ * ``set_runtime_headers`` updates the registered live client.
* ``list_raw_tools`` / ``get_tool`` fetch and wrap upstream tools.
"""
@@ -252,6 +253,10 @@ class GatewayMCPClient(MCPClient):
)
assert self._gateway is not None
body = self.model_dump(mode="json")
+ if self._runtime_headers:
+ # model_dump cannot carry them, and the gateway connects to
+ # the MCP server inside this request.
+ body["runtime_headers"] = self._runtime_headers
status, resp_body = await self._gateway.exec_request(
"POST",
"/mcps",
@@ -302,6 +307,58 @@ class GatewayMCPClient(MCPClient):
raise
self._is_connected = False
+ async def set_runtime_headers(
+ self,
+ headers: dict[str, str],
+ ) -> None:
+ """Replace headers on the registered gateway-side MCP client.
+
+ Unlike a local client, the proxy must already be connected so that
+ the live client exists in the workspace. :meth:`connect` sends them
+ with the registration, so they survive a reconnect.
+
+ Args:
+ headers (`dict[str, str]`):
+ The complete runtime header map. An empty dict clears it.
+
+ Raises:
+ `ValueError`:
+ The gateway rejects an invalid or unsupported header update.
+ `RuntimeError`:
+ The proxy is not connected or the gateway request fails.
+ """
+ if not self._is_connected:
+ raise RuntimeError(
+ f"MCP {self.name!r} is not connected. Call connect() first.",
+ )
+ assert self._gateway is not None
+ status, body = await self._gateway.exec_request(
+ "PUT",
+ f"/mcps/{self.name}/runtime-headers",
+ params={
+ "agent_id": self._agent_id,
+ "session_id": self._session_id,
+ },
+ body={"headers": headers},
+ )
+ if status == 404:
+ raise RuntimeError(
+ f"gateway has no runtime-headers route, or no live client "
+ f"for MCP {self.name!r}: the workspace image may predate "
+ f"the endpoint, or the gateway has restarted",
+ )
+ if status == 400:
+ raise ValueError(
+ f"gateway rejected runtime headers for "
+ f"MCP {self.name!r}: {_safe_detail(status, body)}",
+ )
+ if status >= 400:
+ raise RuntimeError(
+ f"gateway failed to update runtime headers for "
+ f"MCP {self.name!r}: {_safe_detail(status, body)}",
+ )
+ self._runtime_headers = dict(headers)
+
# ── tool discovery ────────────────────────────────────────────
async def list_raw_tools(self) -> list[mcp.types.Tool]:
diff --git a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py
index d4b4da7b1..2c70f6bd2 100644
--- a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py
+++ b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py
@@ -14,7 +14,9 @@ Endpoints::
GET /health
GET /mcps # [MCPClient.model_dump(), ...]
POST /mcps # body: MCPClient.model_dump()
+ # (+ optional runtime_headers)
DELETE /mcps/{name}
+ PUT /mcps/{name}/runtime-headers
GET /mcps/{name}/tools
POST /mcps/{name}/tools/{tool} # body: {arguments: {...}}
@@ -33,7 +35,7 @@ import asyncio
import secrets
from typing import Any
-from fastapi import FastAPI, HTTPException, Request
+from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import PlainTextResponse
from agentscope.mcp import MCPClient
@@ -47,11 +49,20 @@ class _State:
self.lock = asyncio.Lock()
-async def _build_client(spec: dict[str, Any]) -> MCPClient:
+async def _build_client(
+ spec: dict[str, Any],
+ runtime_headers: dict[str, str] | None = None,
+) -> MCPClient:
"""Validate a spec into an ``MCPClient``, connect if stateful,
and prime its tool cache.
+
+ ``runtime_headers`` are applied before connecting: a rotated
+ credential has to be in place for the handshake below, and it is
+ not part of ``spec`` because it must never be persisted.
"""
client = MCPClient.model_validate(spec)
+ if runtime_headers:
+ await client.set_runtime_headers(runtime_headers)
if client.is_stateful:
await client.connect()
await client.list_raw_tools()
@@ -120,6 +131,7 @@ def _build_app(
session_id: str = "",
) -> dict[str, Any]:
body = await request.json()
+ runtime_headers = body.pop("runtime_headers", None)
name = body.get("name", "")
if not name:
raise HTTPException(400, "name required")
@@ -132,9 +144,11 @@ def _build_app(
f"session={session_id!r}",
)
try:
- by_name[name] = await _build_client(body)
+ by_name[name] = await _build_client(body, runtime_headers)
except HTTPException:
raise
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
except Exception as e: # noqa: BLE001
raise HTTPException(500, f"connect failed: {e}") from e
return {"ok": True}
@@ -154,6 +168,29 @@ def _build_app(
await client.close()
return {"ok": True}
+ @app.put("/mcps/{name}/runtime-headers", status_code=204)
+ async def _set_runtime_headers(
+ name: str,
+ request: Request,
+ agent_id: str = "",
+ session_id: str = "",
+ ) -> Response:
+ """Replace live headers without rebuilding the MCP client."""
+ body = await request.json()
+ headers = body.get("headers") if isinstance(body, dict) else None
+ if not isinstance(headers, dict):
+ raise HTTPException(
+ 400,
+ "headers must be a JSON object",
+ )
+ try:
+ async with state.lock:
+ client = _lookup(agent_id, session_id, name)
+ await client.set_runtime_headers(headers)
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return Response(status_code=204)
+
@app.get("/mcps/{name}/tools")
async def _list_tools(
name: str,
diff --git a/tests/mcp_runtime_headers_test.py b/tests/mcp_runtime_headers_test.py
new file mode 100644
index 000000000..45d8f7db0
--- /dev/null
+++ b/tests/mcp_runtime_headers_test.py
@@ -0,0 +1,521 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Tests for live MCP HTTP header updates."""
+from contextlib import asynccontextmanager
+import unittest
+from typing import Any, AsyncGenerator
+from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import AsyncMock, patch
+
+import httpx
+from fastapi.testclient import TestClient
+
+from agentscope.mcp import HttpMCPConfig, MCPClient
+from agentscope.workspace._gateway_client import GatewayClient
+from agentscope.workspace._mcp_gateway._mcp_gateway_app import (
+ _State,
+ _build_app,
+)
+
+_WATCHED = ("Authorization", "X-Static", "X-Runtime", "Mcp-Session-Id")
+
+
+class MCPRuntimeHeadersTest(IsolatedAsyncioTestCase):
+ """Runtime headers are live client state, not serialized config."""
+
+ def setUp(self) -> None:
+ """Replace the transport with one exposing its HTTP client."""
+ self.seen: dict[str, Any] = {}
+
+ @asynccontextmanager
+ async def fake_transport(
+ url: str,
+ *,
+ http_client: httpx.AsyncClient,
+ ) -> AsyncGenerator[tuple[object, object, object], None]:
+ self.seen.update(url=url, http_client=http_client)
+ yield object(), object(), object()
+
+ patcher = patch(
+ "agentscope.mcp._mcp_client.streamable_http_client",
+ fake_transport,
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _outgoing(self, **headers: str) -> dict[str, str]:
+ """The watched headers httpx would put on the next request."""
+ request = self.seen["http_client"].build_request(
+ "POST",
+ "https://example.com/mcp",
+ headers=headers or None,
+ )
+ return {
+ name: request.headers[name]
+ for name in _WATCHED
+ if name in request.headers
+ }
+
+ async def test_runtime_headers_replace_and_clear(self) -> None:
+ """Each call replaces the whole map; an empty one restores config."""
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=True,
+ mcp_config=HttpMCPConfig(
+ url="https://example.com/mcp",
+ headers={
+ "Authorization": "Bearer static",
+ "X-Static": "static",
+ },
+ ),
+ )
+
+ async with client._create_http_client():
+ configured = self._outgoing()
+
+ await client.set_runtime_headers(
+ {"Authorization": "Bearer runtime", "X-Runtime": "first"},
+ )
+ overridden = self._outgoing()
+
+ await client.set_runtime_headers(
+ {"Authorization": "Bearer replacement"},
+ )
+ replaced = self._outgoing()
+
+ await client.set_runtime_headers({})
+ cleared = self._outgoing()
+
+ self.assertDictEqual(
+ {
+ "url": self.seen["url"],
+ "configured": configured,
+ "overridden": overridden,
+ "replaced": replaced,
+ "cleared": cleared,
+ },
+ {
+ "url": "https://example.com/mcp",
+ "configured": {
+ "Authorization": "Bearer static",
+ "X-Static": "static",
+ },
+ "overridden": {
+ "Authorization": "Bearer runtime",
+ "X-Static": "static",
+ "X-Runtime": "first",
+ },
+ "replaced": {
+ "Authorization": "Bearer replacement",
+ "X-Static": "static",
+ },
+ "cleared": {
+ "Authorization": "Bearer static",
+ "X-Static": "static",
+ },
+ },
+ )
+
+ async def test_headers_set_before_the_client_exists_are_applied(
+ self,
+ ) -> None:
+ """A stateless client picks up headers set before it was built."""
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://example.com/mcp"),
+ )
+ await client.set_runtime_headers({"Authorization": "Bearer runtime"})
+
+ async with client._create_http_client():
+ outgoing = self._outgoing()
+
+ self.assertDictEqual(
+ outgoing,
+ {"Authorization": "Bearer runtime"},
+ )
+
+ async def test_transport_headers_win_over_runtime_headers(self) -> None:
+ """Per-request MCP headers outrank anything set on the client."""
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://example.com/mcp"),
+ )
+ await client.set_runtime_headers({"Mcp-Session-Id": "hijacked"})
+
+ async with client._create_http_client():
+ outgoing = self._outgoing(**{"mcp-session-id": "from-transport"})
+
+ self.assertDictEqual(
+ outgoing,
+ {"Mcp-Session-Id": "from-transport"},
+ )
+
+ async def test_owning_the_client_keeps_transport_defaults(self) -> None:
+ """Taking ownership must not change how the client is configured."""
+ defaults: dict[str, Any] = {}
+ for label, config in (
+ (
+ "configured",
+ HttpMCPConfig(
+ url="https://example.com/mcp",
+ headers={"X-Static": "static"},
+ ),
+ ),
+ (
+ "untimed",
+ HttpMCPConfig(url="https://example.com/mcp", timeout=None),
+ ),
+ ):
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=False,
+ mcp_config=config,
+ )
+ async with client._create_http_client():
+ http_client = self.seen["http_client"]
+ defaults[label] = {
+ "follow_redirects": http_client.follow_redirects,
+ "read_timeout": http_client.timeout.read,
+ }
+
+ self.assertDictEqual(
+ defaults,
+ {
+ "configured": {
+ "follow_redirects": False,
+ "read_timeout": 30.0,
+ },
+ "untimed": {
+ "follow_redirects": True,
+ "read_timeout": 300.0,
+ },
+ },
+ )
+
+ async def test_runtime_headers_are_not_serialized(self) -> None:
+ """Live headers never become part of the persisted MCP spec."""
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(
+ url="https://example.com/mcp",
+ headers={"X-Static": "static"},
+ ),
+ )
+ await client.set_runtime_headers({"Authorization": "Bearer runtime"})
+
+ self.assertDictEqual(
+ client.model_dump(mode="json"),
+ {
+ "name": "runtime_headers",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://example.com/mcp",
+ "headers": {"X-Static": "static"},
+ "timeout": 30.0,
+ },
+ "enable_tools": None,
+ "disable_tools": None,
+ "execution_timeout": None,
+ },
+ )
+
+ async def test_runtime_headers_reject_sse(self) -> None:
+ """SSE headers stay fixed for the lifetime of the stream."""
+ for url in (
+ "https://example.com/sse?key=secret",
+ "https://example.com/messages/",
+ ):
+ with self.subTest(url=url):
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=True,
+ mcp_config=HttpMCPConfig(url=url),
+ )
+ with self.assertRaisesRegex(ValueError, "Streamable HTTP"):
+ await client.set_runtime_headers({"X-Runtime": "value"})
+
+ async def test_runtime_headers_reject_http_owned_names(self) -> None:
+ """httpx derives these with setdefault, so a value here would win."""
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://example.com/mcp"),
+ )
+
+ for name in (
+ "Host",
+ "Content-Length",
+ "Transfer-Encoding",
+ "connection",
+ ):
+ with self.subTest(name=name):
+ with self.assertRaisesRegex(ValueError, "owned by the HTTP"):
+ await client.set_runtime_headers({name: "hijacked"})
+
+ async def test_runtime_headers_reject_invalid_wire_values(self) -> None:
+ """Invalid names and values fail before an HTTP request is sent."""
+ client = MCPClient(
+ name="runtime_headers",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://example.com/mcp"),
+ )
+
+ for headers, name in (
+ ({"Bad Header": "sensitive-value"}, "Bad Header"),
+ ({"X-Unsafe": "sensitive\r\nInjected: 1"}, "X-Unsafe"),
+ ({"X-Unicode": "sensitive-é"}, "X-Unicode"),
+ ):
+ with self.subTest(headers=list(headers)):
+ with self.assertRaisesRegex(ValueError, name) as raised:
+ await client.set_runtime_headers(headers)
+ self.assertNotIn("sensitive", str(raised.exception))
+
+
+class GatewayRuntimeHeadersRouteTest(unittest.TestCase):
+ """The gateway updates its live client without replacing it."""
+
+ def setUp(self) -> None:
+ """Build an app with one registered stateful HTTP client."""
+ self.state = _State()
+ self.mcp = MCPClient(
+ name="remote",
+ is_stateful=True,
+ mcp_config=HttpMCPConfig(url="https://example.com/mcp"),
+ )
+ self.mcp._is_connected = True
+ self.state.clients[("agent", "session")] = {"remote": self.mcp}
+ self.client = TestClient(_build_app(self.state))
+
+ def test_update_runtime_headers(self) -> None:
+ """PUT replaces live headers on the same client instance."""
+ response = self.client.put(
+ "/mcps/remote/runtime-headers",
+ params={"agent_id": "agent", "session_id": "session"},
+ json={"headers": {"Authorization": "Bearer runtime"}},
+ )
+
+ self.assertDictEqual(
+ {
+ "status_code": response.status_code,
+ "body": response.content,
+ "same_client": self.state.clients[("agent", "session")][
+ "remote"
+ ]
+ is self.mcp,
+ "is_connected": self.mcp.is_connected,
+ "runtime_headers": self.mcp._runtime_headers,
+ },
+ {
+ "status_code": 204,
+ "body": b"",
+ "same_client": True,
+ "is_connected": True,
+ "runtime_headers": {"Authorization": "Bearer runtime"},
+ },
+ )
+
+ def test_registration_applies_headers_before_connect(self) -> None:
+ """The gateway's own handshake must use the rotated credential."""
+ at_connect: list[dict[str, str]] = []
+
+ async def capture(client: MCPClient) -> None:
+ at_connect.append(dict(client._runtime_headers))
+
+ with patch.object(MCPClient, "connect", capture), patch.object(
+ MCPClient,
+ "list_raw_tools",
+ AsyncMock(return_value=[]),
+ ):
+ response = self.client.post(
+ "/mcps",
+ params={"agent_id": "agent", "session_id": "session"},
+ json={
+ "name": "fresh",
+ "is_stateful": True,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://example.com/mcp",
+ },
+ "runtime_headers": {"Authorization": "Bearer runtime"},
+ },
+ )
+
+ self.assertDictEqual(
+ {
+ "status_code": response.status_code,
+ "headers_at_connect": at_connect,
+ },
+ {
+ "status_code": 200,
+ "headers_at_connect": [{"Authorization": "Bearer runtime"}],
+ },
+ )
+
+ def test_update_runtime_headers_rejects_unknown_client(self) -> None:
+ """The update route preserves the gateway's lookup contract."""
+ response = self.client.put(
+ "/mcps/missing/runtime-headers",
+ params={"agent_id": "agent", "session_id": "session"},
+ json={"headers": {"Authorization": "Bearer runtime"}},
+ )
+
+ self.assertEqual(response.status_code, 404)
+
+ def test_update_runtime_headers_does_not_echo_values(self) -> None:
+ """Validation failures identify only the offending name."""
+ response = self.client.put(
+ "/mcps/remote/runtime-headers",
+ params={"agent_id": "agent", "session_id": "session"},
+ json={"headers": {"Bad Header": "sensitive-value"}},
+ )
+
+ self.assertDictEqual(
+ {
+ "status_code": response.status_code,
+ "body": response.json(),
+ "runtime_headers": self.mcp._runtime_headers,
+ },
+ {
+ "status_code": 400,
+ "body": {"detail": "Runtime header 'Bad Header' is invalid."},
+ "runtime_headers": {},
+ },
+ )
+
+
+class GatewayMCPClientRuntimeHeadersTest(IsolatedAsyncioTestCase):
+ """The host-side proxy forwards runtime header updates."""
+
+ @staticmethod
+ def _proxy(gateway: GatewayClient, connected: bool) -> Any:
+ """A proxy for one stateless HTTP MCP on ``gateway``."""
+ return gateway.make_client(
+ MCPClient(
+ name="remote",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(url="https://example.com/mcp"),
+ ).model_dump(mode="json"),
+ agent_id="agent",
+ session_id="session",
+ connected=connected,
+ )
+
+ async def test_proxy_updates_connected_gateway_client(self) -> None:
+ """The proxy sends one scoped PUT without changing its spec."""
+ gateway = GatewayClient(
+ backend=object(), # type: ignore[arg-type]
+ gateway_port=5600,
+ )
+ gateway.exec_request = AsyncMock( # type: ignore[method-assign]
+ return_value=(204, b""),
+ )
+ client = self._proxy(gateway, connected=True)
+
+ await client.set_runtime_headers({"Authorization": "Bearer runtime"})
+
+ gateway.exec_request.assert_awaited_once_with(
+ "PUT",
+ "/mcps/remote/runtime-headers",
+ params={"agent_id": "agent", "session_id": "session"},
+ body={"headers": {"Authorization": "Bearer runtime"}},
+ )
+ self.assertDictEqual(
+ client.model_dump(mode="json"),
+ {
+ "name": "remote",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://example.com/mcp",
+ "headers": None,
+ "timeout": 30.0,
+ },
+ "enable_tools": None,
+ "disable_tools": None,
+ "execution_timeout": None,
+ },
+ )
+
+ async def test_proxy_registers_with_runtime_headers(self) -> None:
+ """The gateway connects during POST, so they must ride along."""
+ gateway = GatewayClient(
+ backend=object(), # type: ignore[arg-type]
+ gateway_port=5600,
+ )
+ gateway.exec_request = AsyncMock( # type: ignore[method-assign]
+ return_value=(204, b""),
+ )
+ client = self._proxy(gateway, connected=True)
+ await client.set_runtime_headers({"Authorization": "Bearer runtime"})
+ await client.close()
+
+ gateway.exec_request.reset_mock()
+ await client.connect()
+
+ gateway.exec_request.assert_awaited_once_with(
+ "POST",
+ "/mcps",
+ params={"agent_id": "agent", "session_id": "session"},
+ body={
+ "name": "remote",
+ "is_stateful": False,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://example.com/mcp",
+ "headers": None,
+ "timeout": 30.0,
+ },
+ "enable_tools": None,
+ "disable_tools": None,
+ "execution_timeout": None,
+ "runtime_headers": {"Authorization": "Bearer runtime"},
+ },
+ )
+
+ async def test_proxy_rejects_update_before_connect(self) -> None:
+ """Updates require an existing gateway-side client."""
+ gateway = GatewayClient(
+ backend=object(), # type: ignore[arg-type]
+ gateway_port=5600,
+ )
+ client = self._proxy(gateway, connected=False)
+
+ with self.assertRaisesRegex(RuntimeError, "not connected"):
+ await client.set_runtime_headers({"X-Runtime": "value"})
+
+ async def test_proxy_reports_gateway_errors(self) -> None:
+ """400 matches the local exception type; 404 names the cause."""
+ for status, body, error, message in (
+ (
+ 400,
+ b'{"detail":"Runtime header is invalid."}',
+ ValueError,
+ "HTTP 400: Runtime header is invalid",
+ ),
+ (
+ 404,
+ b'{"detail":"Not Found"}',
+ RuntimeError,
+ "no runtime-headers route",
+ ),
+ ):
+ with self.subTest(status=status):
+ gateway = GatewayClient(
+ backend=object(), # type: ignore[arg-type]
+ gateway_port=5600,
+ )
+ gateway.exec_request = ( # type: ignore[method-assign]
+ AsyncMock(return_value=(status, body))
+ )
+ client = self._proxy(gateway, connected=True)
+
+ with self.assertRaisesRegex(error, message):
+ await client.set_runtime_headers({"X-Runtime": "value"})
+
+
+if __name__ == "__main__":
+ unittest.main()