π The fast, Pythonic way to build MCP servers and clients.
Apply Host/Origin protection settings to the SSE transport (#5427)
Jeremiah Lowin633065580996
diff --git a/docs/deployment/http.mdx b/docs/deployment/http.mdxindex a5f34ee0c..f7a58b698 100644--- a/docs/deployment/http.mdx+++ b/docs/deployment/http.mdx@@ -103,7 +103,7 @@ If you're mounting an authenticated server under a path prefix, see [Mounting Au### Host and Origin Protection-FastMCP can validate `Host` and browser `Origin` headers for Streamable HTTP requests before they reach MCP session handling. This request guard protects localhost-bound servers from DNS rebinding attacks, and it stays opt-in to preserve compatibility with existing ASGI, serverless, and reverse-proxy deployments.+FastMCP can validate `Host` and browser `Origin` headers before requests reach MCP session handling. The same settings apply to Streamable HTTP and to the legacy SSE transport. This request guard protects localhost-bound servers from DNS rebinding attacks, and it stays opt-in to preserve compatibility with existing ASGI, serverless, and reverse-proxy deployments.Think of this as a request guard rather than CORS middleware. It decides whether a request can reach MCP session handling. CORS remains a separate browser response-header policy; configure CORS middleware separately when browser JavaScript must read cross-origin responses.diff --git a/docs/more/settings.mdx b/docs/more/settings.mdxindex 7f0fe5df5..ac9182054 100644--- a/docs/more/settings.mdx+++ b/docs/more/settings.mdx@@ -43,7 +43,7 @@ These control how the server listens when running with an HTTP transport.| `FASTMCP_STREAMABLE_HTTP_PATH` | `str` | `/mcp` | Path for Streamable HTTP endpoint. || `FASTMCP_STATELESS_HTTP` | `bool` | `false` | Enable stateless HTTP mode (new transport per request). Useful for multi-worker deployments. || `FASTMCP_JSON_RESPONSE` | `bool` | `false` | Use JSON responses instead of SSE for Streamable HTTP. |-| `FASTMCP_HTTP_HOST_ORIGIN_PROTECTION` | `bool \| "auto"` | `false` | Validate `Host` and browser `Origin` headers for Streamable HTTP requests. `auto` protects localhost-bound servers and explicit host/origin allowlists. `false` disables this guard and FastMCP's DNS-rebinding protection for the endpoint. |+| `FASTMCP_HTTP_HOST_ORIGIN_PROTECTION` | `bool \| "auto"` | `false` | Validate `Host` and browser `Origin` headers for Streamable HTTP and SSE requests. `auto` protects localhost-bound servers and explicit host/origin allowlists. `false` disables this guard and FastMCP's DNS-rebinding protection for the endpoint. || `FASTMCP_HTTP_ALLOWED_HOSTS` | `list[str] \| null` | `null` | Additional trusted hostnames when Host and Origin protection is enabled. Use a JSON array, such as `["mcp.example.com"]`. || `FASTMCP_HTTP_ALLOWED_ORIGINS` | `list[str] \| null` | `null` | Browser origins trusted when Host and Origin protection is enabled. Configure CORS separately for cross-origin browser reads. Use a JSON array, such as `["https://app.example.com"]`. || `FASTMCP_HTTP_SESSION_IDLE_TIMEOUT` | `float \| null` | `null` | Seconds a Streamable HTTP session may remain idle before it is terminated. The deadline resets on every request. When `null`, sessions never expire from inactivity. Not supported in stateless mode. |diff --git a/fastmcp_slim/fastmcp/server/http.py b/fastmcp_slim/fastmcp/server/http.pyindex 70bb17438..c56d572a7 100644--- a/fastmcp_slim/fastmcp/server/http.py+++ b/fastmcp_slim/fastmcp/server/http.py@@ -339,6 +339,33 @@ class HostOriginGuardMiddleware:return _normalize_origin(origin) == request_origin+def _host_origin_guard_middleware(+ host_origin_protection: HostOriginProtection,+ allowed_hosts: Sequence[str] | None,+ allowed_origins: Sequence[str] | None,+) -> Middleware | None:+ """Build the Host/Origin guard for an HTTP transport app.++ Returns None when `host_origin_protection` is False. `True` validates every+ request; `"auto"` validates localhost-bound servers and requests covered by+ explicit host/origin allowlists.+ """+ if host_origin_protection not in (True, False, "auto"):+ raise ValueError("host_origin_protection must be True, False, or 'auto'.")++ # False removes FastMCP's Host/Origin guard. The SDK guard is also disabled+ # on every transport, so DNS-rebinding protection then depends on the deployment.+ if host_origin_protection is False:+ return None++ return Middleware(+ HostOriginGuardMiddleware,+ allowed_hosts=allowed_hosts,+ allowed_origins=allowed_origins,+ mode="strict" if host_origin_protection is True else "auto",+ )++_current_http_request: ContextVar[Request | None] = ContextVar("http_request",default=None,@@ -421,6 +448,9 @@ def create_sse_app(debug: bool = False,routes: list[BaseRoute] | None = None,middleware: list[Middleware] | None = None,+ host_origin_protection: HostOriginProtection = False,+ allowed_hosts: Sequence[str] | None = None,+ allowed_origins: Sequence[str] | None = None,) -> StarletteWithLifespan:"""Return an instance of the SSE server app.@@ -432,6 +462,14 @@ def create_sse_app(debug: Whether to enable debug moderoutes: Optional list of custom routesmiddleware: Optional list of middleware+ host_origin_protection: Whether to validate Host and Origin headers+ before requests reach the SSE connection and message endpoints.+ Defaults to False for compatibility. "auto" protects+ localhost-bound servers and explicit host/origin allowlists.+ allowed_hosts: Additional hostnames that may appear in the Host header.+ allowed_origins: Additional browser origins trusted by the request guard.+ Configure CORS separately when browser JavaScript must read+ cross-origin responses.Returns:A Starlette application with RequestContextMiddleware"""@@ -439,8 +477,20 @@ def create_sse_app(server_routes: list[BaseRoute] = []server_middleware: list[Middleware] = []- # Set up SSE transport- sse = SseServerTransport(message_path)+ host_origin_guard = _host_origin_guard_middleware(+ host_origin_protection,+ allowed_hosts,+ allowed_origins,+ )++ # FastMCP owns DNS-rebinding protection via HostOriginGuardMiddleware, as+ # for streamable HTTP, so the SDK's own check stays disabled.+ sse = SseServerTransport(+ message_path,+ security_settings=TransportSecuritySettings(+ enable_dns_rebinding_protection=False+ ),+ )# Create handler for SSE connectionsasync def handle_sse(scope: Scope, receive: Receive, send: Send) -> Response:@@ -520,6 +570,8 @@ def create_sse_app(server_routes.extend(server._get_additional_http_routes())# Add middleware+ if host_origin_guard is not None:+ server_middleware.insert(0, host_origin_guard)if middleware:server_middleware.extend(middleware)@@ -649,21 +701,13 @@ def create_streamable_http_app(server_routes.extend(server._get_additional_http_routes())# Add middleware- if host_origin_protection not in (True, False, "auto"):- raise ValueError("host_origin_protection must be True, False, or 'auto'.")-- # False removes FastMCP's Host/Origin guard. The SDK guard is also disabled- # below, so DNS-rebinding protection then depends on the deployment.- if host_origin_protection is not False:- server_middleware.insert(- 0,- Middleware(- HostOriginGuardMiddleware,- allowed_hosts=allowed_hosts,- allowed_origins=allowed_origins,- mode="strict" if host_origin_protection is True else "auto",- ),- )+ host_origin_guard = _host_origin_guard_middleware(+ host_origin_protection,+ allowed_hosts,+ allowed_origins,+ )+ if host_origin_guard is not None:+ server_middleware.insert(0, host_origin_guard)if middleware:server_middleware.extend(middleware)diff --git a/fastmcp_slim/fastmcp/server/mixins/transport.py b/fastmcp_slim/fastmcp/server/mixins/transport.pyindex b26e02d18..4e098727c 100644--- a/fastmcp_slim/fastmcp/server/mixins/transport.py+++ b/fastmcp_slim/fastmcp/server/mixins/transport.py@@ -464,6 +464,21 @@ class TransportMixin:auth=self.auth,debug=fastmcp.settings.debug,middleware=middleware,+ host_origin_protection=(+ host_origin_protection+ if host_origin_protection is not None+ else fastmcp.settings.http_host_origin_protection+ ),+ allowed_hosts=(+ allowed_hosts+ if allowed_hosts is not None+ else fastmcp.settings.http_allowed_hosts+ ),+ allowed_origins=(+ allowed_origins+ if allowed_origins is not None+ else fastmcp.settings.http_allowed_origins+ ),)else:raise ValueError(f"Unknown transport: {transport}")diff --git a/tests/server/http/test_sse_host_origin_protection.py b/tests/server/http/test_sse_host_origin_protection.pynew file mode 100644index 000000000..1fc379554--- /dev/null+++ b/tests/server/http/test_sse_host_origin_protection.py@@ -0,0 +1,252 @@+"""Host and Origin validation on the SSE transport's connection and message endpoints."""++from collections.abc import AsyncGenerator+from contextlib import asynccontextmanager+from typing import Any, Literal++import httpx2+import pytest++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.client.transports import SSETransport+from fastmcp.server.http import HostOriginProtection, create_sse_app+from fastmcp.utilities.tests import (+ ASGIServer,+ asgi_server,+ run_server_async,+ temporary_settings,+)++OTHER_HOST = {"host": "other.example"}+OTHER_ORIGIN = {"origin": "https://other.example"}+PING_REQUEST = {"jsonrpc": "2.0", "id": 1, "method": "ping"}++GuardResult = Literal["host rejected", "origin rejected", "allowed"]+++def create_server() -> FastMCP:+ server = FastMCP("SSEGuardServer")++ @server.tool+ def greet(name: str) -> str:+ return f"Hello, {name}!"++ return server+++def _guard_result(status_code: int) -> GuardResult:+ if status_code == 421:+ return "host rejected"+ if status_code == 403:+ return "origin rejected"+ return "allowed"+++async def _get_status(server: ASGIServer, headers: dict[str, str]) -> int:+ async with server.http_client() as http:+ async with http.stream(+ "GET",+ server.url,+ headers={"accept": "text/event-stream", **headers},+ ) as response:+ return response.status_code+++@asynccontextmanager+async def _sse_session(server: ASGIServer) -> AsyncGenerator[str, None]:+ """Open an SSE stream and yield the session's message endpoint URL."""+ async with server.http_client() as http:+ async with http.stream(+ "GET",+ server.url,+ headers={"accept": "text/event-stream"},+ ) as response:+ assert response.status_code == 200+ message_path: str | None = None+ async for line in response.aiter_lines():+ if line.startswith("data: "):+ message_path = line.removeprefix("data: ")+ break+ assert message_path is not None++ yield str(httpx2.URL(server.url).join(message_path))+++async def _post_status(+ server: ASGIServer,+ message_url: str,+ headers: dict[str, str],+) -> int:+ async with server.http_client() as http:+ response = await http.post(message_url, headers=headers, json=PING_REQUEST)+ return response.status_code+++async def protected_server() -> AsyncGenerator[ASGIServer, None]:+ async with asgi_server(+ create_server(),+ transport="sse",+ host_origin_protection=True,+ ) as server:+ yield server+++async def unprotected_server() -> AsyncGenerator[ASGIServer, None]:+ async with asgi_server(+ create_server(),+ transport="sse",+ host_origin_protection=False,+ ) as server:+ yield server+++class TestSSEConnectionEndpoint:+ @pytest.mark.parametrize(+ ("headers", "expected_status"),+ [+ (OTHER_HOST, 421),+ (OTHER_ORIGIN, 403),+ ],+ )+ async def test_rejects_unlisted_host_or_origin(+ self,+ protected_server: ASGIServer,+ headers: dict[str, str],+ expected_status: int,+ ):+ assert await _get_status(protected_server, headers) == expected_status++ async def test_disabled_protection_opens_stream(+ self,+ unprotected_server: ASGIServer,+ ):+ status = await _get_status(+ unprotected_server,+ {**OTHER_HOST, **OTHER_ORIGIN},+ )++ assert status == 200+++class TestSSEMessageEndpoint:+ @pytest.mark.parametrize(+ ("headers", "expected_status"),+ [+ (OTHER_HOST, 421),+ (OTHER_ORIGIN, 403),+ ],+ )+ async def test_rejects_unlisted_host_or_origin_for_open_session(+ self,+ protected_server: ASGIServer,+ headers: dict[str, str],+ expected_status: int,+ ):+ async with _sse_session(protected_server) as message_url:+ status = await _post_status(protected_server, message_url, headers)+ default_status = await _post_status(protected_server, message_url, {})++ assert status == expected_status+ assert default_status == 202++ async def test_disabled_protection_accepts_message(+ self,+ unprotected_server: ASGIServer,+ ):+ async with _sse_session(unprotected_server) as message_url:+ status = await _post_status(+ unprotected_server,+ message_url,+ {**OTHER_HOST, **OTHER_ORIGIN},+ )++ assert status == 202+++class TestSSEProtectionMatchesStreamableHTTP:+ """The same protection settings give the same guard result on both transports."""++ @pytest.mark.parametrize(+ ("protection", "allowed_hosts", "allowed_origins", "headers", "expected"),+ [+ ("auto", None, None, OTHER_HOST, "host rejected"),+ ("auto", None, None, OTHER_ORIGIN, "origin rejected"),+ ("auto", None, None, {"origin": "http://localhost:3000"}, "allowed"),+ (+ "auto",+ ["mcp.example.com"],+ ["https://app.example.com"],+ {"host": "mcp.example.com", "origin": "https://app.example.com"},+ "allowed",+ ),+ (True, ["mcp.example.com"], None, {"host": "mcp.example.com"}, "allowed"),+ (True, None, None, {"host": "mcp.example.com"}, "host rejected"),+ (False, None, None, {**OTHER_HOST, **OTHER_ORIGIN}, "allowed"),+ ],+ )+ async def test_sse_and_streamable_http_agree(+ self,+ protection: HostOriginProtection,+ allowed_hosts: list[str] | None,+ allowed_origins: list[str] | None,+ headers: dict[str, str],+ expected: GuardResult,+ ):+ results: dict[str, GuardResult] = {}+ for transport in ("http", "sse"):+ async with asgi_server(+ create_server(),+ transport=transport,+ host_origin_protection=protection,+ allowed_hosts=allowed_hosts,+ allowed_origins=allowed_origins,+ ) as server:+ results[transport] = _guard_result(await _get_status(server, headers))++ assert results == {"http": expected, "sse": expected}+++class TestSSEProtectionConfiguration:+ def test_invalid_value_is_rejected(self):+ invalid_value: Any = "always"++ with pytest.raises(ValueError, match="host_origin_protection"):+ create_sse_app(+ server=create_server(),+ message_path="/messages/",+ sse_path="/sse",+ host_origin_protection=invalid_value,+ )++ async def test_client_completes_tool_call_with_protection_enabled(+ self,+ protected_server: ASGIServer,+ ):+ async with Client(protected_server.transport()) as client:+ result = await client.call_tool("greet", {"name": "World"})++ assert result.data == "Hello, World!"++ async def test_setting_protects_running_server(self):+ with temporary_settings(http_host_origin_protection=True):+ async with run_server_async(+ create_server(),+ transport="sse",+ path="/sse",+ ) as url:+ async with httpx2.AsyncClient() as http:+ async with http.stream(+ "GET",+ url,+ headers={"accept": "text/event-stream", **OTHER_HOST},+ ) as response:+ other_host_status = response.status_code++ async with Client(SSETransport(url)) as client:+ result = await client.call_tool("greet", {"name": "World"})++ assert other_host_status == 421+ assert result.data == "Hello, World!"