#!/usr/bin/env python3 """``hhs-mcp-http`` -- drive an MCP server over Streamable HTTP from a shell. What ``checks/vm-mcp-http.nix`` uses, and the sibling of ``checks/lib/mcp_client.py``: the same deliberate choice not to use the MCP SDK's own client, for the same reason. The SDK on both ends would agree with itself about a framing and a header neither side had to get right, and the header is half of what this check is about. Standard library only -- ``urllib.request`` and ``json``. One process per invocation, which re-does the ``initialize`` handshake every time; that is a feature here, because the handshake behind a bearer token is one of the things under test. hhs-mcp-http --token T --initialize hhs-mcp-http --token T --list hhs-mcp-http --token T --resources hhs-mcp-http --token T --read hhstream://sessions hhs-mcp-http --token T session_gc hhs-mcp-http --token T session_touch '{"id": "s-1"}' hhs-mcp-http --initialize (no token: expect exit 4) Exit codes, chosen so no assertion can mistake one failure for another: ==== =============================================================== 0 the server answered; whatever it said is on stdout as JSON 2 the server did not answer -- unreachable, timed out, or not JSON 3 the server answered with a JSON-RPC *error* object 4 an HTTP status other than 200 or 202; the status and the headers the check cares about are on stdout as JSON ==== =============================================================== Exit 4 is the interesting one and the reason this program exists rather than a ``curl`` pipeline: a 401 has an empty body, so the thing to assert is a status code and a ``WWW-Authenticate`` header, and both have to come back in a shape a test script can read without parsing curl's header dump. """ from __future__ import annotations import argparse import json import sys import urllib.error import urllib.request PROTOCOL_VERSION = "2025-06-18" #: Both, in this order, because the specification requires a client to accept #: either an immediate JSON body or an SSE stream. The server under test is run #: with `--json-response`, so the body comes back as JSON -- but a client that #: advertised only `application/json` would be testing a narrower contract than #: the one a real client has to satisfy. ACCEPT = "application/json, text/event-stream" class NoAnswer(Exception): """The server did not answer in a way this client can read.""" class HttpStatus(Exception): """The server answered with a status other than 200.""" def __init__(self, status: int, headers: dict[str, str], body: bytes) -> None: super().__init__(f"HTTP {status}") self.status = status self.headers = headers self.body = body def report(self) -> dict[str, object]: """What a test script needs, and deliberately not the body's bytes. A refusal's body is empty and must stay empty; reporting its *length* lets a check assert that without this program being the thing that decides what "empty" means. """ return { "http_status": self.status, "www_authenticate": self.headers.get("www-authenticate"), "cache_control": self.headers.get("cache-control"), "body_len": len(self.body), "body_prefix": self.body[:200].decode("utf-8", "replace"), } class Client: """One connection's worth of state: the token and the session id.""" def __init__(self, url: str, token: str | None, timeout: float) -> None: self.url = url self.token = token self.timeout = timeout self.session_id: str | None = None def send(self, body: dict[str, object]) -> dict[str, object] | None: payload = json.dumps(body).encode("utf-8") headers = {"Content-Type": "application/json", "Accept": ACCEPT} if self.token: headers["Authorization"] = f"Bearer {self.token}" if self.session_id: headers["Mcp-Session-Id"] = self.session_id request = urllib.request.Request( self.url, data=payload, headers=headers, method="POST" ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: raw = response.read() lowered = {k.lower(): v for k, v in response.headers.items()} status = response.status except urllib.error.HTTPError as exc: # The refusals arrive here: urllib raises on 4xx and 5xx, and the # headers are on the exception. raise HttpStatus( exc.code, {k.lower(): v for k, v in (exc.headers or {}).items()}, exc.read() or b"", ) from None except (urllib.error.URLError, OSError, TimeoutError) as exc: raise NoAnswer(f"no answer from {self.url}: {exc!r}") from None # 200 for a request, 202 for a notification -- the specification's own # answer to a message with no id, and it carries no body. Treating it # as a refusal is a mistake worth naming here, because it looks exactly # like one: the `notifications/initialized` that every handshake sends # is answered 202, so a client that only accepts 200 fails on its # second message with something that reads like an auth problem. if status not in (200, 202): raise HttpStatus(status, lowered, raw) # Remembered from the `initialize` response and sent on every request # after it; a stateful server refuses the second request without it. if "mcp-session-id" in lowered: self.session_id = lowered["mcp-session-id"] # A notification is answered with 202 and no body. if not raw: return None try: return json.loads(raw) except json.JSONDecodeError: raise NoAnswer(f"not JSON-RPC from {self.url}: {raw[:400]!r}") from None def request(self, method: str, params: dict[str, object] | None, request_id: int): body: dict[str, object] = {"jsonrpc": "2.0", "id": request_id, "method": method} if params is not None: body["params"] = params answer = self.send(body) if answer is None: raise NoAnswer(f"empty answer to {method}") if "error" in answer: raise SystemExit(_print_and(3, answer["error"])) return answer.get("result") def notify(self, method: str) -> None: self.send({"jsonrpc": "2.0", "method": method}) def handshake(self) -> dict[str, object]: result = self.request( "initialize", { "protocolVersion": PROTOCOL_VERSION, "capabilities": {}, "clientInfo": {"name": "hhs-mcp-http", "version": "0"}, }, 1, ) self.notify("notifications/initialized") return result def _print_and(code: int, obj: object) -> int: print(json.dumps(obj, indent=2, sort_keys=True)) return code def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="hhs-mcp-http", description="Drive an MCP server over Streamable HTTP. Raw JSON-RPC, " "standard library only; not the MCP SDK's client.", ) parser.add_argument("--url", default="http://127.0.0.1:9989/mcp") parser.add_argument("--token", default=None, help="the bearer token; omitted, none is sent") parser.add_argument("--timeout", type=float, default=60.0) parser.add_argument("--initialize", action="store_true", help="the handshake's own result") parser.add_argument("--list", action="store_true", help="tools/list") parser.add_argument("--resources", action="store_true", help="resources/list") parser.add_argument("--read", metavar="URI", help="one resources/read") parser.add_argument("tool", nargs="?", help="a tool name for one tools/call") parser.add_argument("arguments", nargs="?", default="{}", help="its arguments, as JSON") return parser def main(argv: list[str] | None = None) -> int: parser = build_parser() args = parser.parse_args(argv) client = Client(args.url, args.token, args.timeout) try: handshake = client.handshake() if args.initialize: return _print_and(0, handshake) if args.list: return _print_and(0, client.request("tools/list", None, 2)) if args.resources: return _print_and(0, client.request("resources/list", None, 2)) if args.read: return _print_and(0, client.request("resources/read", {"uri": args.read}, 2)) if args.tool: try: arguments = json.loads(args.arguments) except json.JSONDecodeError as exc: parser.error(f"arguments are not JSON: {exc}") return _print_and( 0, client.request("tools/call", {"name": args.tool, "arguments": arguments}, 2) ) except HttpStatus as refused: return _print_and(4, refused.report()) except NoAnswer as exc: print(str(exc), file=sys.stderr) return 2 parser.error("nothing to do: give --initialize, --list, --resources, --read or a tool name") return 2 # pragma: no cover -- parser.error exits if __name__ == "__main__": raise SystemExit(main())