Skip to content

Commit b7df1ce

Browse files
authored
Merge pull request #5387 from modelcontextprotocol/v2/feat/5198-fetch-accept-markdown
fetch: ask for native markdown through Accept content negotiation
2 parents 0b7fb52 + 6ca876f commit b7df1ce

3 files changed

Lines changed: 160 additions & 0 deletions

File tree

‎src/fetch/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ The markdown of an HTML page opens with the page's title as a `#` heading (its `
4242

4343
The server is built on the MCP Python SDK's high-level `MCPServer`: the tool and the prompt are decorated functions, and their type hints and field descriptions are the input schema and the prompt's arguments.
4444

45+
### Content negotiation
46+
47+
The tool and the prompt ask for markdown first, with the request header `Accept: text/markdown, text/html;q=0.9, */*;q=0.8`. A site that serves markdown through content negotiation sends it directly, and a `text/markdown` response is returned as-is: it is not simplified and carries no raw-content notice. A site that ignores the header sends what it always did, and HTML is simplified to markdown as before. A `raw` fetch keeps the default `Accept: */*`, so it gets whatever the site serves by default (for a web page, its HTML), unsimplified; a markdown response it receives anyway is returned as-is too.
48+
4549
### Protocol versions
4650

4751
The server speaks both eras of the Model Context Protocol over stdio, with nothing to configure: a **2026-07-28** client (discovered with `server/discover`, no session) and a **2025-11-25** client (the `initialize` handshake). The client's first request decides which. Tools and prompts behave the same in both. Methods the 2026-07-28 specification removes, such as `ping`, are answered only on a 2025-11-25 connection.

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,17 @@ async def check_may_autonomously_fetch_url(
537537
)
538538

539539

540+
# The Accept header of a non-raw fetch (#5198). A site that negotiates content
541+
# can then serve native markdown, which is returned as-is, and a site that does
542+
# not still serves HTML (preferred over everything else) to be simplified.
543+
MARKDOWN_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8"
544+
545+
546+
def _is_markdown(content_type: str) -> bool:
547+
"""Whether a Content-Type header declares markdown (``text/markdown``, RFC 7763)."""
548+
return content_type.split(";", 1)[0].strip().lower() == "text/markdown"
549+
550+
540551
def _body_looks_like_html(page_raw: str) -> bool:
541552
"""Whether a body served with no Content-Type is an HTML document.
542553
@@ -591,6 +602,10 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
591602
hooks.append(_check_redirect_robots_txt)
592603
if hooks:
593604
client.event_hooks = {"request": hooks}
605+
# A raw fetch keeps httpx's default Accept: */*, so it gets the site's
606+
# default representation (a page's HTML), as before this negotiation.
607+
if not force_raw:
608+
client.headers["Accept"] = MARKDOWN_ACCEPT
594609
try:
595610
response = await client.get(
596611
url,
@@ -612,6 +627,10 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
612627
page_raw = decode_page(response)
613628

614629
content_type = response.headers.get("content-type", "")
630+
# Markdown is already what this tool returns, so it is not simplified, and
631+
# it carries no raw-content prefix even under force_raw: it is unchanged.
632+
if _is_markdown(content_type):
633+
return page_raw, ""
615634
is_page_html = (
616635
"<html" in page_raw[:100]
617636
or "text/html" in content_type.lower()
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
"""Protocol-level tests for asking for native markdown (#5198).
2+
3+
A fetch used to send httpx's default ``Accept: */*``, so a site that can serve
4+
markdown through content negotiation sent HTML to be simplified, and a
5+
``text/markdown`` response was labeled as content that "cannot be simplified
6+
to markdown" behind the raw-content prefix. Now a non-raw fetch prefers
7+
``text/markdown`` (HTML next, anything else last), and a markdown response is
8+
returned as-is with no prefix. A ``raw`` fetch keeps the default ``Accept``,
9+
so it gets the site's default representation (a page's HTML) as before. These
10+
tests drive ``serve()`` through an MCP client with HTTP served by
11+
``harness.FakeWeb``.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import httpx
17+
import pytest
18+
19+
from mcp_server_fetch.server import MARKDOWN_ACCEPT, _is_markdown
20+
21+
from .harness import FakeWeb, connect
22+
23+
PAGE = "https://example.com/doc"
24+
ROBOTS = "https://example.com/robots.txt"
25+
26+
# Opens with an "<html" mention inside the first 100 characters, which the
27+
# HTML sniff would otherwise take for a page to simplify.
28+
MARKDOWN = "# Title\n\nUse an `<html>` tag at the top.\n\n- one\n- two\n"
29+
30+
ARTICLE = """<html><head><title>Test Page</title></head><body>
31+
<article>
32+
<h1>Hello World</h1>
33+
<p>This is a <a href="https://example.com/x">link</a> in a test paragraph
34+
with enough words to count as the main content of the page.</p>
35+
</article>
36+
</body></html>"""
37+
38+
39+
def markdown(content_type: str = "text/markdown; charset=utf-8") -> httpx.Response:
40+
return httpx.Response(
41+
200, content=MARKDOWN.encode(), headers={"content-type": content_type}
42+
)
43+
44+
45+
async def call_fetch(web: FakeWeb, arguments: dict[str, object]) -> str:
46+
async with connect() as (session, _):
47+
result = await session.call_tool("fetch", {"url": PAGE, **arguments})
48+
data = result.model_dump(by_alias=True, mode="json", exclude_none=True)
49+
assert data["isError"] is False
50+
return data["content"][0]["text"]
51+
52+
53+
def page_requests(web: FakeWeb) -> list[httpx.Request]:
54+
return [r for r in web.requests if str(r.url) == PAGE]
55+
56+
57+
async def test_a_fetch_prefers_markdown_then_html(web: FakeWeb) -> None:
58+
web.add(ROBOTS, httpx.Response(404))
59+
web.add(PAGE, markdown())
60+
await call_fetch(web, {})
61+
[request] = page_requests(web)
62+
assert request.headers["accept"] == "text/markdown, text/html;q=0.9, */*;q=0.8"
63+
assert MARKDOWN_ACCEPT == request.headers["accept"]
64+
# The robots.txt lookup is not a page fetch and asks for nothing new.
65+
[robots] = [r for r in web.requests if str(r.url) == ROBOTS]
66+
assert robots.headers["accept"] == "*/*"
67+
68+
69+
@pytest.mark.parametrize(
70+
"content_type", ["text/markdown", "text/markdown; charset=utf-8", "Text/Markdown"]
71+
)
72+
async def test_markdown_is_returned_as_is_without_the_raw_prefix(
73+
web: FakeWeb, content_type: str
74+
) -> None:
75+
web.add(ROBOTS, httpx.Response(404))
76+
web.add(PAGE, markdown(content_type))
77+
text = await call_fetch(web, {})
78+
assert text == f"Contents of {PAGE}:\n{MARKDOWN}"
79+
80+
81+
async def test_a_raw_fetch_keeps_the_default_accept(web: FakeWeb) -> None:
82+
web.add(ROBOTS, httpx.Response(404))
83+
web.add(
84+
PAGE, httpx.Response(200, text=ARTICLE, headers={"content-type": "text/html"})
85+
)
86+
text = await call_fetch(web, {"raw": True})
87+
[request] = page_requests(web)
88+
assert request.headers["accept"] == "*/*"
89+
assert text.endswith(f"Contents of {PAGE}:\n{ARTICLE}")
90+
91+
92+
async def test_markdown_under_raw_is_unchanged_and_unprefixed(web: FakeWeb) -> None:
93+
# Markdown served unasked (a .md file, say) is the same either way.
94+
web.add(ROBOTS, httpx.Response(404))
95+
web.add(PAGE, markdown())
96+
text = await call_fetch(web, {"raw": True})
97+
assert text == f"Contents of {PAGE}:\n{MARKDOWN}"
98+
99+
100+
@pytest.mark.usefixtures("python_readability")
101+
async def test_html_from_a_site_that_ignores_accept_is_still_simplified(
102+
web: FakeWeb,
103+
) -> None:
104+
web.add(ROBOTS, httpx.Response(404))
105+
web.add(
106+
PAGE, httpx.Response(200, text=ARTICLE, headers={"content-type": "text/html"})
107+
)
108+
text = await call_fetch(web, {})
109+
assert "cannot be simplified" not in text
110+
assert "<article>" not in text
111+
assert "Hello World" in text
112+
113+
114+
async def test_the_prompt_returns_markdown_as_is(web: FakeWeb) -> None:
115+
web.add(PAGE, markdown())
116+
async with connect() as (session, _):
117+
result = await session.get_prompt("fetch", {"url": PAGE})
118+
message = result.model_dump(by_alias=True, mode="json")["messages"][0]
119+
assert message["content"]["text"].endswith(MARKDOWN)
120+
assert "cannot be simplified" not in message["content"]["text"]
121+
[request] = page_requests(web)
122+
assert request.headers["accept"] == MARKDOWN_ACCEPT
123+
124+
125+
@pytest.mark.parametrize(
126+
("content_type", "expected"),
127+
[
128+
("text/markdown", True),
129+
(" text/markdown ; variant=GFM", True),
130+
("text/markdownish", False),
131+
("text/x-markdown", False),
132+
("text/plain", False),
133+
("", False),
134+
],
135+
)
136+
def test_is_markdown(content_type: str, expected: bool) -> None:
137+
assert _is_markdown(content_type) is expected

0 commit comments

Comments
 (0)