modelcontextprotocol / modelcontextprotocol/python-sdk
TransportSecuritySettings.allowed_hosts is compared case-sensitively (NOT RFC 9110 compliant), so an uppercase host entry (the Windows default) rejects every fetch-based client with 421
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 24.3k
- 派生
- 4k
- 平均合并
- 1 天 1 小时
- 30 天内合并 PR
- 31
描述
Initial Checks
- I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
Release line
2.x (current stable)
Description
Summary
TransportSecurityMiddleware._validate_host() compares the incoming Host header
against allowed_hosts case-sensitively. Host names are case-insensitive per RFC 9110,
and every WHATWG-URL based client (undici, fetch, browsers, and therefore
mcp-remote) lowercases the URL host before sending it.
On Windows this is the default path into the bug, because %COMPUTERNAME% is always
uppercase. Deriving allowed_hosts from the machine name, which is the obvious thing
to do, yields an entry like MYHOST:*. Clients then send host: myhost:8000, the
comparison fails, and the server returns 421 to every request while being configured
exactly as intended.
Expected behavior
allowed_hosts matching should be case-insensitive. RFC 9110 is explicit:
The scheme and host are case-insensitive and normally provided in lowercase; all
other components are compared in a case-sensitive manner.
Actual behavior
Observed against a live Streamable HTTP server configured with allowed_hosts=["MYHOST:*"],
varying only the Host header and holding everything else byte-identical:
Host: sent |
Result |
|---|---|
MYHOST:8000 (uppercase, matches config) |
200 OK |
myhost:8000 (what any fetch client sends) |
421 Misdirected Request |
10.0.0.5:8000 (by IP) |
421 Misdirected Request |
The uppercase form is the only one accepted, and no client can be made to send it.
Node:
new URL('http://MYHOST:8000/mcp').host // => "myhost:8000"
The WHATWG URL standard requires that lowercasing, so this is not configurable
client-side. Supplying an explicit Host header does not help either: undici treats
Host as a forbidden header and overwrites it from the URL.
Root cause
src/mcp/server/transport_security.py (lines 50-70 as of v2.1.1):
def _validate_host(self, host: str | None) -> bool:
"""Validate the Host header against allowed values."""
if not host:
logger.warning("Missing Host header in request")
return False
# Check exact match first
if host in self.settings.allowed_hosts: # case-sensitive
return True
# Check wildcard port patterns
for allowed in self.settings.allowed_hosts:
if allowed.endswith(":*"):
base_host = allowed[:-2]
if host.startswith(base_host + ":"): # case-sensitive prefix
return True
logger.warning(f"Invalid Host header: {host}")
return False
With allowed_hosts = ["MYHOST:*"], base_host becomes "MYHOST" and the test is
"myhost:8000".startswith("MYHOST:"), which is False. There is no .lower()
anywhere in this function; the file's only .lower() call is the content-type check
on line 96.
Suggested fix
Normalize both sides:
def _validate_host(self, host: str | None) -> bool:
if not host:
logger.warning("Missing Host header in request")
return False
host = host.lower()
allowed_hosts = [a.lower() for a in self.settings.allowed_hosts]
if host in allowed_hosts:
return True
for allowed in allowed_hosts:
if allowed.endswith(":*") and host.startswith(allowed[:-2] + ":"):
return True
logger.warning(f"Invalid Host header: {host}")
return False
_validate_origin() has the same structure and the same issue for its scheme and host
portions.
This direction of change is safe. The current behavior is stricter than the
configuration expresses, so it fails closed: it rejects hosts it was told to allow and
can never accept one it was not. Lowercasing aligns it with the documented intent
rather than loosening it.
Secondary issue: the 421 never reaches the client
Worth fixing alongside, because it is what makes this expensive to diagnose.
The middleware rejects on headers alone and the response completes without the request
body being drained. A client that streams its request body has its write cut short and
then reports an error about its own request instead of surfacing the 421. With undici
this appears as:
TypeError: fetch failed
[cause]: RequestContentLengthMismatchError: Request body length does not match content-length header
code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
Neither the 421 nor the word "host" appears anywhere in the client output, and the
request body was in fact well formed: every body captured on the wire matched its
declared Content-Length exactly. That error points squarely at the client, which is
where the debugging time goes.
Draining the request body before returning the 421 would let clients report the real
status and make this class of misconfiguration self-diagnosing.
Impact
Any Windows Streamable HTTP deployment that derives allowed_hosts from the machine
name is unreachable by every fetch-based client, and the failure surfaces as a
client-side error that never mentions hosts. Linux deployments mostly escape it because
hostnames there are already lowercase, which is likely why this has not been reported
before.
Example Code
"""Minimal reproduction: case-sensitive allowed_hosts matching.
On Windows, %COMPUTERNAME% is uppercase, so configuring allowed_hosts from the
machine name produces an uppercase entry. Every WHATWG-URL client lowercases the
host before sending it, so the request is rejected with 421.
"""
from mcp.server.transport_security import (
TransportSecurityMiddleware,
TransportSecuritySettings,
)
# What you get on Windows from os.environ["COMPUTERNAME"]
settings = TransportSecuritySettings(allowed_hosts=["MYHOST:*"])
mw = TransportSecurityMiddleware(settings)
print(mw._validate_host("MYHOST:8000")) # True - but no client sends this
print(mw._validate_host("myhost:8000")) # False - what every client actually sends
# Why no client sends the uppercase form (Node / undici / browsers):
# new URL('http://MYHOST:8000/mcp').host -> "myhost:8000"
# The WHATWG URL standard mandates the lowercasing, so it cannot be worked
# around from the client side.
Python & MCP Python SDK
Python 3.13.2 (CPython, Windows x86_64)
mcp 2.0.0
Client: mcp-remote 0.8.3 on Node 22.18.0
Transport: Streamable HTTP, stateless_http=True, uvicorn
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 src/mcp/server/transport_security.py 中的 TransportSecurityMiddleware._validate_host() 开始,并将其行为与 _validate_origin() 进行比较。使用 issue 中的示例复现 allowed_hosts 为大写的情况,然后验证匹配是否遵循文档所述的主机名不区分大小写行为,以及被拒绝的流式请求是否会暴露 421 响应,而不只是出现客户端 body 错误。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend-api-design, security
- Issue 类型
- 缺陷
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 活跃
- 描述清晰度
- 描述清楚
- 新手友好度
- 68/100