Skip to content

Commit 5ce4583

Browse files
cliffhallclaude
andcommitted
feat(fetch,git,time): serve the 2026-07-28 era beside 2025-11-25
Each Python server's serve() now drives Server.run(), the SDK's dual-era loop, instead of the legacy-only serve_loop: a 2026-07-28 client is served sessionlessly (server/discover, per-request envelopes) and a 2025-11-25 client through the initialize handshake, the client's first request deciding which. No handler reads the session or calls back to the client, so tool and prompt behavior is identical in both eras; the SDK fills in the 2026-07-28 result fields (resultType, ttlMs, cacheScope). Tests: a tests/test_eras.py per server runs a real mcp 2.x Client, with mode pinned, against serve() over the stdio JSON-RPC path in each era. test_modern_era_is_not_served, modelcontextprotocol#4851's placeholder, becomes a raw-wire pin of the server/discover answer. READMEs and the client-smoke skill say the Python servers serve both eras. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent b84977a commit 5ce4583

4 files changed

Lines changed: 222 additions & 30 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ The fetch tool will truncate the response, but by using the `start_index` argume
3131
- Arguments:
3232
- `url` (string, required): URL to fetch
3333

34+
### Protocol versions
35+
36+
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.
37+
3438
## Installation
3539

3640
Optionally: Install node.js, this will cause the fetch server to use a different HTML simplifier that is more robust.
@@ -259,7 +263,7 @@ uv sync --frozen --all-extras --dev
259263
uv run --frozen pytest
260264
```
261265

262-
The tests drive `serve()` through an MCP `ClientSession` in-process, with HTTP mocked, so they need no network. The HTML extraction tests need Node.js on `PATH` (readabilipy uses Readability.js when Node is present and a pure-Python fallback when it is not).
266+
The tests drive `serve()` through an MCP `ClientSession` in-process (and, in `tests/test_eras.py`, through a `Client` as a 2026-07-28 and as a 2025-11-25 client), with HTTP mocked, so they need no network. The HTML extraction tests need Node.js on `PATH` (readabilipy uses Readability.js when Node is present and a pure-Python fallback when it is not).
263267

264268
Coverage, measured per file with branch coverage:
265269

‎src/mcp_server_fetch/server.py‎

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
# Built on the MCP Python SDK v2's low-level `Server` (#4851). That SDK no
88
# longer validates tool arguments or folds tool exceptions into `isError`
99
# results, so `call_tool` does both with SDK v1's messages, keeping tool
10-
# results as they were on v1. `serve()` runs the legacy (2025-11-25) handshake
11-
# loop only; serving 2026-07-28 is #4853.
10+
# results as they were on v1. `serve()` serves both protocol eras (#4853): a
11+
# 2025-11-25 client through the initialize handshake, and a 2026-07-28 client
12+
# sessionlessly. No handler reads the session or calls back to the client
13+
# (roots, sampling, elicitation, logging), so nothing differs between them.
1214

1315
import asyncio
1416
import ipaddress
@@ -24,7 +26,6 @@
2426
import readabilipy.simple_json
2527
from mcp.shared.exceptions import MCPError
2628
from mcp.server import Server, ServerRequestContext
27-
from mcp.server.runner import serve_loop
2829
from mcp.server.stdio import stdio_server
2930
from mcp.types import (
3031
CallToolRequestParams,
@@ -558,15 +559,9 @@ async def get_prompt(
558559

559560
options = server.create_initialization_options()
560561
async with stdio_server() as (read_stream, write_stream):
561-
# Legacy era only. Server.run() would also serve 2026-07-28 (its
562-
# dual-era loop answers server/discover and per-request envelopes);
563-
# adopting that era is #4853, so this port (#4851) serves the
564-
# handshake loop alone, the only era it served on SDK v1.
565-
async with server.lifespan(server) as lifespan_state:
566-
await serve_loop(
567-
server,
568-
read_stream,
569-
write_stream,
570-
lifespan_state=lifespan_state,
571-
init_options=options,
572-
)
562+
# Both eras (#4853): Server.run()'s dual-era loop lets the client's
563+
# first request decide. `initialize` gets the 2025-11-25 handshake;
564+
# `server/discover` or a request carrying a 2026-07-28 envelope gets
565+
# the modern, sessionless era, with its required result fields
566+
# (resultType, ttlMs, cacheScope) filled in by the SDK.
567+
await server.run(read_stream, write_stream, options)

‎tests/test_eras.py‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
"""Both protocol eras, driven through a real ``mcp`` 2.x ``Client`` (#4853).
2+
3+
serve() answers a 2025-11-25 client through the initialize handshake and a
4+
2026-07-28 client sessionlessly, the client's first request deciding which.
5+
Each test here pins the client's ``mode`` explicitly (never "auto" alone), so a
6+
test names the era it covers and cannot pass by falling back to the other one.
7+
The client talks to the real ``serve()`` over in-memory streams, the same
8+
JSON-RPC path stdio takes, rather than the SDK's in-process shortcut, which
9+
would bypass serve() and its era dispatch. ``web`` (harness.py) keeps every
10+
request off the network.
11+
12+
The legacy-era characterization tests in test_protocol.py stay as the
13+
backward-compatibility net; this file adds what differs by era and shows that
14+
the rest does not.
15+
"""
16+
17+
from collections.abc import AsyncIterator
18+
from contextlib import asynccontextmanager
19+
from typing import Any
20+
from unittest.mock import patch
21+
22+
import anyio
23+
import httpx
24+
import pytest
25+
from mcp import Client
26+
from mcp.client._transport import TransportStreams
27+
from mcp.shared.exceptions import MCPError
28+
from mcp.shared.memory import create_client_server_memory_streams
29+
from mcp.types import (
30+
INVALID_PARAMS,
31+
METHOD_NOT_FOUND,
32+
CallToolResult,
33+
TextContent,
34+
)
35+
36+
from mcp_server_fetch.server import serve
37+
38+
from .harness import FakeWeb
39+
40+
PAGE = "https://example.com/page"
41+
MODERN = "2026-07-28"
42+
LEGACY = "2025-11-25"
43+
# Each `mode` a test pins, with the protocol version it must negotiate.
44+
ERAS = [
45+
pytest.param(MODERN, MODERN, id=MODERN),
46+
pytest.param("legacy", LEGACY, id=LEGACY),
47+
]
48+
49+
50+
@asynccontextmanager
51+
async def connect(mode: str, **serve_kwargs: Any) -> AsyncIterator[Client]:
52+
"""Run ``serve(**serve_kwargs)`` in-process and yield a ``Client`` in ``mode``."""
53+
async with create_client_server_memory_streams() as (
54+
client_streams,
55+
server_streams,
56+
):
57+
58+
@asynccontextmanager
59+
async def fake_stdio_server() -> AsyncIterator[Any]:
60+
yield server_streams
61+
62+
@asynccontextmanager
63+
async def transport() -> AsyncIterator[TransportStreams]:
64+
yield client_streams
65+
66+
with patch("mcp_server_fetch.server.stdio_server", fake_stdio_server):
67+
async with anyio.create_task_group() as tg:
68+
tg.start_soon(lambda: serve(**serve_kwargs))
69+
async with Client(transport(), mode=mode) as client:
70+
yield client
71+
tg.cancel_scope.cancel()
72+
73+
74+
def plain(body: str) -> httpx.Response:
75+
return httpx.Response(
76+
200, content=body.encode(), headers={"content-type": "text/plain"}
77+
)
78+
79+
80+
def text_of(result: CallToolResult) -> str:
81+
"""The text of a result holding one text block."""
82+
assert len(result.content) == 1
83+
block = result.content[0]
84+
assert isinstance(block, TextContent)
85+
return block.text
86+
87+
88+
def wire_list(items: Any) -> list[dict[str, Any]]:
89+
return [i.model_dump(by_alias=True, mode="json", exclude_none=True) for i in items]
90+
91+
92+
@pytest.mark.parametrize(("mode", "negotiated"), ERAS)
93+
async def test_each_era_is_negotiated(web: FakeWeb, mode: str, negotiated: str) -> None:
94+
async with connect(mode) as client:
95+
assert client.session.protocol_version == negotiated
96+
97+
98+
async def test_auto_mode_discovers_the_2026_07_28_era(web: FakeWeb) -> None:
99+
# An auto client probes server/discover first and only falls back to the
100+
# handshake on a server that refuses it; this server no longer does.
101+
async with connect("auto") as client:
102+
assert client.session.protocol_version == MODERN
103+
104+
105+
async def test_tools_and_prompts_lists_are_the_same_in_both_eras(
106+
web: FakeWeb,
107+
) -> None:
108+
# Same tools and prompts, same schemas, same order, in either era.
109+
async with connect(MODERN) as client:
110+
modern_tools = wire_list((await client.list_tools()).tools)
111+
modern_prompts = wire_list((await client.list_prompts()).prompts)
112+
async with connect("legacy") as client:
113+
legacy_tools = wire_list((await client.list_tools()).tools)
114+
legacy_prompts = wire_list((await client.list_prompts()).prompts)
115+
assert [t["name"] for t in modern_tools] == ["fetch"]
116+
assert [p["name"] for p in modern_prompts] == ["fetch"]
117+
assert modern_tools == legacy_tools
118+
assert modern_prompts == legacy_prompts
119+
120+
121+
@pytest.mark.parametrize(("mode", "negotiated"), ERAS)
122+
async def test_tool_call_succeeds_in_each_era(
123+
web: FakeWeb, mode: str, negotiated: str
124+
) -> None:
125+
web.add(PAGE, plain("hello from both eras"))
126+
async with connect(mode) as client:
127+
result = await client.call_tool("fetch", {"url": PAGE})
128+
assert result.is_error is False
129+
assert result.result_type == "complete"
130+
assert text_of(result).endswith(f"Contents of {PAGE}:\nhello from both eras")
131+
132+
133+
@pytest.mark.parametrize(("mode", "negotiated"), ERAS)
134+
async def test_prompt_succeeds_in_each_era(
135+
web: FakeWeb, mode: str, negotiated: str
136+
) -> None:
137+
web.add(PAGE, plain("prompted"))
138+
async with connect(mode) as client:
139+
result = await client.get_prompt("fetch", {"url": PAGE})
140+
assert result.description == f"Contents of {PAGE}"
141+
content = result.messages[0].content
142+
assert isinstance(content, TextContent)
143+
assert content.text.endswith("prompted")
144+
145+
146+
@pytest.mark.parametrize(("mode", "negotiated"), ERAS)
147+
async def test_tool_failure_is_an_is_error_result_in_each_era(
148+
web: FakeWeb, mode: str, negotiated: str
149+
) -> None:
150+
async with connect(mode) as client:
151+
missing = await client.call_tool("fetch", {})
152+
unknown = await client.call_tool("no_such_tool", {})
153+
assert missing.is_error is True
154+
assert text_of(missing) == "Input validation error: 'url' is a required property"
155+
assert unknown.is_error is True
156+
assert text_of(unknown) == "Unknown tool: no_such_tool"
157+
158+
159+
@pytest.mark.parametrize(("mode", "negotiated"), ERAS)
160+
async def test_prompt_failure_is_a_json_rpc_error_in_each_era(
161+
web: FakeWeb, mode: str, negotiated: str
162+
) -> None:
163+
# get_prompt raises MCPError, which reaches the client as a JSON-RPC error
164+
# rather than a result, and an undeclared method is one too.
165+
async with connect(mode) as client:
166+
with pytest.raises(MCPError) as unknown_prompt:
167+
await client.get_prompt("no_such_prompt", {"url": PAGE})
168+
with pytest.raises(MCPError) as no_resources:
169+
await client.list_resources()
170+
assert unknown_prompt.value.error.code == INVALID_PARAMS
171+
assert unknown_prompt.value.error.message == "Unknown prompt: no_such_prompt"
172+
assert no_resources.value.error.code == METHOD_NOT_FOUND
173+
174+
175+
async def test_ping_is_served_only_in_the_legacy_era(web: FakeWeb) -> None:
176+
# ping is removed in 2026-07-28; the legacy era keeps answering it.
177+
async with connect("legacy") as client:
178+
await client.session.send_ping()
179+
async with connect(MODERN) as client:
180+
with pytest.raises(MCPError) as excinfo:
181+
await client.session.send_ping()
182+
assert excinfo.value.error.code == METHOD_NOT_FOUND

‎tests/test_protocol.py‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from mcp.shared.exceptions import MCPError
3030
from mcp.shared.memory import create_client_server_memory_streams
3131
from mcp.shared.message import SessionMessage
32-
from mcp.types import INVALID_PARAMS, METHOD_NOT_FOUND, CallToolResult, JSONRPCRequest
32+
from mcp.types import INVALID_PARAMS, CallToolResult, JSONRPCRequest
3333

3434
from mcp_server_fetch.server import (
3535
DEFAULT_USER_AGENT_AUTONOMOUS,
@@ -1019,16 +1019,16 @@ async def test_get_prompt_does_not_validate_the_url(
10191019
# ---------------------------------------------------------------------------
10201020

10211021

1022-
async def test_modern_era_is_not_served() -> None:
1023-
# #4851: the SDK v2 port serves the 2025-11-25 handshake era only.
1024-
# Server.run() would also open a 2026-07-28 connection for a request that
1025-
# carries the per-request `_meta` envelope; adopting that era is #4853.
1026-
# Until then such a request is refused as an unknown method.
1022+
async def test_server_discover_answers_the_2026_07_28_era() -> None:
1023+
# #4853: serve() serves the 2026-07-28 era beside the 2025-11-25 handshake.
1024+
# A `server/discover` carrying the per-request `_meta` envelope opens it.
1025+
# Asserted on the raw JSON-RPC response, so the fields the 2026-07-28
1026+
# spec requires on a result (resultType, ttlMs, cacheScope) are pinned as
1027+
# the server sends them, not as a client model would default them. Era by
1028+
# era behavior through a real client is in test_eras.py.
10271029
#
1028-
# Behavior change in the SDK v2 port: SDK v1 answered every unknown
1029-
# method with -32602 "Invalid request parameters" (its request union
1030-
# failed to parse); SDK v2 answers -32601 "Method not found", the code
1031-
# JSON-RPC defines for it.
1030+
# Replaces #4851's test_modern_era_is_not_served, which pinned this request
1031+
# being refused with -32601 "Method not found" until this issue landed.
10321032
discover = JSONRPCRequest(
10331033
jsonrpc="2.0",
10341034
id=1,
@@ -1063,9 +1063,20 @@ async def fake_stdio_server() -> AsyncIterator[Any]:
10631063
assert response.message.model_dump(by_alias=True, exclude_none=True) == {
10641064
"jsonrpc": "2.0",
10651065
"id": 1,
1066-
"error": {
1067-
"code": METHOD_NOT_FOUND,
1068-
"message": "Method not found",
1069-
"data": "server/discover",
1066+
"result": {
1067+
"capabilities": {
1068+
"prompts": {"listChanged": False},
1069+
"tools": {"listChanged": False},
1070+
},
1071+
"supportedVersions": ["2026-07-28"],
1072+
"resultType": "complete",
1073+
"ttlMs": 0,
1074+
"cacheScope": "private",
1075+
"_meta": {
1076+
"io.modelcontextprotocol/serverInfo": {
1077+
"name": "mcp-fetch",
1078+
"version": version("mcp-server-fetch"),
1079+
}
1080+
},
10701081
},
10711082
}

0 commit comments

Comments
 (0)