diff --git a/README.dev.md b/README.dev.md index d0978bd..75dbdb4 100644 --- a/README.dev.md +++ b/README.dev.md @@ -51,7 +51,8 @@ import the SDK: ```bash nix develop -hhstream-mcp --list-tools # the whole surface, 26 lines, no stdio +hhstream-mcp --list-tools # the 21 acting verbs +hhstream-mcp --list-resources # the 8 read-only URIs ``` ## The checks @@ -68,7 +69,7 @@ hhstream-mcp --list-tools # the whole surface, 26 lines, no stdio | `vm-keyboard` | the **keymap, the focus and a decoded symbol**: the keymap the driver uploads reaching a real compositor, `pointer acquire` leaving the aimed window holding the *keyboard* and not merely the cursor, and `hhs-keyboard-target` decoding `hello` from the keymap it was **forwarded** — so a driver that stopped uploading one arrives as `sym=?` and goes red | yes | | `vm-keyboard-de` | the same file with `sessions.keyboard.layout = "de"`, because that option reaches the uploaded keymap through exactly one path — `--xkb-layout` on the driver unit — and a single-layout check cannot tell that path from a hardcoded `us`: keysym `y`'s evdev code swaps (21 against 44), the forwarded `symbols=` name with it, and `ü` goes from exit 2 to `udiaeresis` | yes | | `vm-stream-firewall` | the stream's **port**: the guest's own running firewall accepts the configured port and not the module's default, a peer outside the guest reaches it, and is refused on a port beside it that was never opened | yes | -| `vm-mcp` | the **MCP server over stdio**: `mcp.enable` puts the binary on PATH and starts no unit, the `initialize` handshake completes over a real pipe, all 26 tools are listed with their annotations and their two rules, a call reaches the live broker and returns its own protocol object, `shot` arrives as image content at the configured geometry, the pointer lease is granted/used/returned, and exits 9 and 3 arrive as tool *errors* carrying the frozen code | yes | +| `vm-mcp` | the **MCP server over stdio**: `mcp.enable` puts the binary on PATH and starts no unit, the `initialize` handshake completes over a real pipe, all 21 tools and 8 resources are listed with their annotations and their two rules, both a tool call and a resource read reach the live broker and return its own protocol object, two reads of a session do **not** move its idle deadline while `session_touch` does, a frame arrives as a blob at exactly its output's configured size, the pointer lease is granted/used/returned against the real driver, `--toolsets` narrows the tools and leaves the resources alone, and a refusal arrives as a tool error (or, for a read, a protocol error) carrying the frozen exit code | yes | All of them at once: @@ -122,6 +123,12 @@ output is on that path beside it, and `mcp` is in the test environment, because — not optionally: a file that skipped when the SDK was absent would be green in exactly the build where a malformed tool schema mattered. +The MCP suite is four files, split along what each can be tested without: +`test_mcp_invoke.py` (the in-process CLI call and the exit-code mapping), +`test_mcp_tools.py` (the argv each tool builds, and the toolsets), +`test_mcp_resources.py` (URI routing, query parameters, and that a read never +writes) and `test_mcp_server.py` (the SDK wiring, over its memory transport). + The check fails if the suite is **empty**, not just if it is red. `pytest` exits 5 on "collected nothing", but it exits 0 when every test was skipped or deselected, so `checks/lib/check_report.py` parses the JUnit report and refuses diff --git a/README.md b/README.md index a350a28..5bdb2a1 100644 --- a/README.md +++ b/README.md @@ -37,16 +37,31 @@ connects, and keeps running when one disconnects. ## Driving it from an agent: the MCP server -`hhstream-mcp` is the `hhstream` CLI as [Model Context -Protocol](https://modelcontextprotocol.io) tools, so an agent can look at this +`hhstream-mcp` is the `hhstream` CLI behind a [Model Context +Protocol](https://modelcontextprotocol.io) surface, so an agent can look at this desktop, put an application on it, and aim its one pointer and keyboard at that -application through typed tools instead of a shell. One tool per CLI verb, -twenty-six of them; the interface is frozen in `docs/CONTRACT-mcp.md`. +application without writing command lines. The interface is frozen in +`docs/CONTRACT-mcp.md`. -It is a thin wrapper and nothing more: every tool builds the argv list the CLI's -own parser takes, runs the CLI's own handler, and maps what came back. The idle -clock, the pointer lease, the allowlist and the exit-code table all stay where -they were. +It is split the way the protocol splits things: + +- **Resources are the state** — eight of them, read by URI, and reading one + changes nothing. `hhstream://status` is whether the desktop is up, + `hhstream://sessions` is what is running, `hhstream://sessions//logs` is + an application's own output, `hhstream://pointer` is who holds the input + lease, `hhstream://screen` is a frame of the screen. +- **Tools are the acts** — twenty-one, one per CLI verb that does something. + `session_start` puts an application on the screen, `pointer_acquire` takes the + input lease, `keyboard_type` types, `session_kill` ends a session. + +A host decides what state to put in front of its model; the model decides what +to do. That is the whole of the split, and it is why `shot` is still a tool +(capturing is an act at a moment) while `hhstream://screen` exists beside it. + +It is a thin wrapper and nothing more: every tool and every resource builds the +argv list the CLI's own parser takes, runs the CLI's own handler, and maps what +came back. The idle clock, the pointer lease, the allowlist and the exit-code +table all stay where they were. Install it with the module — off by default, because it is the surface through which a language model starts processes on this machine: @@ -86,16 +101,27 @@ server cannot recover that for itself the way the CLI does — see answer is `"command": "sg", "args": ["hhstream", "-c", "hhstream-mcp"]` or an account in the group. -`hhstream-mcp --list-tools` prints the table and exits, which is the quickest -way to check an install. Nothing else about the server is configurable: it holds -no state, caches no lease, and the pointer lease is an explicit argument on -every gesture tool for exactly that reason. +`hhstream-mcp --list-tools` and `--list-resources` print the two tables and +exit, which is the quickest way to check an install. + +If twenty-one tools is more than a client has room for, `--toolsets` narrows +what is offered to whichever families are wanted — `frames`, `sessions`, +`pointer`, `keyboard`: + +```json +{ "command": "hhstream-mcp", "args": ["--toolsets", "frames,pointer,keyboard"] } +``` + +Resources are deliberately *not* narrowed by it: they are the host's context, +not the model's tool budget. Nothing else about the server is configurable — it +holds no state and caches no lease, and the pointer lease is an explicit +argument on every gesture tool for exactly that reason. | Document | What it is | |---|---| | `docs/CONTRACT.md` | the wire protocol and the module surface — the interface other people build against | | `docs/CONTRACT-sessions.md` | the broker, the containers and the input lease | -| `docs/CONTRACT-mcp.md` | the MCP tools: their names, arguments and error mapping | +| `docs/CONTRACT-mcp.md` | the MCP surface: the resource URIs, the tool names, their arguments and the error mapping | | `docs/ARCHITECTURE.md` | how the pieces fit: compositor, capture, server, client | | `README.dev.md` | how to build, test and hack on it | | `examples/README.md` | the demo that films the screen: `agent-eyes-demo.py` | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 75bb9d1..c26f7c1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,7 +37,8 @@ │ ┌────────────┴──────────────┐ │ hhstream-mcp │ spawned per client, stdio only - │ 26 tools, one per verb │◀─── an MCP client's JSON-RPC + │ 21 tools (the acts) │◀─── an MCP client's JSON-RPC + │ 8 resources (the state)│ └───────────────────────────┘ ``` @@ -64,15 +65,21 @@ piece at all: And the sixth, which is a *shim* and not a layer: 6. **The MCP server** (`hhstream-mcp`, `docs/CONTRACT-mcp.md`) is the CLI with a - Model Context Protocol surface on it, so an agent calls typed tools instead - of writing command lines. It is drawn above the CLI rather than beside the - broker because that is where it sits: each tool builds the argv list the - CLI's parser takes and runs the CLI's own handler **in the same process**, - and it is the one component here that owns no state at all — not even the - pointer lease, which is an explicit argument on every gesture tool. Add it - to the diagram's list of things that can go wrong and nothing new appears: - every failure it reports is the CLI's or the broker's, carrying their exit - code. + Model Context Protocol surface on it, so an agent reads state by URI and + acts by calling tools instead of writing command lines. It is drawn above + the CLI rather than beside the broker because that is where it sits: every + tool and every resource builds the argv list the CLI's parser takes and runs + the CLI's own handler **in the same process**, and it is the one component + here that owns no state at all — not even the pointer lease, which is an + explicit argument on every gesture tool. Add it to the diagram's list of + things that can go wrong and nothing new appears: every failure it reports + is the CLI's or the broker's, carrying their exit code. + + The split between its two halves is *who decides*, not what it costs. A + resource is the host's to include (`hhstream://sessions` is state anyone may + want in context); a tool is the model's to call (`session_kill` is a + decision). That is why `shot` is both — a tool because deciding to look is + an act, and `hhstream://screen` because a frame is also just state. It is also the only part with a third-party dependency (the `mcp` SDK), which is why it is a separate derivation (`nix/mcp.nix`) and why diff --git a/docs/CONTRACT-mcp.md b/docs/CONTRACT-mcp.md index 7429e3d..f4b6ff8 100644 --- a/docs/CONTRACT-mcp.md +++ b/docs/CONTRACT-mcp.md @@ -1,22 +1,45 @@ -# CONTRACT — the MCP server (mcp-v1) +# CONTRACT — the MCP server (mcp-v2) -This file is the interface of `hhstream-mcp`: the tool names, the arguments each -takes, what comes back, and which of the CLI's exit codes arrives as which kind -of MCP error. It is the sibling of `docs/CONTRACT.md` (the frame socket's wire -format) and `docs/CONTRACT-sessions.md` (the broker, the containers and the -input lease). +This file is the interface of `hhstream-mcp`: the resource URIs, the tool names, +the arguments each takes, what comes back, and which of the CLI's exit codes +arrives as which kind of MCP error. It is the sibling of `docs/CONTRACT.md` (the +frame socket's wire format) and `docs/CONTRACT-sessions.md` (the broker, the +containers and the input lease). **Immutable without a version bump.** An agent that has learned these names and these argument shapes is a consumer like any other, and renaming a tool breaks it exactly as renaming a wire verb would. -Version: mcp-v1 (2026-10-11). +Version: mcp-v2 (2026-10-11). v1 was the first freeze and lasted one day. + +**v2 is a breaking change, and the only one: the verbs that merely read are +resources now, not tools.** + +| § | Change | Why | +| --- | --- | --- | +| §3, §4 | `status`, `session_list`, `session_status`, `session_logs` and `pointer_state` are **removed from the tool list** and are `hhstream://…` resources instead. 26 tools became 21. | The protocol's own split. 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. Nothing in those five acts. | +| §4 | Eight resources: five fixed, three templates, with query parameters for the arguments the verbs took. | A resource read takes nothing but a URI, so `--lines` becomes `?lines=`. Only declared parameters are accepted. | +| §5 | A refused resource read is a **protocol error** carrying the same remedy a tool error would have. | `CallToolResult` has `isError`; `ReadResourceResult` has nothing. Returning the broker's failure object as the body would make "no such session" read as a successful read of a session. | +| §3 | `--toolsets` selects which families are listed as tools. | A tool listing is a budget. MCP has no grouping primitive — the `Tool` object has nowhere to put one — so the only lever is which tools the *server* lists, chosen at launch. | + +What did **not** move, and the reasons are the interesting part: + +* **`shot` and `record` are still tools**, though neither changes the desktop. + Capturing is an act at a moment: an agent in a loop has to be able to decide + to look *now*, and in many clients a resource is something a person attaches + rather than something a model can fetch on its own initiative. 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` is still a tool**, for a harder reason: with an id the + CLI runs `container.reconcile`, which re-reads the compositor and writes the + record back. It is not a read at all. Only the no-id form is a resource + (`hhstream://containers`). A resource read must never write. ## 0. What this is, and what it is not -It is a **shim**. Each tool builds the argv list the `hhstream` CLI's own parser -takes, hands it to the CLI's own handler **in this process**, and maps what came -back. Nothing in it decides anything: +It is a **shim**. Each tool and each resource builds the argv list the `hhstream` +CLI's own parser takes, hands it to the CLI's own handler **in this process**, +and maps what came back. Nothing in it decides anything: | Rule | Whose it is | | --- | --- | @@ -27,10 +50,10 @@ back. Nothing in it decides anything: | the refusal messages (`reason`, `hint`) | the CLI and the broker | | coordinate normalisation, the scroll bound, the type cap | the broker and the driver | -What this layer owns is the argv list, the mapping of a result to MCP content, -and one sentence of *remedy* per exit code — the "what to do next" that the CLI -says to a human in the words of a command line and an agent needs in the words -of tools. +What this layer owns is the argv list, the routing of a URI to one of them, the +mapping of a result to MCP content, and one sentence of *remedy* per exit code — +the "what to do next" that the CLI says to a human in the words of a command +line and an agent needs in the words of tools and resources. In process, not as a subprocess: `hhstream.cli` is importable Python whose parser already takes an argv list and whose handlers already return a code from @@ -64,25 +87,50 @@ the CLI: Set them in the MCP client's `env` block. One place to configure them is one place for them to be wrong. -The server's own command line is two flags: `--list-tools`, which prints the -table and exits (the package's install check uses it), and nothing else that -affects behaviour. `$HHSTREAM_MCP_LOG` sets the log level on stderr. +The server's own command line: + +| flag | what it does | +| --- | --- | +| `--toolsets NAMES` | comma-separated families to offer as **tools**: `frames`, `sessions`, `pointer`, `keyboard`. Omitted, every tool is offered. An unknown name is argparse's exit 2, never a silently empty server. **Resources are not filtered by it** — they are the host's context, not the model's tool budget, and making `hhstream://sessions` conditional on the session *tools* would couple two decisions that are not the same decision. | +| `--list-tools` | print the table and exit. Honours `--toolsets`, so it is also how to see what a selection would offer. | +| `--list-resources` | print the resource URIs and templates and exit. | + +`$HHSTREAM_MCP_LOG` sets the log level on stderr. Nothing else affects +behaviour; in particular the server holds no state and caches no lease. + +**There is no grouping primitive in MCP**, and `--toolsets` is not pretending to +be one. The `Tool` object carries `name`, `title`, `description`, +`inputSchema`, `outputSchema`, `icons`, `annotations`, `_meta` and `execution` — +nowhere to put a family. Tools are a flat list in the specification too. So the +only honest lever is which tools the *server* lists, decided by whoever spawns +it, and the families below are the grouping that is left: a prefix in the name +and a line in this table. ## 3. The tool surface -**One tool per CLI verb**, named after it, with `_` where the CLI has a space. -Twenty-six tools. The rationale — and the alternative that was rejected, one -tool per family with an `action` enum — is in `hhstream_mcp.tools`' docstring. +**One tool per CLI verb that acts**, named after it, with `_` where the CLI has +a space. Twenty-one tools, in four families. The granularity rationale — and +the alternative that was rejected, one tool per family with an `action` enum — +is in `hhstream_mcp.tools`' docstring. Every schema sets `additionalProperties: false`, so an argument this server would not pass through is refused by the schema rather than dropped on the way to an argv list. +| family | tools | +| --- | --- | +| `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` | + +Every tool is in exactly one family — asserted by a unit test, because a tool in +none of them would be one `--toolsets` could never offer. + ### Frames | Tool | Arguments | Returns | | --- | --- | --- | -| `status` | — | the CLI's own text report: both units, the socket's reachability, one probe frame. This verb has no JSON form, so neither does the tool. | | `shot` | `output?` | **image content** (PNG or JPEG, by the bytes' own magic) plus text naming the geometry, the media type and the byte count | | `record` | `seconds?`, `out?`, `output?`, `fps?`, `work_dir?`, `keep?` | the artefact's **path** and the *measured* rate — never the video | | `run` | `argv`, `settle_s?` | the application's pid, and that it is unmanaged | @@ -107,14 +155,11 @@ running. | Tool | Arguments | | --- | --- | | `session_start` | `app`, `argv?`, `idle_timeout?`, `wait_ready?`, `home?`, `ephemeral_home?`, `request_id?` | -| `session_list` | `all?` | -| `session_status` | `id`, `events?` | | `session_touch` | `id` | | `session_kill` | `id`, `grace?`, `signal?`, `request_id?` | | `session_gc` | `request_id?` | | `session_adopt` | `pid`, `app?`, `idle_timeout?`, `request_id?` | -| `session_logs` | `id`, `lines?` | -| `session_container` | `id?` | +| `session_container` | `id` | | `session_reconcile` | `id?`, `request_id?` | Every one of these runs with `--json`, so what comes back is the broker's own @@ -127,7 +172,8 @@ the CLI's argparse group, moved forward to where the refusal is free. `session_container` is **not** marked read-only, and that is not an oversight: with an `id` the CLI runs `container.reconcile`, which writes the record back. -With no `id` it lists. +That is also why it is a tool rather than a resource. The no-id listing, which +only reads, is `hhstream://containers`. ### Input — the pointer lease is an argument, never a cache @@ -140,7 +186,6 @@ With no `id` it lists. | `pointer_down` | `id`, `lease`, `button?` | | `pointer_up` | `id`, `lease`, `button?` | | `pointer_release` | `id`, `lease` | -| `pointer_state` | — | | `keyboard_type` | `id`, `lease`, `text` | | `keyboard_key` | `id`, `lease`, `name` | | `keyboard_down` | `id`, `lease`, `name` | @@ -157,7 +202,8 @@ not one a transcript can explain. `pointer_acquire`'s reply puts `lease_id` on the first line of the text part, because that is what the next call needs. -`pointer_state` takes no session id. There is one cursor. +Who *holds* the lease is a read, so it is `hhstream://pointer` rather than a +tool. That is the resource to read after an exit 8. Durations (`ttl`, `idle_timeout`, `wait_ready`, `grace`) are **strings** in the CLI's own vocabulary: `30s`, `5m`, `3h`, `2d`, or a bare number of seconds. @@ -170,19 +216,54 @@ precedes every positional. Not a style choice: `--by -0.1,0.5` and a `text` beginning with a dash are both values argparse reads as option strings, and one uniform rule is one fewer thing to get wrong per flag. -## 4. What is deliberately absent +## 4. The resource surface + +Five fixed resources and three templates, all under one scheme, because they +are all views of one machine's one desktop. Every one of them runs the same CLI +verb a tool would have, with `--json` where the verb has it. + +| URI | Body | Query | +| --- | --- | --- | +| `hhstream://status` | `text/plain` — the CLI's own report: both compositor units, the frame socket's path and whether this server can read it, the Wayland socket, one probe frame. `hhstream status` has no JSON form, so neither does this. | — | +| `hhstream://sessions` | `application/json` — the broker's `list` object | `?all=true` includes tombstones | +| `hhstream://pointer` | `application/json` — the holder, since when, and the buttons and **keys** held | — | +| `hhstream://containers` | `application/json` — every container plus the orphan `hh-*` outputs. The **listing** only; see §3. | — | +| `hhstream://screen` | the published main output as an image blob. With containers on this is the whole compositor layout, so it is **wider than any single output's configured size**. | — | +| `hhstream://sessions/{id}` | `application/json` — one session with its recent audit events | `?events=N` | +| `hhstream://sessions/{id}/logs` | `application/json` — the application's own captured output | `?lines=N` | +| `hhstream://outputs/{name}` | one output captured alone, as an image blob. Exactly that output's configured size, which is the coordinate space the pointer tools aim in. | — | + +Rules this surface keeps: + +* **A read never writes.** That is what excludes `session container `. +* **Only declared query parameters are accepted.** An unknown one is refused, + for the reason every tool schema sets `additionalProperties: false`: a + parameter silently ignored is a read that answered a different question from + the one asked. A parameter given twice is refused too. +* **A literal route beats a template.** `hhstream://sessions` is the listing, + not a session whose id happened to be empty. +* **The media type of a frame is read off the bytes**, never off the extension + the server asked the CLI for. The entry's declared `mimeType` is a hint; the + `ReadResourceContents` carries the answer. +* **No subscriptions.** `Server.get_capabilities` in the pinned SDK hardcodes + `ResourcesCapability(subscribe=False, …)` — it never advertises `subscribe` + even if a handler is registered. So resource subscription is *not* available + as the answer to the missing `logs --follow`, which is a shame, because it + would have been the right one. Read it again instead. + +## 5. What is deliberately absent | Not exposed | Why | | --- | --- | -| `session logs --follow` | it polls until interrupted, and a tool call that never returns hangs the client that made it. Call `session_logs` again. | +| `session logs --follow` | it polls until interrupted, and a tool call that never returns hangs the client that made it. Read `hhstream://sessions/{id}/logs` again. Resource *subscriptions* would have been the principled fix; see §4. | | `session start --no-container` | the CLI's flag exists in order to *refuse*: the broker's `start` verb carries no such field (`docs/CONTRACT-sessions.md` §4), so the CLI exits 2 and names the disagreement. A tool argument whose only possible outcome is a refusal is a trap. | | `hhstream --frame-socket` / `session --socket` | §2: the environment configures them, in one place. | -| a per-call timeout | §5. | +| a per-call timeout | §6. | | `session keyboard` with no verb | it prints help and exits 2. There is nothing for a tool to do with that. | -## 5. Error mapping +## 6. Error mapping -Every refusal the CLI produces comes back as a **tool error** — +Every refusal the CLI produces on a **tool call** comes back as a tool error — `CallToolResult` with `isError: true` — carrying: - the remedy sentence, first, naming the code: `exit 9 (NO_LEASE): …`; @@ -191,22 +272,36 @@ Every refusal the CLI produces comes back as a **tool error** — - `structuredContent` with `ok: false`, `exit_code`, `remedy`, and the protocol object's own fields. -`isError` and not a JSON-RPC error, throughout. A JSON-RPC error reaches the -client's log; "another session holds the lease" is something the calling agent -has to read and act on. (The SDK's `call_tool` handler also converts anything -raised into `isError`, so this is the only channel there is in practice.) +`isError` and not a JSON-RPC error, for tools, throughout. A JSON-RPC error +reaches the client's log; "another session holds the lease" is something the +calling agent has to read and act on. (The SDK's `call_tool` handler also +converts anything raised into `isError`, so this is the only channel there is in +practice.) + +On a **resource read** it is the other way round, and not by preference: +`ReadResourceResult` has no `isError`, so a refusal is raised as a JSON-RPC +error with code `-32602` (`INVALID_PARAMS`), its `message` carrying the same +remedy-then-the-CLI's-own-words text and its `data` carrying the same +`{ok, exit_code, error, reason, hint, remedy}` object. Returning the broker's +failure object as the resource's *body* would make "no such session" read as a +successful read of a session, which is the one outcome a contract has to +forbid. The same error is raised for a URI that names nothing and for an +undeclared query parameter — in both cases before the CLI is reached at all. + +"Arrives as" below is for a tool call; on a resource read every one of them is +the protocol error above, with the same remedy. | Exit | Name | Arrives as | The remedy an agent is given | | --- | --- | --- | --- | | 0 | OK | a result | — | | 1 | *not in the frozen table* | tool error | the frame verbs' own failure: no frame published, or `grim`/`ffmpeg` missing from the server's PATH. Also what an uncaught exception in a handler becomes, with its traceback — which is what a CLI process would have done. | | 2 | USAGE | tool error | fix the arguments; a retry fails identically | -| 3 | NO_SUCH_SESSION | tool error | `session_list` to see which ids exist | -| 4 | BAD_STATE | tool error | `session_status` to see which state | -| 5 | DAEMON_UNREACHABLE | tool error | an operator problem; the four frame tools may still work | +| 3 | NO_SUCH_SESSION | tool error | read `hhstream://sessions` to see which ids exist | +| 4 | BAD_STATE | tool error | read `hhstream://sessions/` to see which state | +| 5 | DAEMON_UNREACHABLE | tool error | an operator problem; the three frame tools and `hhstream://status` may still work | | 7 | TIMEOUT | tool error | read the state back, then retry with the same `request_id` | | 6 | POLICY | tool error | a configuration decision; no retry changes it | -| 8 | BUSY | tool error | `pointer_state` names the holder; wait. **Never** "acquire one" | +| 8 | BUSY | tool error | read `hhstream://pointer` for the holder; wait. **Never** "acquire one" | | 9 | NO_LEASE | tool error | `pointer_acquire`, then pass the new `lease_id` | | 10 | COMPOSITOR | tool error | the session is **not** lost; it is degraded | @@ -238,7 +333,7 @@ the frame socket's own `--timeout` — and a call that outlives all of them outlives this server too. A subprocess design could have killed it; that is the one thing given up by calling the CLI in process. -## 6. Concurrency +## 7. Concurrency Tool calls are **serialised**. The CLI prints to a process-global `sys.stdout`, so two concurrent calls would interleave their output into each other's reply. @@ -247,17 +342,19 @@ would notice: the broker already serialises every mutation, and the CLI was one process per verb anyway. The event loop stays free, so a `ping` is answered while a `record` runs. -## 7. The two rules, which every relevant tool repeats +## 8. The two rules, which every relevant tool and resource repeats These are `hhstream_session.ACTIVITY_NOTE` and `KEYBOARD_LEASE_NOTE` restated -in terms of tools. They are on the individual tools and not only in the server -instructions, because a client shows a tool's own description at the point of -use: +in terms of this surface. They are on the individual tools and resources and +not only in the server instructions, because a client shows a thing's own +description at the point of use: 1. **`session_touch` is the only thing that resets a session's idle clock.** - `session_list`, `session_status`, `session_logs` and `session_gc` do not, and - neither does any pointer or keyboard tool. A session being driven is still a - session nobody has said they want kept. + Reading `hhstream://sessions`, `hhstream://sessions/{id}` or its logs does + not, `session_gc` does not, and neither does any pointer or keyboard tool. A + session being driven is still a session nobody has said they want kept. The + three resources it applies to say so in their own descriptions, because a + description is what a host shows beside the thing it describes. 2. **Every keyboard tool needs the pointer lease, and holds only while it holds.** There is no keyboard lease: one compositor seat means one keyboard @@ -266,10 +363,12 @@ use: a second after 600 ms — and this server cannot rate-limit what it does not generate. -`tests/unit/test_mcp_tools.py` asserts both notes are present on every tool -they apply to, and holds the CLI's own constants as a tripwire against drift. +`tests/unit/test_mcp_tools.py` asserts both notes are present on every tool they +apply to and holds the CLI's own constants as a tripwire against drift; +`tests/unit/test_mcp_resources.py` does the same for the five reads the first +rule applies to. -## 8. Packaging +## 9. Packaging `packages.hhstream-mcp` (`nix/mcp.nix`), a separate derivation from `packages.hhstream` because `mcp` is a third-party dependency and the frame diff --git a/docs/TODO/README.md b/docs/TODO/README.md index d9f3aba..dae4329 100644 --- a/docs/TODO/README.md +++ b/docs/TODO/README.md @@ -16,6 +16,7 @@ Each file answers three questions and stops: | [kill-can-leave-the-app-alive](kill-can-leave-the-app-alive.md) | medium | found by counting windows, not sessions | | [capture-binary-and-the-unit-path](capture-binary-and-the-unit-path.md) | medium | found the first time the app was run as a unit: a unit's `PATH` has no `grim` | | [mcp-in-process-has-no-call-deadline](mcp-in-process-has-no-call-deadline.md) | medium | two costs of running the CLI in process: no killable deadline, and no `sg` recovery | +| [mcp-resources-cannot-be-subscribed-to](mcp-resources-cannot-be-subscribed-to.md) | medium | the SDK hardcodes `subscribe=False`, so a log resource can only be re-read | Closed since this folder was written: diff --git a/docs/TODO/mcp-in-process-has-no-call-deadline.md b/docs/TODO/mcp-in-process-has-no-call-deadline.md index c068edb..244ab1a 100644 --- a/docs/TODO/mcp-in-process-has-no-call-deadline.md +++ b/docs/TODO/mcp-in-process-has-no-call-deadline.md @@ -2,9 +2,9 @@ ## The issue -`hhstream-mcp` runs the CLI's handlers **in its own process**: a tool builds the -argv list `hhstream.cli`'s parser takes, and `hhstream_mcp.invoke.dispatch` runs -the handler argparse selected. That is the seam the design asks for — one place +`hhstream-mcp` runs the CLI's handlers **in its own process**: a tool or a +resource read builds the argv list `hhstream.cli`'s parser takes, and +`hhstream_mcp.invoke.dispatch` runs the handler argparse selected. That is the seam the design asks for — one place decides the argv, nothing re-implements a rule — and it costs two things a subprocess would have given for free. Both are consequences of the same fact, so they are one item. @@ -36,11 +36,11 @@ run the server as a member of the group instead. ## Ideas 1. **Leave (1) as it is and make the frame-socket timeout reachable.** *(recommended - for (1))* The honest small fix: let `shot`, `record` and `status` take a - `timeout` argument and emit it as a global flag *before* the verb, which - `hhstream_mcp.tools.argv` cannot express today. That hands the one knob the - CLI already has to the agent, and does not pretend this layer can enforce a - deadline it cannot. + for (1))* The honest small fix: let `shot` and `record` take a `timeout` + argument, and `hhstream://status` and the frame resources a `?timeout=`, + emitted as a global flag *before* the verb — which `hhstream_mcp.tools.argv` + cannot express today. That hands the one knob the CLI already has to the + caller, and does not pretend this layer can enforce a deadline it cannot. 2. **Run each call in a forked child after all.** Restores a killable deadline, at the cost of a process per tool call and of re-introducing the two `exec` paths this design avoids. Worth it only if a hang is observed in practice. diff --git a/docs/TODO/mcp-resources-cannot-be-subscribed-to.md b/docs/TODO/mcp-resources-cannot-be-subscribed-to.md new file mode 100644 index 0000000..7dcc400 --- /dev/null +++ b/docs/TODO/mcp-resources-cannot-be-subscribed-to.md @@ -0,0 +1,65 @@ +# A resource cannot be followed, because the SDK will not advertise subscriptions + +## The issue + +`hhstream://sessions/{id}/logs` is the right shape for watching an application: +a URI whose content changes, which is exactly what MCP resource +**subscriptions** are for (`resources/subscribe`, then +`notifications/resources/updated`). An agent waiting for a build to finish, or +for a page to load, would subscribe once instead of reading in a loop. + +It is not available. `mcp.server.lowlevel.Server.get_capabilities` computes the +resource capability like this (mcp 1.29.0, `server/lowlevel/server.py`): + +```python +if types.ListResourcesRequest in self.request_handlers: + resources_capability = types.ResourcesCapability( + subscribe=False, listChanged=notification_options.resources_changed + ) +``` + +`subscribe=False` is hardcoded. Registering a `@server.subscribe_resource()` +handler does not change it, so a client is told the server cannot be subscribed +to and correctly never tries. The handlers exist on the `Server` class and are +unreachable through the advertised capability. + +This is why `docs/CONTRACT-mcp.md` §4 says there is no following, and why the +`session-logs` resource's own description tells the reader to read it again. It +is also the reason the CLI's `session logs --follow` has no equivalent anywhere +in this surface: the tool form would hang the client, and the resource form is +switched off upstream. + +## Ideas + +1. **Set the capability after construction.** *(recommended)* + `create_initialization_options()` returns the computed capabilities, and the + server is handed them by `serve()` -- so one line in + `hhstream_mcp.server.serve` could set `capabilities.resources.subscribe = + True` before `server.run`, with `subscribe_resource`/`unsubscribe_resource` + handlers behind it. Small, local, and reversible when the SDK grows the + knob. The cost is that it reaches past the SDK's own computation, which is + the kind of thing that breaks on an upgrade without saying so -- so it wants + a unit test asserting the advertised capability, not just the handler. +2. **Poll on the server's side and notify.** Keep `subscribe=False`, and have + the server itself re-read and send `notifications/resources/updated`. Does + not work: a client that was told `subscribe=False` has no reason to have + subscribed, so there is nobody to notify. +3. **Upstream it.** The hardcoded `False` looks like an oversight rather than a + decision; a patch that derives it from whether a `subscribe_resource` + handler was registered would match how every other capability on that method + is computed. Slowest, and the right long-term answer. +4. **Leave it, and say so.** What ships today, in the contract and in the + resource's own description. + +## Why it matters + +It is the difference between an agent that waits and an agent that polls. Every +read is a CLI call in process, so a loop that reads a session's logs every +second is a `hhstream session logs` every second, serialised against every other +call this server makes -- which is exactly the contention the other TODO in this +folder describes. Subscriptions would remove the loop rather than make it +cheaper. + +Medium rather than high because reading again *works*, and because the one +caller who really needs to follow output can run `hhstream session logs +--follow` in a terminal, which is what it is for.