π The fast, Pythonic way to build MCP servers and clients.
Fix proxy forwarding of MCP transport headers (#4853)
Jake Kaplanb2025212d8bc
diff --git a/fastmcp_slim/fastmcp/client/dependencies.py b/fastmcp_slim/fastmcp/client/dependencies.pyindex 54faaefe3..7a8f9f046 100644--- a/fastmcp_slim/fastmcp/client/dependencies.py+++ b/fastmcp_slim/fastmcp/client/dependencies.py@@ -1,6 +1,21 @@"""Client-side dependency helpers."""+def _get_forwardable_http_headers() -> dict[str, str]:+ """Return ambient headers safe to copy onto a new MCP connection.++ MCP transport and routing headers describe one HTTP hop and must be+ regenerated for the new connection. `Last-Event-ID` likewise belongs to+ the inbound connection's event stream. Other headers, including+ authorization and custom proxy headers, are preserved.+ """+ return {+ name: value+ for name, value in get_http_headers(include={"authorization"}).items()+ if not name.startswith("mcp-") and name != "last-event-id"+ }++def get_http_headers(include_all: bool = False,include: set[str] | None = None,diff --git a/fastmcp_slim/fastmcp/client/transports/base.py b/fastmcp_slim/fastmcp/client/transports/base.pyindex 422f3ed9c..9a3d9e09f 100644--- a/fastmcp_slim/fastmcp/client/transports/base.py+++ b/fastmcp_slim/fastmcp/client/transports/base.py@@ -49,10 +49,12 @@ class TransportOptions:session_class: The ClientSession class to instantiate. Proxies supply asession that skips output-schema validation, since they relayresults rather than consume them.- forward_incoming_headers: Whether to forward the inbound request's- authorization header upstream. Only appropriate for proxies, where- the caller's credentials are meant to be propagated. Honored by the- HTTP and SSE transports; ignored by the others.+ forward_incoming_headers: Whether to forward eligible inbound HTTP+ headers upstream, including authorization. Hop-specific HTTP headers+ and MCP transport, routing, and event-stream state are excluded+ because each backend connection owns that state. Only appropriate+ for proxies; honored by the HTTP and SSE transports and ignored by+ the others.backend_mode: The connect `mode` to give backend clients that a wrappingtransport builds on this client's behalf, so a chain of connectionsspeaks one protocol era end to end. `None` leaves each backenddiff --git a/fastmcp_slim/fastmcp/client/transports/http.py b/fastmcp_slim/fastmcp/client/transports/http.pyindex 3ba827931..11703623d 100644--- a/fastmcp_slim/fastmcp/client/transports/http.py+++ b/fastmcp_slim/fastmcp/client/transports/http.py@@ -20,7 +20,7 @@ from fastmcp.client.auth.client_credentials import (PrivateKeyJWTOAuthProvider,)from fastmcp.client.auth.oauth import OAuth-from fastmcp.client.dependencies import get_http_headers+from fastmcp.client.dependencies import _get_forwardable_http_headersfrom fastmcp.client.transports.base import (ClientTransport,SessionKwargs,@@ -161,12 +161,12 @@ class StreamableHttpTransport(ClientTransport):) -> AsyncIterator[ClientSession]:options = transport_options or TransportOptions()- # When used in a proxy, forward the inbound request's authorization- # header to the upstream server. This is off by default so that a- # plain Client used inside a server tool handler doesn't accidentally- # leak the caller's credentials to an unrelated remote server.+ # Proxies preserve eligible inbound headers while starting a distinct+ # MCP connection with its own transport state.+ # This is off by default so a plain Client used inside a server tool+ # handler cannot leak caller headers to an unrelated remote server.if options.forward_incoming_headers:- headers = get_http_headers(include={"authorization"}) | self.headers+ headers = _get_forwardable_http_headers() | self.headerselse:headers = dict(self.headers)diff --git a/fastmcp_slim/fastmcp/client/transports/sse.py b/fastmcp_slim/fastmcp/client/transports/sse.pyindex ed5602444..86f997b72 100644--- a/fastmcp_slim/fastmcp/client/transports/sse.py+++ b/fastmcp_slim/fastmcp/client/transports/sse.py@@ -21,7 +21,7 @@ from fastmcp.client.auth.client_credentials import (PrivateKeyJWTOAuthProvider,)from fastmcp.client.auth.oauth import OAuth-from fastmcp.client.dependencies import get_http_headers+from fastmcp.client.dependencies import _get_forwardable_http_headersfrom fastmcp.client.transports.base import (ClientTransport,SessionKwargs,@@ -138,14 +138,12 @@ class SSETransport(ClientTransport):options = transport_options or TransportOptions()client_kwargs: dict[str, Any] = {}- # When used in a proxy, forward the inbound request's authorization- # header to the upstream server. This is off by default so that a- # plain Client used inside a server tool handler doesn't accidentally- # leak the caller's credentials to an unrelated remote server.+ # Proxies preserve eligible inbound headers while starting a distinct+ # MCP connection with its own transport state.+ # This is off by default so a plain Client used inside a server tool+ # handler cannot leak caller headers to an unrelated remote server.if options.forward_incoming_headers:- client_kwargs["headers"] = (- get_http_headers(include={"authorization"}) | self.headers- )+ client_kwargs["headers"] = _get_forwardable_http_headers() | self.headerselse:client_kwargs["headers"] = dict(self.headers)diff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.pyindex c6b9ef367..c77a3b9d4 100644--- a/fastmcp_slim/fastmcp/server/providers/proxy.py+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py@@ -96,8 +96,8 @@ class _ForwardingClientSession(ClientSession):# Settings every proxy-backend connection uses: relay results without policing-# the backend's output schema, and forward the caller's authorization header-# upstream (appropriate for a proxy, where credentials are meant to propagate).+# the backend's output schema, and forward eligible caller headers upstream+# without inheriting frontend-owned MCP transport state.PROXY_TRANSPORT_OPTIONS = TransportOptions(session_class=_ForwardingClientSession,forward_incoming_headers=True,diff --git a/tests/server/providers/proxy/test_proxy_headers.py b/tests/server/providers/proxy/test_proxy_headers.pynew file mode 100644index 000000000..b82147a0c--- /dev/null+++ b/tests/server/providers/proxy/test_proxy_headers.py@@ -0,0 +1,107 @@+"""Header forwarding across ProxyProvider HTTP hops."""++import json+from typing import Any++import httpx2+from mcp import MCPError+from mcp_types import METHOD_NOT_FOUND+from mcp_types.version import LATEST_HANDSHAKE_VERSION, LATEST_MODERN_VERSION++from fastmcp import FastMCP+from fastmcp.server.middleware import Middleware+from fastmcp.server.providers.proxy import ProxyClient, ProxyProvider+from fastmcp.utilities.tests import asgi_server+++async def test_proxy_does_not_forward_frontend_mcp_headers_to_legacy_backend():+ """A modern frontend's transport state does not contaminate a legacy backend."""+ captured_requests: list[httpx2.Request] = []++ class RejectDiscovery(Middleware):+ async def on_discover(self, context, call_next):+ raise MCPError(code=METHOD_NOT_FOUND, message="Method not found")++ backend = FastMCP("Legacy Backend", middleware=[RejectDiscovery()])++ @backend.tool+ def legacy_ping() -> str:+ return "pong"++ async with asgi_server(backend) as running_backend:++ async def capture_request(request: httpx2.Request) -> None:+ captured_requests.append(request)++ def backend_http_client(+ headers: dict[str, str] | None = None,+ timeout: httpx2.Timeout | None = None,+ auth: httpx2.Auth | None = None,+ **kwargs: Any,+ ) -> httpx2.AsyncClient:+ return running_backend.http_client(+ headers=headers,+ timeout=timeout,+ auth=auth,+ event_hooks={"request": [capture_request]},+ **kwargs,+ )++ backend_transport = running_backend.transport(+ httpx_client_factory=backend_http_client+ )+ proxy = FastMCP(+ "Proxy",+ providers=[+ ProxyProvider(lambda: ProxyClient(backend_transport, mode="auto"))+ ],+ )++ async with asgi_server(proxy) as running_proxy:+ async with running_proxy.client(+ mode="auto",+ headers={+ "Authorization": "Bearer frontend-token",+ "X-Proxy-Custom": "preserved",+ "Mcp-Name": "frontend-name",+ "Mcp-Param-Tenant": "frontend-tenant",+ "Mcp-Session-Id": "frontend-session",+ "Last-Event-ID": "frontend-event",+ },+ ) as client:+ assert client.protocol_version == LATEST_MODERN_VERSION+ tools = await client.list_tools()++ assert [tool.name for tool in tools] == ["legacy_ping"]++ def request_for(method: str) -> httpx2.Request:+ return next(+ request+ for request in captured_requests+ if request.method == "POST"+ and json.loads(request.content).get("method") == method+ )++ discover = request_for("server/discover")+ initialize = request_for("initialize")+ list_tools = request_for("tools/list")++ assert discover.headers["mcp-protocol-version"] == LATEST_MODERN_VERSION+ assert discover.headers["mcp-method"] == "server/discover"++ assert "mcp-protocol-version" not in initialize.headers+ assert "mcp-method" not in initialize.headers+ initialize_body = json.loads(initialize.content)+ assert initialize_body["params"]["protocolVersion"] == LATEST_HANDSHAKE_VERSION++ assert list_tools.headers["mcp-protocol-version"] == LATEST_HANDSHAKE_VERSION+ assert "mcp-method" not in list_tools.headers+ assert list_tools.headers["mcp-session-id"] != "frontend-session"++ for request in (discover, initialize, list_tools):+ assert request.headers["authorization"] == "Bearer frontend-token"+ assert request.headers["x-proxy-custom"] == "preserved"+ assert "mcp-name" not in request.headers+ assert "mcp-param-tenant" not in request.headers+ assert request.headers.get("mcp-session-id") != "frontend-session"+ assert "last-event-id" not in request.headers