"""Shared harness for the fetch server tests (conftest.py re-exports the fixtures). Two pieces: - ``connect(...)`` runs the real ``serve()`` in-process and yields an initialized ``ClientSession`` linked to it over in-memory streams, so tests go through the server's validation and error mapping exactly as a client would. - ``web`` replaces ``httpx.AsyncClient`` with one backed by an ``httpx.MockTransport``, so no test touches the network. It records every request and the keyword arguments each client was constructed with. It also replaces the server's DNS lookup (``_resolve_host``) with ``FakeWeb.dns``: a hostname listed there resolves to its addresses, an IP literal resolves to itself, and any other name resolves to ``PUBLIC_IP``. """ from __future__ import annotations import ipaddress import socket import tempfile from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager from dataclasses import dataclass, field from pathlib import Path from typing import Any from unittest.mock import patch import anyio import httpx import pytest from mcp import ClientSession from mcp.shared.memory import create_client_server_memory_streams from mcp.shared.message import SessionMessage from mcp.types import ( InitializeResult, JSONRPCError, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, ) import mcp_server_fetch.server as server_module from mcp_server_fetch import readability_js Responder = httpx.Response | Callable[[httpx.Request], httpx.Response] # A globally routable address (documentation ranges are not global, so they # would be refused by the private-address guard). PUBLIC_IP = "93.184.215.14" @dataclass class FakeWeb: """A router of URL -> response used as the transport of every AsyncClient.""" routes: dict[str, Responder] = field(default_factory=dict) requests: list[httpx.Request] = field(default_factory=list) client_kwargs: list[dict[str, Any]] = field(default_factory=list) # hostname -> addresses; an empty list makes the name unresolvable. dns: dict[str, list[str]] = field(default_factory=dict) lookups: list[str] = field(default_factory=list) def add(self, url: str, response: Responder) -> None: self.routes[url] = response def handle(self, request: httpx.Request) -> httpx.Response: self.requests.append(request) responder = self.routes.get(str(request.url)) if responder is None: response = httpx.Response(404, content=b"no route in FakeWeb") elif isinstance(responder, httpx.Response): response = responder else: response = responder(request) # Served unread, as from the network. `httpx.Response(content=...)` # reads (and decodes) its body when it is built, which leaves nothing # for the server's raw, capped read (#5370); its stream still holds the # bytes as given, so a fresh response over that stream is the wire form. return httpx.Response( response.status_code, headers=response.headers, stream=response.stream, extensions=response.extensions, ) def urls(self) -> list[str]: return [str(r.url) for r in self.requests] async def resolve(self, host: str) -> list[str]: self.lookups.append(host) try: return [str(ipaddress.ip_address(host))] except ValueError: pass addresses = self.dns.get(host, [PUBLIC_IP]) if not addresses: raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") return addresses @pytest.fixture def web(monkeypatch: pytest.MonkeyPatch) -> FakeWeb: fake = FakeWeb() real_async_client = httpx.AsyncClient def factory(**kwargs: Any) -> httpx.AsyncClient: fake.client_kwargs.append(dict(kwargs)) # A proxy would mount a real proxy transport in front of ours, so it is # recorded above and dropped here. Passing a transport also stops httpx # from picking up HTTP(S)_PROXY from the environment. kwargs.pop("proxy", None) return real_async_client(transport=httpx.MockTransport(fake.handle), **kwargs) # server.py imports AsyncClient from httpx inside each function, so # patching the attribute on the httpx module is what it picks up. monkeypatch.setattr(httpx, "AsyncClient", factory) monkeypatch.setattr(server_module, "_resolve_host", fake.resolve) return fake @asynccontextmanager async def connect( **serve_kwargs: Any, ) -> AsyncIterator[tuple[ClientSession, InitializeResult]]: """Run ``serve(**serve_kwargs)`` in-process and yield a connected client.""" async with create_client_server_memory_streams() as ( client_streams, server_streams, ): @asynccontextmanager async def fake_stdio_server() -> AsyncIterator[Any]: yield server_streams # MCPServer.run_stdio_async() opens the SDK's stdio_server. with patch("mcp.server.mcpserver.server.stdio_server", fake_stdio_server): async with anyio.create_task_group() as tg: tg.start_soon(lambda: server_module.serve(**serve_kwargs)) async with ClientSession(*client_streams) as session: init = await session.initialize() yield session, init tg.cancel_scope.cancel() @pytest.fixture def node_readability() -> None: """Require the Readability.js path the server takes when Node is on PATH. The server silently falls back to readabilipy's pure-Python extractor without Node, and the two produce different Markdown, so each HTML test names the mode it pins. Node is a prerequisite of this repository's gate, so a missing Node fails the test rather than skipping it. """ if readability_js.node_path() is None: pytest.fail( f"Node.js >= {readability_js.MIN_NODE_MAJOR} (and npm, or readabilipy's " "JavaScript dependencies) must be on PATH for the Readability.js path" ) @pytest.fixture def python_readability(monkeypatch: pytest.MonkeyPatch) -> None: """Force the pure-Python fallback, as on a machine without Node.""" monkeypatch.setattr(readability_js, "node_path", lambda: None) @pytest.fixture(autouse=True) def private_tempdir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: """Give each test its own ``tempfile.gettempdir()``. readabilipy 0.2's Readability.js path wrote its input and output to fixed names (``full.html``, ``article.json``) in the shared temp directory, so two test runs at once (parallel gate runs in separate worktrees, say) read each other's pages. The server's own runner uses a fresh directory per page, so this now only keeps each test's temporary files to itself. """ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) async def raw_request( method: str, params: dict[str, Any] ) -> JSONRPCResponse | JSONRPCError: """Send one request exactly as given, bypassing the client's own checks. `ClientSession` validates what it sends, so a malformed request (a list as a tool name, a number as the arguments) can only reach the server as raw JSON-RPC: a 2025-11-25 handshake, then the request, and its response. """ async with create_client_server_memory_streams() as ( (client_read, client_write), server_streams, ): @asynccontextmanager async def fake_stdio_server() -> AsyncIterator[Any]: yield server_streams async def receive(request_id: int) -> JSONRPCResponse | JSONRPCError: async for item in client_read: assert isinstance(item, SessionMessage) message = item.message if ( isinstance(message, (JSONRPCResponse, JSONRPCError)) and message.id == request_id ): return message raise AssertionError("the server closed the stream") # pragma: no cover with patch("mcp.server.mcpserver.server.stdio_server", fake_stdio_server): async with anyio.create_task_group() as tg: tg.start_soon(lambda: server_module.serve()) await client_write.send( SessionMessage( JSONRPCRequest( jsonrpc="2.0", id=1, method="initialize", params={ "protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "raw", "version": "0"}, }, ) ) ) await receive(1) await client_write.send( SessionMessage( JSONRPCNotification( jsonrpc="2.0", method="notifications/initialized" ) ) ) await client_write.send( SessionMessage( JSONRPCRequest( jsonrpc="2.0", id=2, method=method, params=params ) ) ) response = await receive(2) tg.cancel_scope.cancel() return response raise AssertionError("unreachable") # pragma: no cover