Skip to content

Commit 97d89b9

Browse files
cliffhallclaude
andcommitted
fix: refuse foreign Origins on the Python servers whatever HOST is
The SDK's DNS-rebinding protection checks Origin only when it binds loopback, so with HOST widened a page on any origin could reach the git, fetch and time tools. Each transport.py now wraps the SDK's app in a localhost-Origin middleware, as the TypeScript servers do with localhostOriginValidation, and runs it under uvicorn itself. The READMEs now say what each endpoint refuses, and that the TypeScript ones send no CORS headers. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 17d9f9e commit 97d89b9

12 files changed

Lines changed: 333 additions & 21 deletions

File tree

‎src/fetch/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ this one, so set it deliberately. Point a client at the URL, such as
343343
}
344344
```
345345

346-
Every other option works as it does over stdio. On loopback the SDK also checks each request's `Host` and `Origin` headers against loopback names, to guard against DNS rebinding.
346+
Every other option works as it does over stdio. A browser page from any origin but localhost is refused with `403`, whatever `HOST` is, to guard against DNS rebinding; on loopback the SDK also checks each request's `Host` header.
347347

348348
## Windows Configuration
349349

‎src/fetch/src/mcp_server_fetch/transport.py‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,25 @@
44
through the SDK's Streamable HTTP app, which answers 2026-07-28 and 2025-era
55
clients alike. It listens on `HOST`:`PORT` from the environment, loopback:3001
66
by default: the same variables, defaults and loopback-first posture as the
7-
TypeScript servers, and on loopback the SDK also turns on its DNS-rebinding
8-
protection (Host and Origin checks).
7+
TypeScript servers.
8+
9+
A browser page may reach it only from a localhost Origin, whatever `HOST` is,
10+
as with the TypeScript servers' `localhostOriginValidation`. The SDK's own
11+
DNS-rebinding protection checks Origin only when it binds loopback, and its
12+
Host check cannot name the addresses of an interface `HOST` widens to, so the
13+
Origin check is this module's middleware; on loopback the SDK's Host and
14+
Origin checks still run behind it.
915
"""
1016

1117
import os
1218
from collections.abc import Mapping
19+
from urllib.parse import urlsplit
1320

21+
import uvicorn
1422
from mcp.server.mcpserver import MCPServer
23+
from starlette.datastructures import Headers
24+
from starlette.responses import PlainTextResponse
25+
from starlette.types import ASGIApp, Receive, Scope, Send
1526

1627
TRANSPORTS = ("stdio", "streamable-http")
1728
DEFAULT_HOST = "127.0.0.1"
@@ -31,11 +42,44 @@ def http_endpoint(env: Mapping[str, str] = os.environ) -> tuple[str, int]:
3142
return host, int(raw)
3243

3344

45+
LOCALHOST_NAMES = ("localhost", "127.0.0.1", "::1")
46+
47+
48+
def origin_allowed(origin: str | None) -> bool:
49+
"""Whether a request with this Origin may proceed: none (a non-browser
50+
client), or one whose host is localhost, 127.0.0.1 or [::1]."""
51+
if origin is None:
52+
return True
53+
try:
54+
hostname = urlsplit(origin).hostname
55+
except ValueError:
56+
return False
57+
return hostname in LOCALHOST_NAMES
58+
59+
60+
class LocalhostOriginMiddleware:
61+
"""Answer an HTTP request from any other Origin with 403 before `app` sees it."""
62+
63+
def __init__(self, app: ASGIApp) -> None:
64+
self.app = app
65+
66+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
67+
if scope["type"] == "http" and not origin_allowed(
68+
Headers(scope=scope).get("origin")
69+
):
70+
response = PlainTextResponse("Invalid Origin header", status_code=403)
71+
await response(scope, receive, send)
72+
return
73+
await self.app(scope, receive, send)
74+
75+
3476
async def run(server: MCPServer, transport: str) -> None:
3577
"""Serve `server` on `transport` until it is stopped."""
3678
if transport == "streamable-http":
3779
host, port = http_endpoint()
38-
await server.run_streamable_http_async(host=host, port=port)
80+
app = LocalhostOriginMiddleware(server.streamable_http_app(host=host))
81+
config = uvicorn.Config(app, host=host, port=port)
82+
await uvicorn.Server(config).serve()
3983
else:
4084
# Both eras (#4853): the SDK's dual-era loop lets the client's first
4185
# request decide. `initialize` gets the 2025-11-25 handshake;

‎src/fetch/tests/test_http.py‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from collections.abc import AsyncIterator
99
from contextlib import asynccontextmanager
1010
from functools import partial
11+
from typing import Any
1112
from unittest.mock import AsyncMock, patch
1213

1314
import anyio
@@ -16,7 +17,13 @@
1617

1718
import mcp_server_fetch
1819
from mcp_server_fetch.server import serve
19-
from mcp_server_fetch.transport import DEFAULT_HOST, DEFAULT_PORT, http_endpoint
20+
from mcp_server_fetch.transport import (
21+
DEFAULT_HOST,
22+
DEFAULT_PORT,
23+
LocalhostOriginMiddleware,
24+
http_endpoint,
25+
origin_allowed,
26+
)
2027

2128
ERAS = [
2229
pytest.param("2026-07-28", "2026-07-28", id="2026-07-28"),
@@ -114,3 +121,55 @@ def test_main_refuses_an_unknown_transport_or_a_bad_port(
114121
assert exit_info.value.code == 2
115122
serve_mock.assert_not_awaited()
116123
assert "error:" in capsys.readouterr().err
124+
125+
126+
@pytest.mark.parametrize(
127+
"origin,allowed",
128+
[
129+
(None, True),
130+
("http://localhost:6274", True),
131+
("http://127.0.0.1", True),
132+
("http://[::1]:3000", True),
133+
("https://evil.example", False),
134+
("http://localhost.evil.example", False),
135+
("http://[::1", False),
136+
("null", False),
137+
],
138+
)
139+
def test_origin_allowed(origin: str | None, allowed: bool) -> None:
140+
assert origin_allowed(origin) is allowed
141+
142+
143+
async def test_middleware_refuses_a_foreign_origin_whatever_the_host() -> None:
144+
"""The check does not depend on the bind address, so it holds under HOST=0.0.0.0."""
145+
reached: list[str] = []
146+
147+
async def app(scope: Any, receive: Any, send: Any) -> None:
148+
reached.append(scope["type"])
149+
150+
sent: list[Any] = []
151+
152+
async def send(message: Any) -> None:
153+
sent.append(message)
154+
155+
async def receive() -> Any:
156+
return {"type": "http.request", "body": b"", "more_body": False}
157+
158+
middleware = LocalhostOriginMiddleware(app)
159+
foreign = {
160+
"type": "http",
161+
"method": "POST",
162+
"path": "/mcp",
163+
"headers": [
164+
(b"host", b"192.168.1.20:3001"),
165+
(b"origin", b"https://evil.example"),
166+
],
167+
}
168+
await middleware(foreign, receive, send)
169+
assert reached == []
170+
assert sent[0]["status"] == 403
171+
172+
local = {**foreign, "headers": [(b"origin", b"http://localhost:6274")]}
173+
await middleware(local, receive, send)
174+
await middleware({"type": "lifespan"}, receive, send)
175+
assert reached == ["http", "lifespan"]

‎src/filesystem/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -414,8 +414,9 @@ npx -y @modelcontextprotocol/server-filesystem --transport streamable-http /User
414414

415415
It listens on `127.0.0.1:3001` unless `HOST` and `PORT` say otherwise (for
416416
example `PORT=8080`); `HOST=0.0.0.0` exposes it to every machine that can reach
417-
this one, so set it deliberately. A browser page can reach it only from a
418-
localhost origin. Point a client at the URL, such as
417+
this one, so set it deliberately. A request from a browser page on any
418+
origin but localhost is refused with `403`, and the endpoint sends no CORS
419+
headers, so it serves clients that are not browser pages. Point a client at the URL, such as
419420
`http://127.0.0.1:3001/mcp`, instead of giving it a command:
420421

421422
```json

‎src/git/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ this one, so set it deliberately. Point a client at the URL, such as
407407
}
408408
```
409409

410-
Every other option works as it does over stdio; `--repository` matters more here, since any client that can reach the port can use the server. On loopback the SDK also checks each request's `Host` and `Origin` headers against loopback names, to guard against DNS rebinding.
410+
Every other option works as it does over stdio; `--repository` matters more here, since any client that can reach the port can use the server. A browser page from any origin but localhost is refused with `403`, whatever `HOST` is, to guard against DNS rebinding; on loopback the SDK also checks each request's `Host` header.
411411

412412
## Debugging
413413

‎src/git/src/mcp_server_git/transport.py‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,25 @@
44
through the SDK's Streamable HTTP app, which answers 2026-07-28 and 2025-era
55
clients alike. It listens on `HOST`:`PORT` from the environment, loopback:3001
66
by default: the same variables, defaults and loopback-first posture as the
7-
TypeScript servers, and on loopback the SDK also turns on its DNS-rebinding
8-
protection (Host and Origin checks).
7+
TypeScript servers.
8+
9+
A browser page may reach it only from a localhost Origin, whatever `HOST` is,
10+
as with the TypeScript servers' `localhostOriginValidation`. The SDK's own
11+
DNS-rebinding protection checks Origin only when it binds loopback, and its
12+
Host check cannot name the addresses of an interface `HOST` widens to, so the
13+
Origin check is this module's middleware; on loopback the SDK's Host and
14+
Origin checks still run behind it.
915
"""
1016

1117
import os
1218
from collections.abc import Mapping
19+
from urllib.parse import urlsplit
1320

21+
import uvicorn
1422
from mcp.server.mcpserver import MCPServer
23+
from starlette.datastructures import Headers
24+
from starlette.responses import PlainTextResponse
25+
from starlette.types import ASGIApp, Receive, Scope, Send
1526

1627
TRANSPORTS = ("stdio", "streamable-http")
1728
DEFAULT_HOST = "127.0.0.1"
@@ -31,11 +42,44 @@ def http_endpoint(env: Mapping[str, str] = os.environ) -> tuple[str, int]:
3142
return host, int(raw)
3243

3344

45+
LOCALHOST_NAMES = ("localhost", "127.0.0.1", "::1")
46+
47+
48+
def origin_allowed(origin: str | None) -> bool:
49+
"""Whether a request with this Origin may proceed: none (a non-browser
50+
client), or one whose host is localhost, 127.0.0.1 or [::1]."""
51+
if origin is None:
52+
return True
53+
try:
54+
hostname = urlsplit(origin).hostname
55+
except ValueError:
56+
return False
57+
return hostname in LOCALHOST_NAMES
58+
59+
60+
class LocalhostOriginMiddleware:
61+
"""Answer an HTTP request from any other Origin with 403 before `app` sees it."""
62+
63+
def __init__(self, app: ASGIApp) -> None:
64+
self.app = app
65+
66+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
67+
if scope["type"] == "http" and not origin_allowed(
68+
Headers(scope=scope).get("origin")
69+
):
70+
response = PlainTextResponse("Invalid Origin header", status_code=403)
71+
await response(scope, receive, send)
72+
return
73+
await self.app(scope, receive, send)
74+
75+
3476
async def run(server: MCPServer, transport: str) -> None:
3577
"""Serve `server` on `transport` until it is stopped."""
3678
if transport == "streamable-http":
3779
host, port = http_endpoint()
38-
await server.run_streamable_http_async(host=host, port=port)
80+
app = LocalhostOriginMiddleware(server.streamable_http_app(host=host))
81+
config = uvicorn.Config(app, host=host, port=port)
82+
await uvicorn.Server(config).serve()
3983
else:
4084
# Both eras (#4853): the SDK's dual-era loop lets the client's first
4185
# request decide. `initialize` gets the 2025-11-25 handshake;

‎src/git/tests/test_http.py‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import socket
77
from collections.abc import AsyncIterator
88
from contextlib import asynccontextmanager
9+
from typing import Any
910
from unittest.mock import AsyncMock, patch
1011

1112
import anyio
@@ -15,7 +16,13 @@
1516

1617
import mcp_server_git
1718
from mcp_server_git.server import serve
18-
from mcp_server_git.transport import DEFAULT_HOST, DEFAULT_PORT, http_endpoint
19+
from mcp_server_git.transport import (
20+
DEFAULT_HOST,
21+
DEFAULT_PORT,
22+
LocalhostOriginMiddleware,
23+
http_endpoint,
24+
origin_allowed,
25+
)
1926

2027
ERAS = [
2128
pytest.param("2026-07-28", "2026-07-28", id="2026-07-28"),
@@ -105,3 +112,55 @@ def test_main_refuses_an_unknown_transport_or_a_bad_port(
105112
assert result.exit_code == 2
106113
serve_mock.assert_not_awaited()
107114
assert "Error" in result.output
115+
116+
117+
@pytest.mark.parametrize(
118+
"origin,allowed",
119+
[
120+
(None, True),
121+
("http://localhost:6274", True),
122+
("http://127.0.0.1", True),
123+
("http://[::1]:3000", True),
124+
("https://evil.example", False),
125+
("http://localhost.evil.example", False),
126+
("http://[::1", False),
127+
("null", False),
128+
],
129+
)
130+
def test_origin_allowed(origin: str | None, allowed: bool) -> None:
131+
assert origin_allowed(origin) is allowed
132+
133+
134+
async def test_middleware_refuses_a_foreign_origin_whatever_the_host() -> None:
135+
"""The check does not depend on the bind address, so it holds under HOST=0.0.0.0."""
136+
reached: list[str] = []
137+
138+
async def app(scope: Any, receive: Any, send: Any) -> None:
139+
reached.append(scope["type"])
140+
141+
sent: list[Any] = []
142+
143+
async def send(message: Any) -> None:
144+
sent.append(message)
145+
146+
async def receive() -> Any:
147+
return {"type": "http.request", "body": b"", "more_body": False}
148+
149+
middleware = LocalhostOriginMiddleware(app)
150+
foreign = {
151+
"type": "http",
152+
"method": "POST",
153+
"path": "/mcp",
154+
"headers": [
155+
(b"host", b"192.168.1.20:3001"),
156+
(b"origin", b"https://evil.example"),
157+
],
158+
}
159+
await middleware(foreign, receive, send)
160+
assert reached == []
161+
assert sent[0]["status"] == 403
162+
163+
local = {**foreign, "headers": [(b"origin", b"http://localhost:6274")]}
164+
await middleware(local, receive, send)
165+
await middleware({"type": "lifespan"}, receive, send)
166+
assert reached == ["http", "lifespan"]

‎src/memory/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,9 @@ npx -y @modelcontextprotocol/server-memory --transport streamable-http
167167

168168
It listens on `127.0.0.1:3001` unless `HOST` and `PORT` say otherwise (for
169169
example `PORT=8080`); `HOST=0.0.0.0` exposes it to every machine that can reach
170-
this one, so set it deliberately. A browser page can reach it only from a
171-
localhost origin. Point a client at the URL, such as
170+
this one, so set it deliberately. A request from a browser page on any
171+
origin but localhost is refused with `403`, and the endpoint sends no CORS
172+
headers, so it serves clients that are not browser pages. Point a client at the URL, such as
172173
`http://127.0.0.1:3001/mcp`, instead of giving it a command:
173174

174175
```json

‎src/sequentialthinking/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,9 @@ npx -y @modelcontextprotocol/server-sequential-thinking --transport streamable-h
230230

231231
It listens on `127.0.0.1:3001` unless `HOST` and `PORT` say otherwise (for
232232
example `PORT=8080`); `HOST=0.0.0.0` exposes it to every machine that can reach
233-
this one, so set it deliberately. A browser page can reach it only from a
234-
localhost origin. Point a client at the URL, such as
233+
this one, so set it deliberately. A request from a browser page on any
234+
origin but localhost is refused with `403`, and the endpoint sends no CORS
235+
headers, so it serves clients that are not browser pages. Point a client at the URL, such as
235236
`http://127.0.0.1:3001/mcp`, instead of giving it a command:
236237

237238
```json

‎src/time/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ this one, so set it deliberately. Point a client at the URL, such as
255255
}
256256
```
257257

258-
Every other option works as it does over stdio. On loopback the SDK also checks each request's `Host` and `Origin` headers against loopback names, to guard against DNS rebinding.
258+
Every other option works as it does over stdio. A browser page from any origin but localhost is refused with `403`, whatever `HOST` is, to guard against DNS rebinding; on loopback the SDK also checks each request's `Host` header.
259259

260260
## Example Interactions
261261

0 commit comments

Comments
 (0)