feat(mcp)!: state as resources, acts as tools, and --toolsets for the rest

BREAKING: `status`, `session_list`, `session_status`, `session_logs` and
`pointer_state` are no longer tools. They are `hhstream://…` resources. 26
tools became 21, and eight resources appeared beside them.

The reason is the split the protocol itself draws, which the first cut ignored.
A resource is **application**-controlled context: the host decides what to put
in front of the model, and "what is on this machine right now" is the host's
question. A tool is **model**-controlled: an act the model chooses to perform.
Nothing in those five verbs acts. So the line between the halves is *who
decides*, not what a call costs.

    hhstream://status                     text, the units and the frame socket
    hhstream://sessions          {?all}   the broker's own list object
    hhstream://pointer                    the lease holder, buttons and keys
    hhstream://containers                 every container, plus the orphans
    hhstream://screen                     a frame, as an image blob
    hhstream://sessions/{id}     {?events}
    hhstream://sessions/{id}/logs {?lines}
    hhstream://outputs/{name}             one output's frame, as a blob

What did *not* move is the interesting part. `shot` and `record` stay tools
though neither changes the desktop: capturing is an act at a moment, and an
agent in a loop has to be able to decide to look *now* -- in many clients a
resource is something a person attaches rather than something a model can
fetch. The same frames are readable as `hhstream://screen` and
`hhstream://outputs/{name}` as well, for a host that wants one in context
itself. `session_container` stays a tool for a harder reason: with an id the
CLI runs `container.reconcile`, which writes the record back, so it is not a
read at all. Only the no-id listing is a resource. **A resource read must never
write**, and `resources.py` says so where it would be tempting.

Three consequences worth naming:

* A refusal cannot be content. `ReadResourceResult` has no `isError`, so a CLI
  refusal is raised as `-32602` with the same remedy text in `message` and the
  same `{ok, exit_code, error, reason, hint, remedy}` in `data`. Returning the
  broker's failure object as the *body* would make "no such session" read as a
  successful read of a session.
* Arguments become query parameters, and only declared ones are accepted -- for
  the reason every tool schema sets `additionalProperties: false`. A parameter
  silently ignored is a read that answered a different question.
* A v1 tool name is told where it went: `session_list` comes back with "It is a
  RESOURCE now ... read hhstream://sessions instead". "No such tool" alone
  reads as a broken server rather than a moved surface.

`--toolsets frames,sessions,pointer,keyboard` lands with it, because 21 flat
tools is the same problem one size smaller. There is **no grouping primitive in
MCP** -- `Tool` carries name, title, description, inputSchema, outputSchema,
icons, annotations, _meta and execution, and nowhere to put a family -- so the
only honest lever is which tools the *server* lists, chosen at launch. An
unknown name is argparse's exit 2, never a silently empty server, and a tool
outside the selection is unreachable rather than merely unlisted. Resources are
deliberately not filtered by it: they are the host's context, not the model's
budget.

`--list-resources` joins `--list-tools`; both are in the package's own
entry-point check, with `--toolsets` beside them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-11 11:49:46 +00:00
1 parent 6a40c7e2e4
commit 0a63c9b7fc
6 files changed
+818 -197

No files matched your search

+148 -140
View File
@@ -1,4 +1,19 @@
"""The tool table: one tool per CLI verb. Standard library only.
"""The tool table: one tool per CLI verb that *acts*. Standard library only.
**What is here and what is not.** A tool is model-controlled: an act the model
chooses to perform. The verbs that only read state are not tools -- they are
resources, addressed by URI in :mod:`hhstream_mcp.resources`, because that is
application-controlled context and "what is on this machine right now" is the
host's business. So ``session_kill`` is here and ``hhstream://sessions`` is
there, and the line between them is *who decides* rather than what it costs.
``shot`` and ``record`` stay tools even though neither changes the desktop:
capturing is an act at a moment, and an agent in a loop has to be able to decide
to look *now*. The same frames are also readable as ``hhstream://screen`` and
``hhstream://outputs/{name}`` for a host that wants to put one in context
itself. ``session_container`` stays a tool for a harder reason: with an id the
CLI runs ``container.reconcile``, which writes the record back, so it is not a
read at all.
**Granularity, and why.** One tool per verb rather than one tool per family
with an ``action`` enum. Three reasons, in order of weight:
@@ -11,14 +26,14 @@ with an ``action`` enum. Three reasons, in order of weight:
(after a round trip).
2. The two rules an agent gets wrong have to be *on the tool it gets wrong*.
A client shows a tool's own description at the point of use; a family-level
note about the idle clock is not what is read when ``session_list`` is about
to be called for the ninth time.
3. ``readOnlyHint`` is per tool and is a real distinction here: ``session_list``
reads, ``session_kill`` destroys, and ``session_container`` with an id
reconciles -- which is a write, and is marked as one.
note about the idle clock is not what is read when ``session_touch`` is the
thing being forgotten.
3. ``readOnlyHint`` is per tool and is still a real distinction among what is
left: ``shot`` reads, ``session_kill`` destroys, ``record`` writes a file.
The cost is twenty-six tools in one listing. That is paid back by the names
being the CLI's own: an agent that has read ``hhstream session --help``, or this
The cost is twenty-one tools in one listing, and :data:`TOOLSETS` is the lever
for a client that cannot afford them all. It is paid back by the names being
the CLI's own: an agent that has read ``hhstream session --help``, or this
repository's README, already knows what ``session_touch`` is, and a transcript
of tool calls can be re-run by hand as a shell session.
@@ -57,12 +72,13 @@ from .invoke import GENERIC_FAILURE, Outcome, Runner, remedy_for, temp_name
ACTIVITY_NOTE = (
"ACTIVITY: `session_touch` is the ONLY thing that resets a session's idle "
"clock. `session_list`, `session_status`, `session_logs` and `session_gc` "
"do NOT count, and neither does any pointer or keyboard tool -- if polling "
"kept a session alive, an abandoned session would never be reaped. A "
"session being watched or driven is still a session nobody has said they "
"want kept. If you leave an application running, call `session_touch` "
"before its idle timeout expires or the broker will reap it."
"clock. Reading `hhstream://sessions`, `hhstream://sessions/<id>` or its "
"logs does NOT count; neither does `session_gc`, and neither does any "
"pointer or keyboard tool -- if polling kept a session alive, an abandoned "
"session would never be reaped. A session being watched or driven is still "
"a session nobody has said they want kept. If you leave an application "
"running, call `session_touch` before its idle timeout expires or the "
"broker will reap it."
)
LEASE_NOTE = (
@@ -262,7 +278,10 @@ def json_verb(
SESSION_ID = {
"type": "string",
"description": "the session id, as `session_start` printed it or `session_list` reports it",
"description": (
"the session id, as `session_start` printed it or "
"`hhstream://sessions` reports it"
),
}
LEASE = {
"type": "string",
@@ -314,39 +333,49 @@ def obj(properties: dict[str, Any], required: list[str] | None = None, **extra:
# ── frames ─────────────────────────────────────────────────────────────────
def _status(runner: Runner, args: dict[str, Any]) -> Result:
# No `--json`: `hhstream status` has none. It is a human report of the
# units, the socket's reachability and one probe frame, and this passes it
# through as text rather than inventing a shape for it.
return report(runner.run(["status"]))
def _shot(runner: Runner, args: dict[str, Any]) -> Result:
"""One frame, as MCP image content.
def capture(runner: Runner, output: str | None) -> tuple[Outcome, bytes | None]:
"""One frame, as the CLI's outcome and the bytes it wrote.
Captured to a temporary file and read back, because that is the CLI's only
output shape -- `shot` writes a file and prints its path -- and because a
pipe would mean asking the CLI for something it does not offer. The
directory goes away with the call; the bytes are in the reply.
directory goes away with the call; the bytes are the return value.
Shared with :mod:`hhstream_mcp.resources`, which serves the same frames by
URI: one capture path, so a fix to it cannot reach one caller and miss the
other. ``None`` for the bytes means the CLI claimed success and left no
readable file, which is its own kind of failure and is reported as one.
"""
with tempfile.TemporaryDirectory(prefix="hhstream-mcp-shot-") as scratch:
destination = os.path.join(scratch, "frame.png")
options = [flag("out", destination), *_optional(args, "output")]
options = [flag("out", destination)]
if output:
options.append(flag("output", output))
outcome = runner.run(argv(["shot"], options, []))
if not outcome.ok:
return report(outcome)
return outcome, None
try:
frame = pathlib.Path(destination).read_bytes()
except OSError as exc:
return Result(
text=(
f"hhstream shot reported success but wrote no readable file: {exc}\n\n"
f"hhstream said:\n{outcome.stdout.strip()}"
),
data={"ok": False, "exit_code": 0, "error": "no_artifact"},
is_error=True,
)
return outcome, pathlib.Path(destination).read_bytes()
except OSError:
return outcome, None
def _shot(runner: Runner, args: dict[str, Any]) -> Result:
"""One frame, as MCP image content."""
outcome, frame = capture(runner, args.get("output"))
if not outcome.ok:
return report(outcome)
if frame is None:
return Result(
text=(
"hhstream shot reported success but wrote no readable file.\n\n"
f"hhstream said:\n{outcome.stdout.strip()}"
),
data={"ok": False, "exit_code": 0, "error": "no_artifact"},
is_error=True,
)
image = media.sniff(frame)
where = args.get("output")
@@ -500,22 +529,6 @@ def build() -> tuple[Tool, ...]:
"""The whole surface. A function, so the table is built once per process."""
tools: list[Tool] = [
Tool(
name="status",
title="Session status",
description=(
"Is the headless Hyprland session up, and can this server reach "
"its frame socket? Reports each unit's state, the socket path "
"and whether it is readable, the Wayland socket the compositor "
"bound, and one probe frame's size and geometry. Start here "
"when any other tool fails in a way that smells like the "
"desktop being down. Human-readable text; this verb has no "
"JSON form."
),
schema=obj({}),
invoke=_status,
read_only=True,
),
Tool(
name="shot",
title="Capture one frame",
@@ -721,48 +734,6 @@ def _session_tools() -> list[Tool]:
summary=_start_summary,
),
),
Tool(
name="session_list",
title="List sessions",
description=(
"Every session the broker is tracking, with its state, pid and "
"idle deadline. `all` includes the tombstones of ended ones.\n\n"
f"{ACTIVITY_NOTE}"
),
schema=obj(
{"all": {"type": "boolean", "description": "include tombstones of ended sessions"}}
),
invoke=json_verb(["session", "list"], options=lambda a: _switch(a, "all")),
read_only=True,
),
Tool(
name="session_status",
title="One session, in detail",
description=(
"One session: its state, pid, container, idle deadline, and the "
"most recent entries from the broker's audit trail. The audit "
"events are the place to look when a session died for a reason "
"its own logs do not show.\n\n"
f"{ACTIVITY_NOTE}"
),
schema=obj(
{
"id": SESSION_ID,
"events": {
"type": "integer",
"minimum": 0,
"description": "how many recent audit events to include (the CLI's default is 20)",
},
},
["id"],
),
invoke=json_verb(
["session", "status"],
options=lambda a: _optional(a, "events"),
positionals=lambda a: [a["id"]],
),
read_only=True,
),
Tool(
name="session_touch",
title="Reset the idle clock",
@@ -855,37 +826,6 @@ def _session_tools() -> list[Tool]:
],
),
),
Tool(
name="session_logs",
title="A session's captured output",
description=(
"The tail of the application's own stdout and stderr, as the "
"broker captured it. The first place to look when an "
"application started and then did nothing.\n\n"
"There is no follow mode here, deliberately: the CLI's "
"`--follow` polls until interrupted, and a tool call that never "
"returns hangs the client that made it. Call this again "
"instead.\n\n"
f"{ACTIVITY_NOTE}"
),
schema=obj(
{
"id": SESSION_ID,
"lines": {
"type": "integer",
"minimum": 1,
"description": "how many lines to tail (the CLI's default is 100)",
},
},
["id"],
),
invoke=json_verb(
["session", "logs"],
options=lambda a: _optional(a, "lines"),
positionals=lambda a: [a["id"]],
),
read_only=True,
),
Tool(
name="session_container",
title="A session's output and workspace",
@@ -1134,20 +1074,6 @@ def _pointer_tools() -> list[Tool]:
positionals=lambda a: [a["id"]],
),
),
Tool(
name="pointer_state",
title="Who holds the pointer",
description=(
"Who holds the one pointer lease, since when, and which buttons "
"and KEYS are currently held down. This is the tool to call "
"after an exit 8 (BUSY): it names the holder. It takes no "
"session id -- there is one cursor.\n\n"
f"{ACTIVITY_NOTE}"
),
schema=obj({}),
invoke=json_verb(["session", "pointer", "state"]),
read_only=True,
),
]
@@ -1261,3 +1187,85 @@ def _keyboard_tools() -> list[Tool]:
TOOLS: tuple[Tool, ...] = build()
BY_NAME: dict[str, Tool] = {tool.name: tool for tool in TOOLS}
# ── toolsets ───────────────────────────────────────────────────────────────
#: The families ``--toolsets`` selects from, in listing order.
#:
#: Not a protocol feature -- MCP has no notion of a tool group, and the ``Tool``
#: object has nowhere to put one -- so this is what the ecosystem actually does:
#: the *server* is told which families to list, at launch, by whoever spawns it.
#: It exists because a tool listing is a budget. A client with room for a dozen
#: tools gets a coherent dozen this way instead of an arbitrary truncation, and
#: an agent that will never start an application need not be shown how.
#:
#: Resources are deliberately NOT filtered by it. They are the host's context,
#: not the model's budget, and making ``hhstream://sessions`` conditional on the
#: session *tools* being enabled would couple two decisions that are not the
#: same decision.
TOOLSETS: dict[str, tuple[str, ...]] = {
"frames": ("shot", "record", "run"),
"sessions": (
"session_start",
"session_touch",
"session_kill",
"session_gc",
"session_adopt",
"session_container",
"session_reconcile",
),
"pointer": (
"pointer_acquire",
"pointer_move",
"pointer_click",
"pointer_scroll",
"pointer_down",
"pointer_up",
"pointer_release",
),
"keyboard": ("keyboard_type", "keyboard_key", "keyboard_down", "keyboard_up"),
}
#: Tools that mcp-v1 had and mcp-v2 does not, each pointing at the resource
#: that replaced it.
#:
#: Kept so a refusal can say where the thing went. An agent (or a transcript,
#: or a prompt) that learned the v1 names will ask for these, and "no such
#: tool" alone makes that look like a server that is broken rather than a
#: surface that moved. One sentence here saves a whole loop of guessing.
MOVED_TO_RESOURCES: dict[str, str] = {
"status": "hhstream://status",
"session_list": "hhstream://sessions",
"session_status": "hhstream://sessions/<id>",
"session_logs": "hhstream://sessions/<id>/logs",
"pointer_state": "hhstream://pointer",
}
class UnknownToolset(ValueError):
"""A name ``--toolsets`` does not know. Refused, never ignored."""
def selected(names: Any = None) -> tuple[Tool, ...]:
"""The tools in the named families, in the table's own order.
``None`` is every tool, which is the default and what an unconfigured
client gets. An unknown name is refused rather than skipped: a server that
quietly served nothing because of a typo would look like a server with no
tools, which is the hardest failure of all to diagnose from the far side of
a pipe.
"""
if names is None:
return TOOLS
wanted = tuple(dict.fromkeys(names))
unknown = [name for name in wanted if name not in TOOLSETS]
if unknown:
raise UnknownToolset(
f"no such toolset: {', '.join(repr(u) for u in unknown)}. "
f"Known: {', '.join(TOOLSETS)}"
)
chosen = {tool for family in wanted for tool in TOOLSETS[family]}
return tuple(tool for tool in TOOLS if tool.name in chosen)