Skip to content

Commit 7635572

Browse files
authored
Merge pull request #5300 from modelcontextprotocol/v2/fix/5134-fetch-missing-content-type
fix(fetch): treat a header-less response as HTML only when its body is
2 parents 8520fb2 + 593dab9 commit 7635572

2 files changed

Lines changed: 194 additions & 1 deletion

File tree

‎src/fetch/src/mcp_server_fetch/server.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,18 @@ async def check_may_autonomously_fetch_url(
319319
)
320320

321321

322+
def _body_looks_like_html(page_raw: str) -> bool:
323+
"""Whether a body served with no Content-Type is an HTML document.
324+
325+
A missing header says nothing about the payload, so only a body that opens
326+
(after any byte-order mark and whitespace) with an HTML doctype or an
327+
``<html`` tag is simplified; JSON, plain text and the like come back raw
328+
rather than being forced through readability (#5134).
329+
"""
330+
start = page_raw.lstrip("\ufeff").lstrip()[:20].lower()
331+
return start.startswith(("<!doctype html", "<html"))
332+
333+
322334
async def fetch_url(
323335
url: str,
324336
user_agent: str,
@@ -374,7 +386,10 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
374386

375387
content_type = response.headers.get("content-type", "")
376388
is_page_html = (
377-
"<html" in page_raw[:100] or "text/html" in content_type or not content_type
389+
"<html" in page_raw[:100]
390+
or "text/html" in content_type.lower()
391+
or "application/xhtml+xml" in content_type.lower()
392+
or (not content_type and _body_looks_like_html(page_raw))
378393
)
379394

380395
if is_page_html and not force_raw:
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
"""Protocol-level tests for responses served without a Content-Type (#5134).
2+
3+
A missing Content-Type header used to make every body count as HTML, so JSON,
4+
plain text and other payloads were pushed through readability and came back
5+
altered or as a simplification error. Now a header-less body is simplified
6+
only when it itself opens like an HTML document (an HTML doctype or an
7+
``<html`` tag, after any byte-order mark and whitespace); anything else comes
8+
back raw. These tests drive ``serve()`` through an MCP client with HTTP served
9+
by ``harness.FakeWeb``, and also pin the HTML media types that are still
10+
simplified whatever the body looks like.
11+
"""
12+
13+
from __future__ import annotations
14+
15+
import sys
16+
17+
import httpx
18+
import pytest
19+
from mcp.types import CallToolResult
20+
21+
from mcp_server_fetch.server import _body_looks_like_html
22+
23+
from .harness import FakeWeb, connect
24+
25+
PAGE = "https://example.com/page"
26+
BOM = "\ufeff"
27+
28+
ARTICLE_BODY = """<head><title>Test Page</title></head><body>
29+
<article>
30+
<h1>Hello World</h1>
31+
<p>This is a <a href="https://example.com/x">link</a> in a test paragraph
32+
with enough words to count as the main content of the page.</p>
33+
<h2>Sub heading</h2>
34+
<p>More text here.</p>
35+
</article>
36+
</body>"""
37+
38+
39+
def text_of(result: CallToolResult) -> str:
40+
data = result.model_dump(by_alias=True, mode="json", exclude_none=True)
41+
assert data["isError"] is False
42+
assert len(data["content"]) == 1
43+
assert data["content"][0]["type"] == "text"
44+
return data["content"][0]["text"]
45+
46+
47+
def headerless(body: str) -> httpx.Response:
48+
response = httpx.Response(200, content=body.encode())
49+
assert "content-type" not in response.headers
50+
return response
51+
52+
53+
async def fetch(web: FakeWeb, response: httpx.Response) -> str:
54+
web.add(PAGE, response)
55+
async with connect(ignore_robots_txt=True) as (session, _):
56+
result = await session.call_tool("fetch", {"url": PAGE})
57+
return text_of(result)
58+
59+
60+
def assert_raw(text: str, body: str) -> None:
61+
assert "Page failed to be simplified" not in text
62+
assert text.endswith(f"Contents of {PAGE}:\n{body}")
63+
assert "cannot be simplified to markdown, but here is the raw content:" in text
64+
65+
66+
def assert_simplified(text: str) -> None:
67+
assert text.startswith(f"Contents of {PAGE}:\n")
68+
assert "[link](https://example.com/x)" in text
69+
assert "## Sub heading" in text
70+
assert "<article>" not in text
71+
72+
73+
@pytest.mark.parametrize(
74+
"body",
75+
[
76+
'{"key": "value", "snake_case": "*starred*"}',
77+
"[1, 2, 3]",
78+
"just some plain_text with *asterisks*\nand a second line",
79+
"a,b,c\n1,2,3\n",
80+
],
81+
ids=["json-object", "json-array", "plain-text", "csv"],
82+
)
83+
async def test_non_html_without_content_type_is_returned_raw(
84+
web: FakeWeb, body: str
85+
) -> None:
86+
assert_raw(await fetch(web, headerless(body)), body)
87+
88+
89+
async def test_empty_body_without_content_type_is_not_simplified(
90+
web: FakeWeb,
91+
) -> None:
92+
# An empty body used to reach readability and fail to simplify; now it is
93+
# raw content with nothing in it, which the tool reports as such.
94+
text = await fetch(web, headerless(""))
95+
assert "Page failed to be simplified" not in text
96+
assert "cannot be simplified to markdown, but here is the raw content:" in text
97+
assert text.endswith("<error>No more content available.</error>")
98+
99+
100+
@pytest.mark.usefixtures("node_readability")
101+
@pytest.mark.parametrize(
102+
"body",
103+
[
104+
pytest.param(f"<!DOCTYPE html>\n{ARTICLE_BODY}", id="doctype-upper"),
105+
pytest.param(f"<!doctype html>{ARTICLE_BODY}", id="doctype-lower"),
106+
pytest.param(
107+
f"{BOM}\n <!DocType HTML>\n{ARTICLE_BODY}",
108+
id="bom-and-whitespace",
109+
# readabilipy 0.2.0 writes the page to a temp file in the locale
110+
# encoding, which cannot hold a BOM on Windows (cp1252). The
111+
# detection itself is covered on every platform by
112+
# test_body_detection_skips_bom_and_whitespace below.
113+
marks=pytest.mark.skipif(
114+
sys.platform == "win32",
115+
reason="readabilipy 0.2.0 cannot extract non-cp1252 pages on Windows (#5303)",
116+
),
117+
),
118+
# More leading whitespace than the 100-character "<html" window.
119+
pytest.param(f"{' ' * 120}<HTML>{ARTICLE_BODY}</HTML>", id="long-indent"),
120+
],
121+
)
122+
async def test_html_without_content_type_is_still_simplified(
123+
web: FakeWeb, body: str
124+
) -> None:
125+
assert_simplified(await fetch(web, headerless(body)))
126+
127+
128+
@pytest.mark.usefixtures("node_readability")
129+
@pytest.mark.parametrize(
130+
"content_type",
131+
[
132+
"application/xhtml+xml",
133+
"application/xhtml+xml; charset=utf-8",
134+
"Text/HTML; charset=UTF-8",
135+
],
136+
)
137+
async def test_html_media_types_are_simplified(web: FakeWeb, content_type: str) -> None:
138+
# The body carries no "<html" tag, so only the header can make it HTML.
139+
response = httpx.Response(
140+
200, content=ARTICLE_BODY.encode(), headers={"content-type": content_type}
141+
)
142+
assert_simplified(await fetch(web, response))
143+
144+
145+
async def test_doctype_alone_does_not_override_a_declared_content_type(
146+
web: FakeWeb,
147+
) -> None:
148+
# Sniffing the doctype applies only when the header is missing.
149+
body = f"<!doctype html>{ARTICLE_BODY}"
150+
response = httpx.Response(
151+
200, content=body.encode(), headers={"content-type": "text/plain"}
152+
)
153+
assert_raw(await fetch(web, response), body)
154+
155+
156+
@pytest.mark.parametrize(
157+
"body, expected",
158+
[
159+
(f"{BOM}<!doctype html><p>x</p>", True),
160+
(f"{BOM}\n <!DocType HTML>\n<p>x</p>", True),
161+
(f"{BOM} \t\r\n<HTML><p>x</p></HTML>", True),
162+
(f'{BOM}{{"key": "value"}}', False),
163+
(f"{BOM}plain text", False),
164+
("", False),
165+
],
166+
ids=[
167+
"bom-doctype",
168+
"bom-whitespace-doctype",
169+
"bom-html",
170+
"bom-json",
171+
"bom-text",
172+
"empty",
173+
],
174+
)
175+
def test_body_detection_skips_bom_and_whitespace(body: str, expected: bool) -> None:
176+
# Runs on every platform: what #5134 decides, without readabilipy's
177+
# extraction (which cannot handle a BOM on Windows, #5303).
178+
assert _body_looks_like_html(body) is expected

0 commit comments

Comments
 (0)