Skip to content

Commit e50ba17

Browse files
cliffhallclaude
andcommitted
fix(fetch): decode a page by the charset its HTML declares
When the Content-Type header names no charset, fetch_url decoded the body with httpx's UTF-8 default, so a page declaring a legacy encoding only in <meta charset> or <meta http-equiv="Content-Type"> came back garbled. decode_page now scans the first 1024 bytes of an HTML or untyped body for that declaration, after a BOM and the header charset, and falls back to the old decoding for an unknown or non-web codec. Closes #5199 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent f72fdbd commit e50ba17

2 files changed

Lines changed: 232 additions & 1 deletion

File tree

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

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,58 @@ def make_client(proxy_url: str | None) -> httpx.AsyncClient:
257257
)
258258

259259

260+
def decode_page(response: httpx.Response) -> str:
261+
"""Decode a fetched body, honoring a charset the HTML declares (#5199).
262+
263+
httpx's ``response.text`` uses the Content-Type header's charset, and
264+
UTF-8 without one, so a page that declares a legacy encoding only in a
265+
``<meta charset>`` or ``<meta http-equiv="Content-Type">`` tag came back
266+
garbled. Following the HTML encoding-sniffing order, kept simple: a byte
267+
order mark or a header charset wins (httpx already honors the header), and
268+
otherwise the first 1024 bytes of an HTML (or untyped) body are scanned
269+
for a declaration. A declaration Python does not know, or one that names
270+
a codec that is not a web text encoding, is ignored, and the body is
271+
decoded as before.
272+
"""
273+
# Imported here so the helper stays one self-contained block of this file.
274+
import codecs
275+
import re
276+
277+
content = response.content
278+
content_type = response.headers.get("content-type", "").lower()
279+
if (
280+
response.charset_encoding is not None
281+
or (content_type and "html" not in content_type)
282+
or content.startswith(
283+
(codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)
284+
)
285+
):
286+
return response.text
287+
288+
match = re.search(
289+
rb"""<meta\b[^>]*?charset\s*=\s*["']?\s*([A-Za-z0-9_.:-]+)""",
290+
content[:1024],
291+
re.IGNORECASE,
292+
)
293+
if match is None:
294+
return response.text
295+
try:
296+
name = codecs.lookup(match.group(1).decode("ascii")).name
297+
# A UTF-16/32 declaration in an ASCII-compatible document cannot be
298+
# true, so the HTML standard reads it as UTF-8.
299+
if name.startswith(("utf-16", "utf-32")):
300+
name = "utf-8"
301+
# Python codecs that are not web text encodings: decoding a page with
302+
# them would mangle it rather than fix it.
303+
if name in ("idna", "punycode", "unicode-escape", "raw-unicode-escape"):
304+
return response.text
305+
return content.decode(name, errors="replace")
306+
except (LookupError, UnicodeError):
307+
# An unknown charset, a non-text codec (base64, rot13, …) or one that
308+
# refuses to decode at all (``undefined``).
309+
return response.text
310+
311+
260312
async def check_may_autonomously_fetch_url(
261313
url: str,
262314
user_agent: str,
@@ -357,7 +409,7 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
357409
f"Failed to fetch {url} - status code {response.status_code}"
358410
)
359411

360-
page_raw = response.text
412+
page_raw = decode_page(response)
361413

362414
content_type = response.headers.get("content-type", "")
363415
is_page_html = (
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
"""Protocol-level tests for decoding a page by the charset its HTML declares (#5199).
2+
3+
httpx decodes a body by the Content-Type header's charset and falls back to
4+
UTF-8 without one, so a legacy-encoded page that names its charset only in a
5+
``<meta charset>`` or ``<meta http-equiv="Content-Type">`` tag came back
6+
garbled. ``decode_page`` now scans the head of an HTML (or untyped) body for
7+
that declaration when the header names none. These tests drive the real
8+
server through an MCP client with HTTP served by ``harness.FakeWeb``, and pin
9+
both the fix and its edges: the header and a byte order mark still win, a
10+
declaration on a non-HTML body or past the first 1024 bytes is ignored, and an
11+
unknown or unusable declared charset falls back to the old decoding.
12+
13+
Most cases fetch with ``raw: true`` so the decoded text reaches the client
14+
untouched by HTML extraction; one case goes through extraction to show the
15+
Markdown is right too.
16+
"""
17+
18+
from __future__ import annotations
19+
20+
from typing import Any
21+
22+
import httpx
23+
import pytest
24+
from mcp import ClientSession
25+
from mcp.types import CallToolResult
26+
27+
from .harness import FakeWeb, connect
28+
29+
PAGE = "https://example.com/page"
30+
ROBOTS = "https://example.com/robots.txt"
31+
32+
JAPANESE = "日本語のページです"
33+
RUSSIAN = "Привет, мир"
34+
KOREAN = "안녕하세요 세계"
35+
CHINESE = "你好,世界"
36+
37+
38+
def text_of(result: CallToolResult) -> str:
39+
assert not result.is_error, result
40+
data = result.model_dump(by_alias=True, mode="json", exclude_none=True)
41+
assert len(data["content"]) == 1
42+
return data["content"][0]["text"]
43+
44+
45+
def page(body: bytes, content_type: str | None = "text/html") -> httpx.Response:
46+
headers = {} if content_type is None else {"content-type": content_type}
47+
return httpx.Response(200, content=body, headers=headers)
48+
49+
50+
async def fetch(web: FakeWeb, response: httpx.Response, **arguments: Any) -> str:
51+
web.add(ROBOTS, httpx.Response(404))
52+
web.add(PAGE, response)
53+
async with connect() as (session, _):
54+
assert isinstance(session, ClientSession)
55+
result = await session.call_tool("fetch", {"url": PAGE, **arguments})
56+
return text_of(result)
57+
58+
59+
def document(meta: str, text: str) -> str:
60+
return f"<html><head>{meta}<title>t</title></head><body><p>{text}</p></body></html>"
61+
62+
63+
@pytest.mark.parametrize(
64+
("meta", "encoding", "text"),
65+
[
66+
('<meta charset="Shift_JIS">', "shift_jis", JAPANESE),
67+
("<meta charset=windows-1251>", "cp1251", RUSSIAN),
68+
("<META CHARSET='euc-kr'>", "euc_kr", KOREAN),
69+
('<meta charset="GBK" />', "gbk", CHINESE),
70+
(
71+
'<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">',
72+
"shift_jis",
73+
JAPANESE,
74+
),
75+
(
76+
"<meta http-equiv='content-type' content='text/html;charset=windows-1251'>",
77+
"cp1251",
78+
RUSSIAN,
79+
),
80+
],
81+
)
82+
async def test_a_charset_declared_only_in_the_html_is_honored(
83+
web: FakeWeb, meta: str, encoding: str, text: str
84+
) -> None:
85+
body = document(meta, text).encode(encoding)
86+
assert text in await fetch(web, page(body), raw=True)
87+
88+
89+
async def test_a_declared_charset_is_honored_without_a_content_type_header(
90+
web: FakeWeb,
91+
) -> None:
92+
body = document('<meta charset="Shift_JIS">', JAPANESE).encode("shift_jis")
93+
assert JAPANESE in await fetch(web, page(body, content_type=None), raw=True)
94+
95+
96+
async def test_xhtml_content_type_is_scanned(web: FakeWeb) -> None:
97+
body = document('<meta charset="windows-1251">', RUSSIAN).encode("cp1251")
98+
response = page(body, content_type="application/xhtml+xml")
99+
assert RUSSIAN in await fetch(web, response, raw=True)
100+
101+
102+
async def test_the_extracted_markdown_is_decoded_too(
103+
web: FakeWeb, python_readability: None
104+
) -> None:
105+
body = document('<meta charset="Shift_JIS">', JAPANESE).encode("shift_jis")
106+
assert JAPANESE in await fetch(web, page(body))
107+
108+
109+
async def test_a_header_charset_wins_over_the_html_declaration(web: FakeWeb) -> None:
110+
# The page lies in its meta tag; the header is right, and wins.
111+
body = document('<meta charset="Shift_JIS">', RUSSIAN).encode("cp1251")
112+
response = page(body, content_type="text/html; charset=windows-1251")
113+
assert RUSSIAN in await fetch(web, response, raw=True)
114+
115+
116+
async def test_a_byte_order_mark_wins_over_the_html_declaration(
117+
web: FakeWeb,
118+
) -> None:
119+
body = b"\xef\xbb\xbf" + document('<meta charset="Shift_JIS">', JAPANESE).encode(
120+
"utf-8"
121+
)
122+
assert JAPANESE in await fetch(web, page(body), raw=True)
123+
124+
125+
async def test_a_declaration_on_a_non_html_body_is_ignored(web: FakeWeb) -> None:
126+
# A text/plain body is UTF-8 by default; a meta-like string in it is text.
127+
body = document('<meta charset="windows-1251">', JAPANESE).encode("utf-8")
128+
assert JAPANESE in await fetch(web, page(body, content_type="text/plain"))
129+
130+
131+
async def test_a_declaration_past_the_first_1024_bytes_is_ignored(
132+
web: FakeWeb,
133+
) -> None:
134+
padding = "<!-- " + "x" * 1100 + " -->"
135+
body = (
136+
f"<html><head>{padding}<meta charset=windows-1251></head>"
137+
f"<body><p>{JAPANESE}</p></body></html>"
138+
).encode("utf-8")
139+
assert JAPANESE in await fetch(web, page(body), raw=True)
140+
141+
142+
async def test_a_page_with_no_declaration_is_decoded_as_utf8(web: FakeWeb) -> None:
143+
body = document("", JAPANESE).encode("utf-8")
144+
assert JAPANESE in await fetch(web, page(body), raw=True)
145+
146+
147+
@pytest.mark.parametrize(
148+
"declared",
149+
[
150+
# Unknown to Python.
151+
"no-such-charset",
152+
"x-user-defined",
153+
# Known codecs that are not text encodings, or refuse to decode.
154+
"base64",
155+
"rot13",
156+
"undefined",
157+
# Text codecs that are not web encodings.
158+
"unicode_escape",
159+
"raw_unicode_escape",
160+
"idna",
161+
"punycode",
162+
],
163+
)
164+
async def test_an_unusable_declared_charset_falls_back_to_the_old_decoding(
165+
web: FakeWeb, declared: str
166+
) -> None:
167+
body = document(f'<meta charset="{declared}">', JAPANESE + " \\u0041").encode(
168+
"utf-8"
169+
)
170+
text = await fetch(web, page(body), raw=True)
171+
assert JAPANESE + " \\u0041" in text
172+
173+
174+
@pytest.mark.parametrize("declared", ["utf-16", "UTF-16LE", "utf-32"])
175+
async def test_a_utf16_or_utf32_declaration_is_read_as_utf8(
176+
web: FakeWeb, declared: str
177+
) -> None:
178+
body = document(f'<meta charset="{declared}">', JAPANESE).encode("utf-8")
179+
assert JAPANESE in await fetch(web, page(body), raw=True)

0 commit comments

Comments
 (0)