|
| 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 |
0 commit comments