"""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 ` 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