46 more unit tests, and `vm-mcp` rewritten around the new split (21 subtests, up from 14). `test_mcp_resources.py` is the new file and its subject is what the resource layer actually decides: which entry a URI resolves to, which query parameters it will accept, and the argv each read builds. The cases that matter are the ones a reshuffle would quietly break -- a literal route beating a template (`hhstream://sessions` is the listing, not a session with a blank id), a switch parameter becoming a bare flag or nothing at all (`--all=false` is not something the CLI takes), an undeclared parameter being refused rather than dropped, a frame's media type being sniffed rather than assumed, and a refusal being *raised* instead of returned as the body. One test exists only to stop a future kindness: there must be no resource for the reconciling container read, because that one writes. `test_mcp_server.py` grows the protocol-level half -- both listings, a read that returns JSON, a read that returns a blob, a refused read arriving as `McpError`, and a toolset selection that narrows the tools while leaving the resources alone. The tool and toolset tests move with the surface: the read-only verbs are asserted *absent* by name rather than merely missing, so re-adding one is a failure instead of a silent widening of what mcp-v2 narrowed. In the guest, the subtest the whole surface turns on is now measured rather than described: two reads of `hhstream://sessions/<id>` must NOT move the idle deadline, and `session_touch` must. It also asks for the same container two ways and checks the answers agree, reads one output's frame as a blob and confirms the `shot` tool reports the same geometry, and proves `--toolsets` makes an omitted tool unreachable and not merely unlisted. `checks/lib/mcp_client.py` gains `--resources`, `--read` and `--server-arg`, and exits 3 rather than 2 on a protocol error -- so "the server refused this read" stays distinguishable from "the server did not answer at all", which is the distinction that keeps the refusal subtests from passing for the wrong reason. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
304 lines
12 KiB
Python
304 lines
12 KiB
Python
"""The resource table: which URI runs which CLI call, and what comes back.
|
|
|
|
Same subject as ``test_mcp_tools.py`` and the same stand-in: what this layer
|
|
decides is the argv list, and here also the *routing* -- which entry a URI
|
|
resolves to, and which query parameters it will accept. Nothing here imports
|
|
the MCP SDK; the protocol wiring is ``test_mcp_server.py``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import mcp_fake
|
|
import pytest
|
|
from hhstreamd.protocol import ExitCode
|
|
from hhstream_mcp import invoke, resources, tools
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _isolated(monkeypatch, tmp_path):
|
|
mcp_fake.isolate(monkeypatch, tmp_path)
|
|
|
|
|
|
@pytest.fixture
|
|
def read():
|
|
"""`read("hhstream://sessions")` -> (Reading, [argv, ...])."""
|
|
|
|
def _read(uri, **script):
|
|
fake = mcp_fake.FakeCli(**script)
|
|
reading = resources.read(invoke.Runner(fake), uri)
|
|
return reading, fake.calls
|
|
|
|
return _read
|
|
|
|
|
|
# ── the table ──────────────────────────────────────────────────────────────
|
|
|
|
#: Every resource `docs/CONTRACT-mcp.md` §4 freezes, written out rather than
|
|
#: derived, for the reason the tool list is.
|
|
EXPECTED_FIXED = {
|
|
"hhstream://status",
|
|
"hhstream://sessions",
|
|
"hhstream://pointer",
|
|
"hhstream://containers",
|
|
"hhstream://screen",
|
|
}
|
|
EXPECTED_TEMPLATES = {
|
|
"hhstream://sessions/{id}{?events}",
|
|
"hhstream://sessions/{id}/logs{?lines}",
|
|
"hhstream://outputs/{name}",
|
|
}
|
|
|
|
|
|
def test_the_whole_surface_is_there_and_nothing_else_is():
|
|
assert {entry.uri for entry in resources.FIXED} == EXPECTED_FIXED
|
|
assert {entry.uri_template for entry in resources.TEMPLATES} == EXPECTED_TEMPLATES
|
|
assert len(resources.ENTRIES) == len(EXPECTED_FIXED) + len(EXPECTED_TEMPLATES)
|
|
|
|
|
|
def test_every_entry_has_a_unique_name_and_a_description():
|
|
names = [entry.name for entry in resources.ENTRIES]
|
|
assert len(names) == len(set(names))
|
|
for entry in resources.ENTRIES:
|
|
assert entry.title, entry.name
|
|
assert len(entry.description) > 40, entry.name
|
|
assert entry.media_type
|
|
|
|
|
|
def test_a_template_is_exactly_an_entry_with_a_capture():
|
|
for entry in resources.FIXED:
|
|
assert entry.captures == ()
|
|
for entry in resources.TEMPLATES:
|
|
assert entry.captures
|
|
|
|
|
|
def test_the_three_reads_the_activity_rule_names_say_so_themselves():
|
|
"""The rule has to be where it is read, and these are read, not called."""
|
|
|
|
for name in ("sessions", "session", "session-logs", "pointer", "containers"):
|
|
description = resources.BY_NAME[name].description
|
|
assert "does NOT reset" in description, name
|
|
assert "`session_touch`" in description, name
|
|
|
|
|
|
# ── routing ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_literal_route_beats_a_template_that_would_also_match():
|
|
"""`hhstream://sessions` is the listing, not a session with a blank id."""
|
|
|
|
entry, arguments = resources.resolve("hhstream://sessions")
|
|
assert entry.name == "sessions"
|
|
assert arguments == {}
|
|
|
|
|
|
def test_a_capture_becomes_the_argument_the_cli_takes(read):
|
|
_, calls = read("hhstream://sessions/foot-abc", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "status", "--json", "--", "foot-abc"]]
|
|
|
|
|
|
def test_a_deeper_route_is_its_own_entry(read):
|
|
_, calls = read("hhstream://sessions/foot-abc/logs", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "logs", "--json", "--", "foot-abc"]]
|
|
|
|
|
|
def test_each_fixed_resource_runs_the_verb_it_names(read):
|
|
cases = {
|
|
"hhstream://status": ["status"],
|
|
"hhstream://sessions": ["session", "list", "--json"],
|
|
"hhstream://pointer": ["session", "pointer", "state", "--json"],
|
|
"hhstream://containers": ["session", "container", "--json"],
|
|
}
|
|
for uri, argv in cases.items():
|
|
_, calls = read(uri, stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [argv], uri
|
|
|
|
|
|
def test_the_status_resource_is_text_because_the_verb_has_no_json(read):
|
|
reading, calls = read("hhstream://status", stdout="services:\n up\n")
|
|
assert calls == [["status"]]
|
|
assert reading.media_type == "text/plain"
|
|
assert reading.text == "services:\n up"
|
|
assert reading.blob is None
|
|
|
|
|
|
def test_a_json_resource_passes_the_protocol_object_through_unchanged(read):
|
|
reply = {"ok": True, "sessions": [{"id": "s-1", "state": "running"}]}
|
|
reading, _ = read("hhstream://sessions", stdout=json.dumps(reply, indent=2))
|
|
|
|
assert reading.media_type == "application/json"
|
|
assert json.loads(reading.text) == reply
|
|
|
|
|
|
def test_a_scheme_this_server_does_not_serve_is_refused(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("file:///etc/passwd")
|
|
assert "not a hhstream resource" in str(caught.value)
|
|
|
|
|
|
def test_a_uri_that_names_nothing_is_refused_and_points_at_the_listing(read):
|
|
for uri in ("hhstream://nonsense", "hhstream://sessions/a/b/c", "hhstream://"):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(uri)
|
|
assert "resources/list" in str(caught.value) or "names no resource" in str(
|
|
caught.value
|
|
)
|
|
|
|
|
|
def test_nothing_was_run_for_a_uri_that_did_not_resolve(monkeypatch, tmp_path):
|
|
"""The routing refuses before the CLI is reached, as a schema would."""
|
|
|
|
fake = mcp_fake.FakeCli()
|
|
with pytest.raises(resources.ReadRefused):
|
|
resources.read(invoke.Runner(fake), "hhstream://nonsense")
|
|
assert fake.calls == []
|
|
|
|
|
|
# ── query parameters ───────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_declared_parameter_becomes_the_flag_the_cli_takes(read):
|
|
_, calls = read(
|
|
"hhstream://sessions/foot-abc/logs?lines=250", stdout=mcp_fake.reply(ok=True)
|
|
)
|
|
assert calls == [["session", "logs", "--json", "--lines=250", "--", "foot-abc"]]
|
|
|
|
_, calls = read(
|
|
"hhstream://sessions/foot-abc?events=5", stdout=mcp_fake.reply(ok=True)
|
|
)
|
|
assert calls == [["session", "status", "--json", "--events=5", "--", "foot-abc"]]
|
|
|
|
|
|
def test_a_switch_parameter_is_a_bare_flag_or_nothing(read):
|
|
"""`--all=false` is not a thing the CLI takes, so false must omit it."""
|
|
|
|
_, calls = read("hhstream://sessions?all=true", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "list", "--json", "--all"]]
|
|
|
|
for falsey in ("false", "0", "no", "off", ""):
|
|
_, calls = read(f"hhstream://sessions?all={falsey}", stdout=mcp_fake.reply(ok=True))
|
|
assert calls == [["session", "list", "--json"]], falsey
|
|
|
|
|
|
def test_an_undeclared_parameter_is_refused_rather_than_dropped(read):
|
|
"""A parameter silently ignored is a read that answered another question."""
|
|
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://sessions?lines=5")
|
|
assert "'lines'" in str(caught.value)
|
|
assert "all" in str(caught.value)
|
|
|
|
|
|
def test_a_resource_with_no_parameters_says_so_when_given_one(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://pointer?id=s-1")
|
|
assert "accepts: none" in str(caught.value)
|
|
|
|
|
|
def test_a_parameter_given_twice_is_refused(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://sessions/s-1/logs?lines=1&lines=2")
|
|
assert "more than once" in str(caught.value)
|
|
|
|
|
|
def test_the_template_advertises_the_parameters_it_accepts():
|
|
"""So a client can construct a URI without guessing."""
|
|
|
|
logs = resources.BY_NAME["session-logs"]
|
|
assert logs.uri_template == "hhstream://sessions/{id}/logs{?lines}"
|
|
assert logs.parameters == ("lines",)
|
|
|
|
|
|
# ── refusals ───────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_a_cli_refusal_is_raised_and_never_returned_as_the_body(read):
|
|
"""A resource has no `isError`; returning the failure object would lie."""
|
|
|
|
reply = {"ok": False, "error": "no_such_session", "reason": "no session 'nope'"}
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(
|
|
"hhstream://sessions/nope",
|
|
stderr=mcp_fake.reply(**reply),
|
|
exit_code=int(ExitCode.NO_SUCH_SESSION),
|
|
)
|
|
refused = caught.value
|
|
assert "exit 3 (NO_SUCH_SESSION)" in refused.message
|
|
assert "no session 'nope'" in refused.message
|
|
# And the structured detail carries what a tool error would have carried.
|
|
assert refused.detail["exit_code"] == int(ExitCode.NO_SUCH_SESSION)
|
|
assert refused.detail["error"] == "no_such_session"
|
|
assert "hhstream://sessions" in refused.detail["remedy"]
|
|
|
|
|
|
def test_an_unreachable_broker_is_refused_with_the_operator_s_remedy(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(
|
|
"hhstream://sessions",
|
|
stderr=mcp_fake.reply(ok=False, error="daemon_unreachable", reason="no socket"),
|
|
exit_code=int(ExitCode.DAEMON_UNREACHABLE),
|
|
)
|
|
assert "HHSTREAM_SOCKET" in caught.value.message
|
|
|
|
|
|
# ── frames ─────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_the_screen_resource_is_the_frame_bytes_with_its_real_media_type(read):
|
|
frame = mcp_fake.png(width=320, height=180)
|
|
reading, calls = read("hhstream://screen", write_png=frame)
|
|
|
|
assert calls[0][0] == "shot"
|
|
assert calls[0][1].startswith("--out=")
|
|
assert len(calls[0]) == 2, "the screen takes no --output"
|
|
assert reading.blob == frame
|
|
assert reading.text is None
|
|
assert reading.media_type == "image/png"
|
|
|
|
|
|
def test_an_output_resource_captures_that_output_alone(read):
|
|
frame = mcp_fake.png()
|
|
reading, calls = read("hhstream://outputs/hh-foot-abc", write_png=frame)
|
|
|
|
assert "--output=hh-foot-abc" in calls[0]
|
|
assert reading.blob == frame
|
|
|
|
|
|
def test_a_frame_s_media_type_is_sniffed_and_not_assumed(read):
|
|
"""The entry declares image/png; a JPEG publisher must still be told truly."""
|
|
|
|
assert resources.BY_NAME["screen"].media_type == "image/png"
|
|
reading, _ = read("hhstream://screen", write_png=mcp_fake.jpeg())
|
|
assert reading.media_type == "image/jpeg"
|
|
|
|
|
|
def test_a_capture_that_wrote_no_file_is_refused_rather_than_empty(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read("hhstream://screen")
|
|
assert "no readable file" in str(caught.value)
|
|
|
|
|
|
def test_a_refused_capture_carries_the_cli_s_own_words(read):
|
|
with pytest.raises(resources.ReadRefused) as caught:
|
|
read(
|
|
"hhstream://outputs/hh-gone",
|
|
stderr="hhstream: could not capture output 'hh-gone': unknown output\n",
|
|
exit_code=1,
|
|
)
|
|
assert "unknown output" in str(caught.value)
|
|
assert "hh-gone" in str(caught.value)
|
|
|
|
|
|
# ── the one read that must not be a resource ───────────────────────────────
|
|
|
|
|
|
def test_there_is_no_resource_for_the_reconciling_container_read():
|
|
"""`session container <id>` writes. Only the no-id list is a resource."""
|
|
|
|
assert "hhstream://containers" in EXPECTED_FIXED
|
|
for entry in resources.ENTRIES:
|
|
assert entry.route[:1] != ("containers",) or entry.captures == ()
|
|
# ...and the writing form is still reachable, as a tool.
|
|
assert "session_container" in tools.BY_NAME
|