Files
hyprland-headless-stream-pl…/checks/lib/mcp_http_client.py
T
HermenixandClaude Opus 5 8d6a6c7ae8 test(mcp): the http transport, its unit and its token, in a guest
`checks.vm-mcp-http` -- the sibling of `vm-mcp`, on the same session
machine.  That one proves the *surface* over a pipe; this one proves the
two things stdio does not have: a unit systemd supervises, and a
credential on the way in.  So there is one tool call and one resource
read here, just enough to show a request reached the broker through an
authenticated session, and the weight is on the refusals, the state
directory's permissions, and the unit's lifecycle.

**The first subtest is the one that justifies the file.** The server
exits 2 while the authorization table is empty, which leaves a freshly
provisioned machine in a failed state on purpose -- and that trade is
only sound because the unit retries, so the first `token mint` brings it
up with no `systemctl start`. That self-heal lives in
`StartLimitIntervalSec = 0` and nothing in Python can test it. If it
regresses, every machine that enables the option comes up dead and stays
dead, and this is the only thing that would notice.

Also asserted, and each for a reason rather than for coverage: the state
directory is 0700 and owned by the account that mints tokens (which is
also the proof an operator *can* mint one on a machine configured this
way); the table is 0600 and does not contain the token; the port is on
loopback and **not** in the firewall, because neither default may become
implied; the refusals are 401 with an empty body and no echo; two tokens
served by one process see different tool budgets, which is the whole
argument for putting toolsets on a token; a revocation takes effect on
the next request with no restart, because an operator who must restart a
service to lock someone out does not have revocation; and revoking
*every* token does not stop the process, since the startup refusal exists
to catch a forgotten mint rather than to police a deliberate one.

`lib/mcp_http_client.py` is raw JSON-RPC over `urllib` and deliberately
not the SDK's client, for the reason `lib/mcp_client.py` is not either --
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 file
is about. It earned that choice immediately: it is what caught the 307 on
the exact path that the SDK-shaped test client had been following
silently.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KchcvnbfhhZhUHy83YL3Ya
2026-10-11 22:50:21 +00:00

225 lines
9.2 KiB
Python

#!/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())