fix(mcp): check Host and Origin on the Streamable HTTP transport (#4852)

## Description

`headroom mcp serve --transport http` built the MCP SDK's
`StreamableHTTPSessionManager` without `security_settings`. With no
settings, the SDK's transport security middleware turns its Host/Origin
validation off, so the server answered whatever `Host` and `Origin` a
request carried. A page whose hostname is pointed at 127.0.0.1 could
then reach the loopback MCP server from the user's browser and call its
tools (retrieve, compress, stats).

The session manager now gets `TransportSecuritySettings` derived from
the bind the operator asked for:

- loopback bind (`127.0.0.1`, `localhost`, `::1`) or wildcard bind
(`0.0.0.0`, `::`): `Host` must be `127.0.0.1:<port>`, `localhost:<port>`
or `[::1]:<port>`;
- any other bind address: `Host` must be that address and port;
- `HEADROOM_MCP_ALLOWED_HOSTS` (comma-separated `name:port`) adds names
for clients that reach the server through a hostname or a reverse proxy.
A wildcard bind without it logs a warning saying so.

`Origin`, when present, must be `http(s)://` one of the allowed hosts.
MCP clients that send no `Origin` are unaffected.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/ccr/mcp_http.py`: new `transport_security_settings(host,
port)`; `create_streamable_http_session_manager` takes `host`/`port`
(defaulting to the CLI defaults `127.0.0.1:8788`) and passes the
settings; `serve_streamable_http` threads its bind through.
- `tests/test_ccr_mcp_http.py`: the existing round-trip test now
addresses the server by its bind; new tests for a foreign `Host` (421)
and a foreign `Origin` (403), and for `HEADROOM_MCP_ALLOWED_HOSTS` on a
wildcard bind.
- `docs/content/docs/mcp.mdx`: one paragraph on the Host rule and
`HEADROOM_MCP_ALLOWED_HOSTS`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# mcp 2.3.0 (the pinned range is >=2.2.0,<3.0.0)
$ pytest tests/test_ccr_mcp_http.py
============================== 4 passed in 1.29s ===============================

# same request on origin/main vs this branch (in-process ASGI, mcp 2.3.0)
== origin/main
Host=page.example:8788 Origin=http://page.example:8788 -> HTTP 200 session=yes
Host=127.0.0.1:8788 Origin=https://page.example -> HTTP 200 session=yes
Host=127.0.0.1:8788 Origin=- -> HTTP 200 session=yes
== this branch
Host=page.example:8788 Origin=http://page.example:8788 -> HTTP 421 session=no
Host=127.0.0.1:8788 Origin=https://page.example -> HTTP 403 session=no
Host=127.0.0.1:8788 Origin=- -> HTTP 200 session=yes

$ ruff check headroom/ccr/mcp_http.py tests/test_ccr_mcp_http.py
All checks passed!
$ mypy headroom/ccr/mcp_http.py --ignore-missing-imports
Success: no issues found in 1 source file
```

The new tests call `create_streamable_http_session_manager(..., host=,
port=)`, which does not exist on main, so on main they fail with a
`TypeError`; the probe above is the behavioural before/after.

## Real Behavior Proof

- Environment: macOS, Python 3.12, mcp 2.3.0, `headroom mcp serve
--transport http --host 127.0.0.1 --port 18931`.
- Exact command / steps: `curl -X POST http://127.0.0.1:18931/mcp` with
an `initialize` body, `Content-Type: application/json`, `Accept:
application/json, text/event-stream`, and (a) `Host: page.example:18931`
+ `Origin: http://page.example:18931`, (b) `Origin:
https://page.example`, (c) no Origin.
- Observed result:
  ```text
  Host: page.example:18931 / Origin: http://page.example:18931 -> 421
  Host: 127.0.0.1:18931 / Origin: https://page.example -> 403
  Host: 127.0.0.1:18931 / (no Origin) -> 200
  server log: WARNING: Invalid Host header: page.example:18931
              WARNING: Invalid Origin header: https://page.example
  ```
- Not tested: a real remote client through `HEADROOM_MCP_ALLOWED_HOSTS`
(covered by the unit test).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: the HTTP transport now refuses a
`Host` that is not the bind address (421) and a foreign browser `Origin`
(403). The stdio transport (the default) is untouched. Someone serving
on `0.0.0.0` and connecting remotely by hostname or IP must list that
name in `HEADROOM_MCP_ALLOWED_HOSTS`; the server logs a warning on such
a bind.
- Kill switch / disable path: `HEADROOM_MCP_ALLOWED_HOSTS=name:port,...`
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

Fix adapted from a proposal by Anton Dzyatkovskiy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4852"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-14 10:46:00 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 02dfdd8f89
commit 70ba72138d
3 changed files with 151 additions and 6 deletions
+2
View File
@@ -159,6 +159,8 @@ For multiple proxy instances, register one stdio MCP server per proxy URL:
If you need Streamable HTTP instead of stdio, run `headroom mcp serve --transport http` and point your MCP host at that endpoint. The default path is `/mcp`, and the default port is `8788`.
The HTTP transport only answers requests whose `Host` header names the address it is bound to (`127.0.0.1`, `localhost` or `[::1]` with the bound port for a loopback or `0.0.0.0` bind), and refuses browser requests from any other origin. If clients reach it through another name, such as a hostname or a reverse proxy, list them in `HEADROOM_MCP_ALLOWED_HOSTS` (comma-separated) exactly as clients send them in `Host`: `name:port`, or just `name` when the port is the scheme default (80 or 443, e.g. behind a TLS reverse proxy).
Do not assume that a running proxy exposes an HTTP MCP endpoint at `/mcp`. The proxy serves its own API; it does not automatically provide the MCP HTTP transport.
### `command: "headroom"` fails to start
+61 -4
View File
@@ -2,13 +2,26 @@
from __future__ import annotations
import logging
import os
from typing import Any
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import TransportSecuritySettings
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.types import Receive, Scope, Send
from headroom.proxy.loopback_guard import is_loopback_host
logger = logging.getLogger(__name__)
#: Extra ``Host`` values (``name:port``, comma-separated) the HTTP transport
#: accepts, for a server reached through a hostname or a reverse proxy.
ALLOWED_HOSTS_ENV = "HEADROOM_MCP_ALLOWED_HOSTS"
_LOOPBACK_NAMES = ("127.0.0.1", "localhost", "[::1]")
_WILDCARD_BINDS = ("0.0.0.0", "::", "")
def _normalize_path(path: str) -> str:
normalized = path.strip()
@@ -29,9 +42,53 @@ class StreamableHTTPASGIApp:
await self.session_manager.handle_request(scope, receive, send)
def create_streamable_http_session_manager(server: Any) -> StreamableHTTPSessionManager:
"""Build the SDK session manager for an existing MCP server."""
return StreamableHTTPSessionManager(app=server.server)
def transport_security_settings(host: str, port: int) -> TransportSecuritySettings:
"""Host/Origin allowlist for a server bound to ``host:port``.
The SDK checks neither header unless it is given settings. Without the
Host check, a page whose hostname is re-pointed at 127.0.0.1 can reach
this server from the user's browser. A loopback or wildcard bind accepts
the loopback names; any other bind accepts its own address. More names
come from ``HEADROOM_MCP_ALLOWED_HOSTS``.
"""
bare = host.strip("[]")
bound = f"[{bare}]" if ":" in bare else bare
if bare in _WILDCARD_BINDS or is_loopback_host(bare):
names = list(_LOOPBACK_NAMES)
if bare not in _WILDCARD_BINDS and bound not in names:
names.append(bound)
else:
names = [bound]
allowed_hosts = [f"{name}:{port}" for name in names]
if port in (80, 443):
# Clients leave a scheme-default port out of Host and Origin.
allowed_hosts.extend(names)
extra = [entry.strip() for entry in os.environ.get(ALLOWED_HOSTS_ENV, "").split(",")]
allowed_hosts.extend(entry for entry in extra if entry)
if bare in _WILDCARD_BINDS and not any(extra):
logger.warning(
"MCP HTTP server bound to %s accepts only loopback Host headers; "
"set %s=<name:port,...> for the names remote clients use",
host or "all interfaces",
ALLOWED_HOSTS_ENV,
)
return TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=allowed_hosts,
allowed_origins=[
f"{scheme}://{allowed}" for allowed in allowed_hosts for scheme in ("http", "https")
],
)
def create_streamable_http_session_manager(
server: Any, *, host: str = "127.0.0.1", port: int = 8788
) -> StreamableHTTPSessionManager:
"""Build the SDK session manager for an existing MCP server bound to ``host:port``."""
return StreamableHTTPSessionManager(
app=server.server,
security_settings=transport_security_settings(host, port),
)
def create_streamable_http_app(
@@ -66,7 +123,7 @@ async def serve_streamable_http(
"""Serve the MCP server over Streamable HTTP with uvicorn."""
import uvicorn
session_manager = create_streamable_http_session_manager(server)
session_manager = create_streamable_http_session_manager(server, host=host, port=port)
starlette_app = create_streamable_http_app(session_manager, path=path, debug=debug)
config = uvicorn.Config(
starlette_app,
+88 -2
View File
@@ -40,11 +40,11 @@ async def test_streamable_http_initialize_and_list_tools() -> None:
async with session_manager.run():
async with httpx2.AsyncClient(
transport=transport,
base_url="http://testserver",
base_url="http://127.0.0.1:8788",
event_hooks={"response": [record_session_id]},
) as http_client:
async with streamable_http_client(
"http://testserver/mcp",
"http://127.0.0.1:8788/mcp",
http_client=http_client,
terminate_on_close=False,
) as (read_stream, write_stream):
@@ -58,3 +58,89 @@ async def test_streamable_http_initialize_and_list_tools() -> None:
assert "headroom_compress" in tool_names
assert "headroom_retrieve" in tool_names
assert "headroom_stats" in tool_names
_INITIALIZE = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "test", "version": "0"},
},
}
async def _post_initialize(app, base_url: str, headers: dict[str, str]) -> httpx2.Response:
async with httpx2.AsyncClient(
transport=httpx2.ASGITransport(app=app), base_url=base_url
) as http_client:
return await http_client.post(
"/mcp",
json=_INITIALIZE,
headers={"Accept": "application/json, text/event-stream", **headers},
)
@pytest.mark.parametrize(
("base_url", "headers", "status"),
[
# A page whose hostname now resolves to 127.0.0.1: Host names that page.
("http://page.example:8788", {"Origin": "http://page.example:8788"}, 421),
# Right Host, but the request comes from another page's script.
("http://127.0.0.1:8788", {"Origin": "https://page.example"}, 403),
],
)
async def test_streamable_http_refuses_foreign_host_or_origin(
base_url: str, headers: dict[str, str], status: int
) -> None:
session_manager = create_streamable_http_session_manager(
create_ccr_mcp_server(), host="127.0.0.1", port=8788
)
app = create_streamable_http_app(session_manager, path="/mcp")
async with session_manager.run():
response = await _post_initialize(app, base_url, headers)
assert response.status_code == status
assert "mcp-session-id" not in response.headers
async def test_streamable_http_accepts_configured_host(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_MCP_ALLOWED_HOSTS", "mcp.internal:8788")
session_manager = create_streamable_http_session_manager(
create_ccr_mcp_server(), host="0.0.0.0", port=8788
)
app = create_streamable_http_app(session_manager, path="/mcp")
async with session_manager.run():
configured = await _post_initialize(app, "http://mcp.internal:8788", {})
loopback = await _post_initialize(app, "http://localhost:8788", {})
other = await _post_initialize(app, "http://other.internal:8788", {})
assert configured.status_code == 200, configured.text
assert loopback.status_code == 200, loopback.text
assert other.status_code == 421
@pytest.mark.parametrize(
("host", "port", "base_url"),
[
("127.0.0.1", 80, "http://localhost"),
("[::1]", 8788, "http://[::1]:8788"),
("127.0.0.2", 8788, "http://127.0.0.2:8788"),
],
)
async def test_streamable_http_accepts_loopback_as_clients_address_it(
host: str, port: int, base_url: str
) -> None:
session_manager = create_streamable_http_session_manager(
create_ccr_mcp_server(), host=host, port=port
)
app = create_streamable_http_app(session_manager, path="/mcp")
async with session_manager.run():
response = await _post_initialize(app, base_url, {"Origin": base_url})
assert response.status_code == 200, response.text