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:
1 parent
6a40c7e2e4
commit
0a63c9b7fc
6 files changed
+818
-197
No files matched your search
+27
-10
@@ -14,7 +14,7 @@
|
||||
# `buildPythonApplication` output is not.
|
||||
#
|
||||
# `grim` and `ffmpeg` do go on PATH, because the CLI itself spawns them --
|
||||
# `shot --output` and `record` are two of the twenty-six tools, and the server
|
||||
# `shot --output` and `record` are two of the twenty-one tools, and the server
|
||||
# is launched by an MCP client whose PATH is not ours to predict. `--prefix`
|
||||
# and not `--set`, so a deployment that wants its own ahead of these puts them
|
||||
# on PATH and wins.
|
||||
@@ -63,19 +63,22 @@ python3.pkgs.buildPythonApplication {
|
||||
# nix/package.nix, for the same reason.
|
||||
doCheck = false;
|
||||
|
||||
# Cheap proof that the tool table builds and the SDK wiring imports: `tools`
|
||||
# constructs all twenty-six at import time, and `server` is the only module
|
||||
# that touches `mcp`. A missing SDK, a schema that is not a dict, or a tool
|
||||
# named twice all fail here rather than at an agent's first call.
|
||||
# Cheap proof that both tables build and the SDK wiring imports: `tools` and
|
||||
# `resources` construct every entry at import time, and `server` is the only
|
||||
# module that touches `mcp`. A missing SDK, a schema that is not a dict, or a
|
||||
# tool named twice all fail here rather than at an agent's first call.
|
||||
pythonImportsCheck = [
|
||||
"hhstream_mcp.tools"
|
||||
"hhstream_mcp.resources"
|
||||
"hhstream_mcp.server"
|
||||
];
|
||||
|
||||
# `pythonImportsCheck` proves the modules load; it does not prove the script
|
||||
# Nix wrapped can run, and the script is what an MCP client spawns.
|
||||
# `--list-tools` is the one code path that exercises argument parsing and the
|
||||
# whole table without opening stdio, so it is the honest smoke test.
|
||||
# `--list-tools` and `--list-resources` are the two code paths that exercise
|
||||
# argument parsing and both whole tables without opening stdio, so together
|
||||
# they are the honest smoke test. `--toolsets` is in it because a selection
|
||||
# that silently served everything would be the failure nobody notices.
|
||||
#
|
||||
# A `postPhases` entry and not `postInstall`, because the script is wrapped in
|
||||
# `fixupPhase`: run any earlier and it has no PYTHONPATH, so `import mcp`
|
||||
@@ -84,9 +87,23 @@ python3.pkgs.buildPythonApplication {
|
||||
postPhases = [ "entryPointCheckPhase" ];
|
||||
entryPointCheckPhase = ''
|
||||
echo "checking the wrapped entry point..."
|
||||
listed=$($out/bin/hhstream-mcp --list-tools)
|
||||
echo "$listed"
|
||||
test "$(echo "$listed" | wc -l)" -ge 26
|
||||
tools=$($out/bin/hhstream-mcp --list-tools)
|
||||
echo "$tools"
|
||||
test "$(echo "$tools" | wc -l)" -eq 21
|
||||
|
||||
resources=$($out/bin/hhstream-mcp --list-resources)
|
||||
echo "$resources"
|
||||
test "$(echo "$resources" | wc -l)" -eq 8
|
||||
|
||||
narrowed=$($out/bin/hhstream-mcp --list-tools --toolsets keyboard | wc -l)
|
||||
echo "--toolsets keyboard offers $narrowed tools"
|
||||
test "$narrowed" -eq 4
|
||||
|
||||
# An unknown toolset must be argparse's exit 2, not a server with no tools.
|
||||
if $out/bin/hhstream-mcp --list-tools --toolsets nonsense; then
|
||||
echo "an unknown toolset was accepted" >&2
|
||||
exit 1
|
||||
fi
|
||||
'';
|
||||
|
||||
meta = {
|
||||
|
||||
+9
-8
@@ -917,16 +917,17 @@ in {
|
||||
# to declare.
|
||||
environment.systemPackages = lib.mkIf cfg.mcp.enable [ cfg.mcp.package ];
|
||||
|
||||
# A warning and not an assertion: twenty-two of the twenty-six tools need
|
||||
# the broker, and an agent handed them against a machine where it is off
|
||||
# gets exit 5 from every one of them -- which is a true answer, badly
|
||||
# timed. The four frame tools are genuinely useful on their own, so this is
|
||||
# a thing worth saying rather than a thing worth refusing.
|
||||
# A warning and not an assertion: eighteen of the twenty-one tools and six
|
||||
# of the eight resources need the broker, and an agent handed them against
|
||||
# a machine where it is off gets exit 5 from every one of them -- which is
|
||||
# a true answer, badly timed. The frame tools are genuinely useful on their
|
||||
# own, so this is a thing worth saying rather than a thing worth refusing.
|
||||
warnings = lib.optional (cfg.mcp.enable && !cfg.sessions.enable) ''
|
||||
services.hyprland-headless-stream.mcp.enable is on while sessions.enable
|
||||
is off: the MCP server's session, pointer and keyboard tools will all
|
||||
fail with exit 5 (the broker is unreachable). Only status, shot, record
|
||||
and run will work.
|
||||
is off: the MCP server's session, pointer and keyboard tools, and every
|
||||
resource but hhstream://status and hhstream://screen, will fail because
|
||||
the broker is unreachable (exit 5). Only shot, record, run and those two
|
||||
resources will work.
|
||||
'';
|
||||
|
||||
# The broker's state directory and the moved socket directory are two
|
||||
|
||||
+16
-13
@@ -15,7 +15,7 @@ the client would see its connection die:
|
||||
the whole process through the setuid ``sg`` wrapper when the frame socket is
|
||||
out of reach.
|
||||
2. ``cmd_run`` ends in ``os.execvpe`` -- that *is* the verb. ``run`` therefore
|
||||
forks first; see :meth:`Runner.launch`.
|
||||
spawns instead; see :meth:`Runner.launch`.
|
||||
|
||||
So the parser is the CLI's (``cli.build_parser``), the handler is the one
|
||||
argparse selected, and the exit code is that handler's own return value. What
|
||||
@@ -139,20 +139,20 @@ REMEDY: dict[int, str] = {
|
||||
"Fix the arguments; retrying the same call will fail the same way."
|
||||
),
|
||||
ExitCode.NO_SUCH_SESSION: (
|
||||
"No session (or process) by that id. Call `session_list` to see which "
|
||||
"ids exist; a reaped session is gone and has to be started again."
|
||||
"No session (or process) by that id. Read `hhstream://sessions` to see "
|
||||
"which ids exist; a reaped session is gone and has to be started again."
|
||||
),
|
||||
ExitCode.BAD_STATE: (
|
||||
"The session exists but is not in a state this verb can act on -- it "
|
||||
"is still starting, or it has already exited, been killed or been "
|
||||
"reaped. Call `session_status` to see which."
|
||||
"reaped. Read `hhstream://sessions/<id>` to see which."
|
||||
),
|
||||
ExitCode.DAEMON_UNREACHABLE: (
|
||||
"The session broker (`hhstreamd`) could not be reached on its control "
|
||||
"socket. Nothing was done. This is an operator problem, not an "
|
||||
"argument problem: the daemon is down, or $HHSTREAM_SOCKET points "
|
||||
"somewhere else. Frame tools (`status`, `shot`, `record`, `run`) do "
|
||||
"not need the broker and may still work."
|
||||
"somewhere else. The frame tools (`shot`, `record`, `run`) and "
|
||||
"`hhstream://status` do not need the broker and may still work."
|
||||
),
|
||||
ExitCode.POLICY: (
|
||||
"Refused by policy. The application is not on the broker's allowlist, "
|
||||
@@ -162,16 +162,18 @@ REMEDY: dict[int, str] = {
|
||||
),
|
||||
ExitCode.TIMEOUT: (
|
||||
"The broker accepted the request and did not finish in time. Whether "
|
||||
"it took effect is unknown -- read the state back (`session_status`, "
|
||||
"`session_list`, `pointer_state`) before retrying, and retry with the "
|
||||
"same `request_id` so a mutation cannot happen twice."
|
||||
"it took effect is unknown -- read the state back "
|
||||
"(`hhstream://sessions`, `hhstream://sessions/<id>`, "
|
||||
"`hhstream://pointer`) before retrying, and retry with the same "
|
||||
"`request_id` so a mutation cannot happen twice."
|
||||
),
|
||||
ExitCode.BUSY: (
|
||||
"Something else holds what this call needs -- for the pointer and "
|
||||
"keyboard verbs, another session holds the one pointer lease, and the "
|
||||
"refusal names the holder. Nothing was injected. Call `pointer_state` "
|
||||
"to see who holds it, then wait for them to release it or for its TTL "
|
||||
"to expire. Do NOT try to take it from them; there is no such verb."
|
||||
"refusal names the holder. Nothing was injected. Read "
|
||||
"`hhstream://pointer` to see who holds it, then wait for them to "
|
||||
"release it or for its TTL to expire. Do NOT try to take it from "
|
||||
"them; there is no such verb."
|
||||
),
|
||||
ExitCode.NO_LEASE: (
|
||||
"This verb needs the pointer lease and this session does not hold one "
|
||||
@@ -191,7 +193,8 @@ REMEDY: dict[int, str] = {
|
||||
GENERIC_FAILURE: (
|
||||
"The command failed without one of the broker's classified codes. For "
|
||||
"the frame tools this is usually the publisher sending no frame (is the "
|
||||
"compositor up? call `status`) or `grim`/`ffmpeg` missing from the "
|
||||
"compositor up? read `hhstream://status`) or `grim`/`ffmpeg` missing "
|
||||
"from the "
|
||||
"server's PATH. The text below is the CLI's own."
|
||||
),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
"""The read-only half of the surface: state as resources. Standard library only.
|
||||
|
||||
Every verb of the CLI that only *reads* is addressed by URI here rather than
|
||||
called as a tool, because that is the split the protocol draws. 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 business. A
|
||||
tool is **model**-controlled: an act the model chooses to perform, and every one
|
||||
left in :mod:`hhstream_mcp.tools` either changes something or costs something.
|
||||
|
||||
So the line is not "cheap here, expensive there" -- it is *who decides*.
|
||||
``hhstream://sessions`` is state a host may always include; ``session_kill`` is
|
||||
a decision only the model can make.
|
||||
|
||||
Two things this module is careful about:
|
||||
|
||||
* **A resource read must not write.** That rules out ``session container <id>``,
|
||||
which looks like a read and is not: with an id the CLI runs
|
||||
``container.reconcile`` and brings the record up to the compositor's answer.
|
||||
Only the no-id form (``container.list``) is here, as ``hhstream://containers``;
|
||||
the reconciling form stays the ``session_container`` tool.
|
||||
* **A refusal must not arrive as content.** There is no ``isError`` on a
|
||||
resource read, so a CLI refusal is *raised* and carries the same remedy
|
||||
sentence a tool error would have. Returning the broker's failure object as
|
||||
the body would make "this session does not exist" look like a successful read
|
||||
of a session.
|
||||
|
||||
Arguments become query parameters, because a resource read takes nothing but a
|
||||
URI. Only the declared ones are accepted -- an unknown parameter is refused
|
||||
rather than dropped, for the reason every tool schema sets
|
||||
``additionalProperties: false``: an argument silently ignored is a read that
|
||||
answered a different question than the one asked.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import urllib.parse
|
||||
from typing import Any, Callable
|
||||
|
||||
from . import media, tools
|
||||
from .invoke import Outcome, Runner, remedy_for
|
||||
|
||||
#: The scheme every resource here lives under. One, because they are all views
|
||||
#: of one machine's one desktop.
|
||||
SCHEME = "hhstream"
|
||||
|
||||
JSON = "application/json"
|
||||
TEXT = "text/plain"
|
||||
|
||||
|
||||
class ReadRefused(Exception):
|
||||
"""The CLI refused, or the URI names nothing. Raised, never returned.
|
||||
|
||||
Carries what a tool error would have carried, so a host that surfaces the
|
||||
message gives its model the same remedy a tool call would have given it.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, detail: dict[str, Any] | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.detail = detail or {}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reading:
|
||||
"""What one resource read produced. Text or bytes, never both."""
|
||||
|
||||
media_type: str
|
||||
text: str | None = None
|
||||
blob: bytes | None = None
|
||||
|
||||
|
||||
Read = Callable[[Runner, dict[str, str]], Reading]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Entry:
|
||||
"""One resource, or one family of them.
|
||||
|
||||
``route`` is the URI after the scheme, as segments: a literal matches
|
||||
itself, ``{name}`` captures exactly one segment. An entry with a capture is
|
||||
a *template*; there is no second class for it, because the only thing that
|
||||
differs is whether ``resources/list`` or ``resources/templates/list``
|
||||
mentions it.
|
||||
"""
|
||||
|
||||
route: tuple[str, ...]
|
||||
name: str
|
||||
title: str
|
||||
description: str
|
||||
media_type: str
|
||||
read: Read
|
||||
#: Query parameters this read accepts, by the name an agent puts in the
|
||||
#: URI. What each becomes on the command line is :data:`_FLAGS`' business,
|
||||
#: so that translation lives in one place rather than once per entry.
|
||||
parameters: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def captures(self) -> tuple[str, ...]:
|
||||
return tuple(s[1:-1] for s in self.route if s.startswith("{"))
|
||||
|
||||
@property
|
||||
def is_template(self) -> bool:
|
||||
return bool(self.captures)
|
||||
|
||||
@property
|
||||
def uri(self) -> str:
|
||||
"""The concrete URI. Only meaningful for an entry with no captures."""
|
||||
|
||||
return f"{SCHEME}://" + "/".join(self.route)
|
||||
|
||||
@property
|
||||
def uri_template(self) -> str:
|
||||
"""RFC 6570, including the query parameters it accepts."""
|
||||
|
||||
base = f"{SCHEME}://" + "/".join(self.route)
|
||||
if not self.parameters:
|
||||
return base
|
||||
return base + "{?" + ",".join(sorted(self.parameters)) + "}"
|
||||
|
||||
def match(self, segments: tuple[str, ...]) -> dict[str, str] | None:
|
||||
"""The captured values, or ``None`` if this entry is not the one."""
|
||||
|
||||
if len(segments) != len(self.route):
|
||||
return None
|
||||
captured: dict[str, str] = {}
|
||||
for pattern, value in zip(self.route, segments):
|
||||
if pattern.startswith("{"):
|
||||
if not value:
|
||||
return None
|
||||
captured[pattern[1:-1]] = value
|
||||
elif pattern != value:
|
||||
return None
|
||||
return captured
|
||||
|
||||
|
||||
# ── parsing a URI ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def split(uri: str) -> tuple[tuple[str, ...], dict[str, str]]:
|
||||
"""``hhstream://sessions/s-1/logs?lines=5`` -> ``(("sessions","s-1","logs"), {...})``.
|
||||
|
||||
The authority and the path are one route: ``urlsplit`` puts the first
|
||||
segment in ``netloc`` for a ``scheme://a/b`` URI, which is an artefact of
|
||||
the form rather than a distinction worth preserving.
|
||||
"""
|
||||
|
||||
parsed = urllib.parse.urlsplit(uri)
|
||||
if parsed.scheme != SCHEME:
|
||||
raise ReadRefused(
|
||||
f"not a {SCHEME} resource: {uri!r}. Every resource this server "
|
||||
f"serves is {SCHEME}://… — call resources/list for the set."
|
||||
)
|
||||
joined = parsed.netloc + parsed.path
|
||||
segments = tuple(s for s in joined.split("/") if s)
|
||||
if not segments:
|
||||
raise ReadRefused(f"{uri!r} names no resource; call resources/list")
|
||||
query: dict[str, str] = {}
|
||||
for key, value in urllib.parse.parse_qsl(parsed.query, keep_blank_values=True):
|
||||
if key in query:
|
||||
raise ReadRefused(
|
||||
f"{key!r} is given more than once in {uri!r}; each parameter "
|
||||
"takes one value"
|
||||
)
|
||||
query[key] = value
|
||||
return segments, query
|
||||
|
||||
|
||||
def resolve(uri: str) -> tuple[Entry, dict[str, str]]:
|
||||
"""The entry for ``uri``, with its captures and validated query merged.
|
||||
|
||||
Literal routes are tried before templates, so ``hhstream://sessions`` is the
|
||||
listing and not a session whose id happens to be absent.
|
||||
"""
|
||||
|
||||
segments, query = split(uri)
|
||||
for entry in sorted(ENTRIES, key=lambda e: len(e.captures)):
|
||||
captured = entry.match(segments)
|
||||
if captured is None:
|
||||
continue
|
||||
unknown = set(query) - set(entry.parameters)
|
||||
if unknown:
|
||||
accepted = ", ".join(sorted(entry.parameters)) or "none"
|
||||
raise ReadRefused(
|
||||
f"{entry.name} does not accept "
|
||||
f"{', '.join(repr(u) for u in sorted(unknown))}; it accepts: {accepted}"
|
||||
)
|
||||
return entry, {**captured, **query}
|
||||
raise ReadRefused(
|
||||
f"no resource at {uri!r}. Call resources/list for the fixed ones and "
|
||||
"resources/templates/list for the rest."
|
||||
)
|
||||
|
||||
|
||||
# ── turning a CLI call into a reading ──────────────────────────────────────
|
||||
|
||||
|
||||
def _checked(outcome: Outcome, what: str) -> Outcome:
|
||||
"""The outcome, or a refusal carrying the CLI's own words and the remedy."""
|
||||
|
||||
if outcome.ok:
|
||||
return outcome
|
||||
payload = outcome.payload() or {}
|
||||
said = (outcome.stderr or outcome.stdout).strip()
|
||||
raise ReadRefused(
|
||||
f"could not read {what}: {remedy_for(outcome.returncode)}"
|
||||
+ (f"\n\n{said}" if said else ""),
|
||||
{
|
||||
"ok": False,
|
||||
"exit_code": outcome.returncode,
|
||||
"error": payload.get("error"),
|
||||
"reason": payload.get("reason"),
|
||||
"hint": payload.get("hint"),
|
||||
"remedy": remedy_for(outcome.returncode),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
#: Query parameter -> the flag it becomes on the command line. One table, not
|
||||
#: one entry per resource: the name an agent puts in a URI and the flag the CLI
|
||||
#: takes are allowed to differ, and a per-entry copy would be a per-entry
|
||||
#: chance for them to disagree.
|
||||
_FLAGS = {"all": "all", "events": "events", "lines": "lines"}
|
||||
|
||||
#: Of those, the ones that are switches and not values -- so `?all=true` is
|
||||
#: `--all` and `?all=false` is no flag at all, rather than `--all=false`, which
|
||||
#: the CLI would refuse.
|
||||
_SWITCHES = {"all"}
|
||||
|
||||
_FALSE = {"false", "0", "no", "off", ""}
|
||||
|
||||
|
||||
def _flag_for(name: str, value: str) -> list[str]:
|
||||
flag = _FLAGS[name]
|
||||
if name in _SWITCHES:
|
||||
return [] if value.strip().lower() in _FALSE else [f"--{flag}"]
|
||||
return [tools.flag(flag, value)]
|
||||
|
||||
|
||||
def _json_read(verb: list[str], what: str) -> Read:
|
||||
"""A ``--json`` verb's protocol object, verbatim, as the resource's body.
|
||||
|
||||
Verbatim because that object is what the broker actually said, and a
|
||||
resource that reshaped it would be a second wire format for the same facts.
|
||||
"""
|
||||
|
||||
def read(runner: Runner, arguments: dict[str, str]) -> Reading:
|
||||
options = ["--json"]
|
||||
for name in sorted(arguments):
|
||||
if name in _FLAGS:
|
||||
options.extend(_flag_for(name, arguments[name]))
|
||||
positionals = [arguments["id"]] if "id" in arguments else []
|
||||
outcome = _checked(runner.run(tools.argv(verb, options, positionals)), what)
|
||||
return Reading(media_type=JSON, text=outcome.stdout.strip())
|
||||
|
||||
return read
|
||||
|
||||
|
||||
def _status(runner: Runner, arguments: dict[str, str]) -> Reading:
|
||||
"""``hhstream status``: the one verb with no ``--json``, so it stays text."""
|
||||
|
||||
outcome = _checked(runner.run(["status"]), "the session's status")
|
||||
return Reading(media_type=TEXT, text=outcome.stdout.strip())
|
||||
|
||||
|
||||
def _frame(runner: Runner, arguments: dict[str, str]) -> Reading:
|
||||
"""One captured frame as bytes.
|
||||
|
||||
Serves both the whole screen and one named output: ``hhstream://screen``
|
||||
captures with no ``--output`` and ``hhstream://outputs/{name}`` captures
|
||||
with one, which is the same CLI call with one flag more.
|
||||
|
||||
The media type is read off the bytes, never assumed: the publisher serves
|
||||
`image/jpeg` on some machines and the CLI writes the payload it was given
|
||||
verbatim, so the entry's declared `mimeType` is a hint and this is the
|
||||
answer.
|
||||
"""
|
||||
|
||||
named = arguments.get("name")
|
||||
what = f"output {named!r}" if named else "the screen"
|
||||
outcome, frame = tools.capture(runner, named)
|
||||
_checked(outcome, what)
|
||||
if frame is None:
|
||||
raise ReadRefused(
|
||||
f"hhstream shot reported success but wrote no readable file for {what}"
|
||||
)
|
||||
image = media.sniff(frame)
|
||||
return Reading(
|
||||
media_type=image.media_type if image else "application/octet-stream",
|
||||
blob=frame,
|
||||
)
|
||||
|
||||
|
||||
# ── the table ──────────────────────────────────────────────────────────────
|
||||
|
||||
#: Appended to the three descriptions whose verb the CLI's own note names.
|
||||
_NOT_ACTIVITY = (
|
||||
" Reading this does NOT reset the session's idle clock -- only the "
|
||||
"`session_touch` tool does."
|
||||
)
|
||||
|
||||
ENTRIES: tuple[Entry, ...] = (
|
||||
Entry(
|
||||
route=("status",),
|
||||
name="status",
|
||||
title="Is the desktop up",
|
||||
description=(
|
||||
"Whether the headless Hyprland session is running and reachable: "
|
||||
"each unit's state, the frame socket's path and whether this "
|
||||
"server can read it, the Wayland socket the compositor bound, and "
|
||||
"one probe frame's size. Read this first when something else "
|
||||
"fails in a way that smells like the desktop being down. It says "
|
||||
"nothing about the session broker -- an unreachable broker shows "
|
||||
"up as exit 5 from a session tool or a failed read of "
|
||||
"`hhstream://sessions`."
|
||||
),
|
||||
media_type=TEXT,
|
||||
read=_status,
|
||||
),
|
||||
Entry(
|
||||
route=("sessions",),
|
||||
name="sessions",
|
||||
title="Every tracked session",
|
||||
description=(
|
||||
"The broker's list: every session it is tracking, with its state, "
|
||||
"pid and idle deadline. `?all=true` includes the tombstones of "
|
||||
"ended ones." + _NOT_ACTIVITY
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "list"], "the session list"),
|
||||
parameters=("all",),
|
||||
),
|
||||
Entry(
|
||||
route=("pointer",),
|
||||
name="pointer",
|
||||
title="Who holds the pointer",
|
||||
description=(
|
||||
"Who holds the one pointer lease, since when, and which buttons "
|
||||
"and KEYS are held down. This is what to read after a tool "
|
||||
"returns exit 8 (BUSY): it names the holder. There is one cursor, "
|
||||
"so there is one of these." + _NOT_ACTIVITY
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "pointer", "state"], "the pointer lease"),
|
||||
),
|
||||
Entry(
|
||||
route=("containers",),
|
||||
name="containers",
|
||||
title="Every container, and the orphans",
|
||||
description=(
|
||||
"Each session's output, workspace and mode, plus the `hh-*` "
|
||||
"outputs no live session claims. The output names here are what "
|
||||
"`hhstream://outputs/{name}` and the `record` tool take.\n\n"
|
||||
"This is the LIST, which only reads the record. Asking where a "
|
||||
"session's window is *now* re-reads the compositor and writes the "
|
||||
"answer back, so it is the `session_container` tool and not a "
|
||||
"resource." + _NOT_ACTIVITY
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "container"], "the container list"),
|
||||
),
|
||||
Entry(
|
||||
route=("screen",),
|
||||
name="screen",
|
||||
title="One frame of the screen",
|
||||
description=(
|
||||
"The published main output, as an image. This is the whole "
|
||||
"compositor layout: with containers on, each session's own output "
|
||||
"sits beside the main one, so the frame is wider than any single "
|
||||
"output's configured size. For one container alone, read "
|
||||
"`hhstream://outputs/{name}`."
|
||||
),
|
||||
media_type="image/png",
|
||||
read=_frame,
|
||||
),
|
||||
Entry(
|
||||
route=("sessions", "{id}"),
|
||||
name="session",
|
||||
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. `?events=N` "
|
||||
"sets how many of those to include. The audit events are where a "
|
||||
"session that died for a reason its own logs do not show explains "
|
||||
"itself." + _NOT_ACTIVITY
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "status"], "that session"),
|
||||
parameters=("events",),
|
||||
),
|
||||
Entry(
|
||||
route=("sessions", "{id}", "logs"),
|
||||
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. `?lines=N` sets how "
|
||||
"much to tail.\n\n"
|
||||
"There is no following here and there cannot be: this SDK does "
|
||||
"not advertise resource subscriptions, and the CLI's `--follow` "
|
||||
"polls until interrupted. Read it again instead." + _NOT_ACTIVITY
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "logs"], "that session's logs"),
|
||||
parameters=("lines",),
|
||||
),
|
||||
Entry(
|
||||
route=("outputs", "{name}"),
|
||||
name="output",
|
||||
title="One output's frame",
|
||||
description=(
|
||||
"One output captured in isolation through `grim` -- a session's "
|
||||
"container is `hh-<session-id>`, and `hhstream://containers` "
|
||||
"lists the names. Unlike `hhstream://screen` this is exactly the "
|
||||
"configured size of that output, which is the coordinate space "
|
||||
"the pointer tools aim in."
|
||||
),
|
||||
media_type="image/png",
|
||||
read=_frame,
|
||||
),
|
||||
)
|
||||
|
||||
BY_NAME: dict[str, Entry] = {entry.name: entry for entry in ENTRIES}
|
||||
|
||||
#: The fixed ones, for `resources/list`.
|
||||
FIXED: tuple[Entry, ...] = tuple(e for e in ENTRIES if not e.is_template)
|
||||
#: The rest, for `resources/templates/list`.
|
||||
TEMPLATES: tuple[Entry, ...] = tuple(e for e in ENTRIES if e.is_template)
|
||||
|
||||
|
||||
def read(runner: Runner, uri: str) -> Reading:
|
||||
"""Resolve ``uri`` and read it. Raises :class:`ReadRefused`."""
|
||||
|
||||
entry, arguments = resolve(uri)
|
||||
return entry.read(runner, arguments)
|
||||
+182
-26
@@ -36,9 +36,12 @@ from typing import Any
|
||||
import anyio
|
||||
import mcp.types as types
|
||||
from mcp.server.lowlevel import NotificationOptions, Server
|
||||
from mcp.server.lowlevel.helper_types import ReadResourceContents
|
||||
from mcp.server.stdio import stdio_server
|
||||
from mcp.shared.exceptions import McpError
|
||||
from pydantic import AnyUrl
|
||||
|
||||
from . import SERVER_NAME, __version__, tools
|
||||
from . import SERVER_NAME, __version__, resources, tools
|
||||
from .invoke import Runner
|
||||
|
||||
log = logging.getLogger("hhstream.mcp")
|
||||
@@ -51,29 +54,39 @@ INSTRUCTIONS = """\
|
||||
Drive this machine's headless Hyprland desktop: look at it, put applications on
|
||||
it, and aim its one pointer and keyboard at them.
|
||||
|
||||
Each tool is one verb of the `hhstream` CLI and does nothing the CLI would not.
|
||||
Where to start: `status` says whether the desktop is up; `session_start` puts an
|
||||
allowlisted application on it and returns a session id; `shot` shows you the
|
||||
screen; `pointer_acquire` gives you the lease that every pointer and keyboard
|
||||
tool needs.
|
||||
Everything here is one verb of the `hhstream` CLI and does nothing the CLI would
|
||||
not. The surface is split the way the protocol splits it:
|
||||
|
||||
* **Resources are the state.** `hhstream://status` is whether the desktop is up,
|
||||
`hhstream://sessions` is what is running, `hhstream://sessions/<id>` is one of
|
||||
them with its recent audit events, `hhstream://sessions/<id>/logs` is an
|
||||
application's own output, `hhstream://pointer` is who holds the input lease,
|
||||
`hhstream://containers` is each session's output and workspace. Reading any of
|
||||
them changes nothing.
|
||||
* **Tools are the acts.** `session_start` puts an allowlisted application on the
|
||||
screen and returns a session id; `shot` captures the screen now;
|
||||
`pointer_acquire` gives you the lease every pointer and keyboard tool needs;
|
||||
`session_kill` ends a session.
|
||||
|
||||
Two rules this surface will not let you avoid, because they are the two an agent
|
||||
gets wrong:
|
||||
|
||||
1. `session_touch` is the ONLY thing that resets a session's idle clock.
|
||||
Listing, reading status, reading logs, collecting garbage, clicking and
|
||||
typing all deliberately do NOT. A session being driven is still a session
|
||||
nobody has said they want kept, and the broker reaps it on schedule.
|
||||
Reading any resource deliberately does NOT, nor does `session_gc`, nor does
|
||||
clicking or typing. A session being driven is still a session nobody has said
|
||||
they want kept, and the broker reaps it on schedule.
|
||||
|
||||
2. Every keyboard tool needs the POINTER lease, and holds only while that lease
|
||||
holds. There is no keyboard lease: one compositor seat means one keyboard
|
||||
focus. A held non-modifier key floods the window until you lift it or the
|
||||
lease expires, because the application does the repeating.
|
||||
|
||||
Failures come back as tool errors carrying the CLI's own exit code, its
|
||||
Tool failures come back as tool errors carrying the CLI's own exit code, its
|
||||
machine-readable error name, its reason and what to do next. Exit 8 means
|
||||
another session holds the pointer lease (`pointer_state` names the holder); exit
|
||||
9 means you need to acquire one.
|
||||
another session holds the pointer lease (read `hhstream://pointer` for the
|
||||
holder); exit 9 means you need to acquire one. A resource read that the CLI
|
||||
refuses is raised as an error carrying the same remedy, because a resource has
|
||||
no way to hand back a failure as content.
|
||||
"""
|
||||
|
||||
|
||||
@@ -126,7 +139,12 @@ def content_for(result: tools.Result) -> list[types.ContentBlock]:
|
||||
return blocks
|
||||
|
||||
|
||||
def call(runner: Runner, name: str, arguments: dict[str, Any]) -> types.CallToolResult:
|
||||
def call(
|
||||
runner: Runner,
|
||||
name: str,
|
||||
arguments: dict[str, Any],
|
||||
available: Any = None,
|
||||
) -> types.CallToolResult:
|
||||
"""Run one tool. A refusal comes back as a tool error, never as a success.
|
||||
|
||||
``isError`` rather than a JSON-RPC error, throughout. That is not only a
|
||||
@@ -139,16 +157,35 @@ def call(runner: Runner, name: str, arguments: dict[str, Any]) -> types.CallTool
|
||||
verdict at all: a tool name that does not exist, and this layer's own bug.
|
||||
"""
|
||||
|
||||
tool = tools.BY_NAME.get(name)
|
||||
# The *selected* set, not the whole table: a tool `--toolsets` left out is
|
||||
# not listed, so calling it must fail rather than work anyway. The SDK only
|
||||
# validates arguments against what `tools/list` returned, so without this a
|
||||
# client could reach an unlisted tool by name.
|
||||
offered = tools.BY_NAME if available is None else available
|
||||
tool = offered.get(name)
|
||||
if tool is None:
|
||||
known = ", ".join(sorted(offered)) or "nothing (every toolset is disabled)"
|
||||
hint = ""
|
||||
if name in tools.MOVED_TO_RESOURCES:
|
||||
# The v1 name. Say where it went rather than only that it is gone:
|
||||
# a caller asking for `session_list` wants the session list, and the
|
||||
# answer is one `resources/read` away.
|
||||
hint = (
|
||||
f" It is a RESOURCE now, not a tool: read "
|
||||
f"{tools.MOVED_TO_RESOURCES[name]} instead. Reading state is "
|
||||
"the host's to offer, not the model's to call -- call "
|
||||
"resources/list for the whole read-only half of this server."
|
||||
)
|
||||
elif name in tools.BY_NAME:
|
||||
hint = (
|
||||
f" {name!r} exists but this server was started without its "
|
||||
"toolset, so it is not offered."
|
||||
)
|
||||
return types.CallToolResult(
|
||||
content=[
|
||||
types.TextContent(
|
||||
type="text",
|
||||
text=(
|
||||
f"no such tool: {name!r}. This server exposes: "
|
||||
f"{', '.join(sorted(tools.BY_NAME))}"
|
||||
),
|
||||
text=f"no such tool: {name!r}.{hint} This server exposes: {known}",
|
||||
)
|
||||
],
|
||||
structuredContent={"ok": False, "error": "no_such_tool"},
|
||||
@@ -175,14 +212,86 @@ def call(runner: Runner, name: str, arguments: dict[str, Any]) -> types.CallTool
|
||||
)
|
||||
|
||||
|
||||
def build(runner: Runner) -> Server:
|
||||
# ── resources ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def describe_resource(entry: resources.Entry) -> types.Resource:
|
||||
return types.Resource(
|
||||
uri=AnyUrl(entry.uri),
|
||||
name=entry.name,
|
||||
title=entry.title,
|
||||
description=entry.description,
|
||||
mimeType=entry.media_type,
|
||||
)
|
||||
|
||||
|
||||
def describe_template(entry: resources.Entry) -> types.ResourceTemplate:
|
||||
return types.ResourceTemplate(
|
||||
uriTemplate=entry.uri_template,
|
||||
name=entry.name,
|
||||
title=entry.title,
|
||||
description=entry.description,
|
||||
mimeType=entry.media_type,
|
||||
)
|
||||
|
||||
|
||||
def resource_listing() -> list[types.Resource]:
|
||||
return [describe_resource(entry) for entry in resources.FIXED]
|
||||
|
||||
|
||||
def template_listing() -> list[types.ResourceTemplate]:
|
||||
return [describe_template(entry) for entry in resources.TEMPLATES]
|
||||
|
||||
|
||||
def read(runner: Runner, uri: str) -> list[ReadResourceContents]:
|
||||
"""One resource read. A refusal is an error, because there is no other way.
|
||||
|
||||
A ``CallToolResult`` can say ``isError``; ``ReadResourceResult`` cannot. So
|
||||
a URI that names nothing, or a CLI that refused, is raised as a JSON-RPC
|
||||
error carrying the remedy a tool error would have carried. Handing back the
|
||||
broker's failure object as the resource's *body* would make "no such
|
||||
session" read as a successful read of a session.
|
||||
"""
|
||||
|
||||
try:
|
||||
reading = resources.read(runner, uri)
|
||||
except resources.ReadRefused as refused:
|
||||
raise McpError(
|
||||
types.ErrorData(
|
||||
code=types.INVALID_PARAMS,
|
||||
message=refused.message,
|
||||
data=refused.detail or None,
|
||||
)
|
||||
) from refused
|
||||
body = reading.blob if reading.blob is not None else (reading.text or "")
|
||||
return [ReadResourceContents(content=body, mime_type=reading.media_type)]
|
||||
|
||||
|
||||
def build(runner: Runner, toolsets: Any = None) -> Server:
|
||||
server: Server = Server(
|
||||
SERVER_NAME, version=__version__, instructions=INSTRUCTIONS
|
||||
)
|
||||
available = tools.selected(toolsets)
|
||||
by_name = {tool.name: tool for tool in available}
|
||||
|
||||
@server.list_tools()
|
||||
async def _list() -> list[types.Tool]:
|
||||
return listing()
|
||||
return [describe(tool) for tool in available]
|
||||
|
||||
@server.list_resources()
|
||||
async def _list_resources() -> list[types.Resource]:
|
||||
return resource_listing()
|
||||
|
||||
@server.list_resource_templates()
|
||||
async def _list_templates() -> list[types.ResourceTemplate]:
|
||||
return template_listing()
|
||||
|
||||
@server.read_resource()
|
||||
async def _read_resource(uri: AnyUrl) -> list[ReadResourceContents]:
|
||||
# Off the event loop for the reason a tool call is: this runs the CLI,
|
||||
# which blocks. `str(uri)` because the route is parsed here, not by
|
||||
# pydantic -- see `resources.split`.
|
||||
return await anyio.to_thread.run_sync(lambda: read(runner, str(uri)))
|
||||
|
||||
# `validate_input` left on: the schemas are the first refusal, and they
|
||||
# refuse before an argv list exists.
|
||||
@@ -193,7 +302,7 @@ def build(runner: Runner) -> Server:
|
||||
# loop stays free to answer a ping and to read the next request. The
|
||||
# calls themselves are serialised inside `Runner.run`, because the CLI
|
||||
# prints to a stdout this process shares.
|
||||
return await anyio.to_thread.run_sync(lambda: call(runner, name, arguments))
|
||||
return await anyio.to_thread.run_sync(lambda: call(runner, name, arguments, by_name))
|
||||
|
||||
return server
|
||||
|
||||
@@ -252,16 +361,45 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
"disagree. Set them in the MCP client's `env` block."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--toolsets",
|
||||
metavar="NAMES",
|
||||
help="comma-separated families to offer as tools: "
|
||||
+ ", ".join(tools.TOOLSETS)
|
||||
+ ". Omitted, every tool is offered. Resources are NOT filtered by "
|
||||
"this -- they are the host's context, not the model's tool budget.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--list-tools",
|
||||
action="store_true",
|
||||
help="print the tool names and exit, without serving. For checking an install.",
|
||||
help="print the tool names and exit, without serving. Honours "
|
||||
"--toolsets, so it is also how to see what a selection would offer.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--list-resources",
|
||||
action="store_true",
|
||||
help="print the resource URIs and templates and exit, without serving.",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def chosen_toolsets(raw: str | None) -> list[str] | None:
|
||||
"""``--toolsets`` as a list, or ``None`` for every tool."""
|
||||
|
||||
if raw is None:
|
||||
return None
|
||||
names = [part.strip() for part in raw.split(",") if part.strip()]
|
||||
if not names:
|
||||
raise tools.UnknownToolset(
|
||||
"--toolsets was given no names. Omit the flag for every tool, or "
|
||||
f"name some of: {', '.join(tools.TOOLSETS)}"
|
||||
)
|
||||
return names
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
# stderr, never stdout: stdout is the transport, and one stray print on it
|
||||
# is a protocol error the client reports as a parse failure.
|
||||
logging.basicConfig(
|
||||
@@ -269,15 +407,33 @@ def main(argv: list[str] | None = None) -> int:
|
||||
stream=sys.stderr,
|
||||
format="%(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
try:
|
||||
toolsets = chosen_toolsets(args.toolsets)
|
||||
offered = tools.selected(toolsets)
|
||||
except tools.UnknownToolset as exc:
|
||||
# argparse's own exit code for a bad argument, because that is what
|
||||
# this is: `choices=` cannot express a comma-separated subset.
|
||||
parser.error(str(exc))
|
||||
return int(2) # pragma: no cover -- parser.error exits
|
||||
if args.list_tools:
|
||||
for tool in tools.TOOLS:
|
||||
for tool in offered:
|
||||
print(f"{tool.name}\t{tool.title}")
|
||||
return 0
|
||||
log.info("serving %d tools over stdio", len(tools.TOOLS))
|
||||
if args.list_resources:
|
||||
for entry in resources.FIXED:
|
||||
print(f"{entry.uri}\t{entry.title}")
|
||||
for entry in resources.TEMPLATES:
|
||||
print(f"{entry.uri_template}\t{entry.title}")
|
||||
return 0
|
||||
log.info(
|
||||
"serving %d tools and %d resources over stdio",
|
||||
len(offered),
|
||||
len(resources.ENTRIES),
|
||||
)
|
||||
# The transport is claimed before the event loop starts, so no coroutine can
|
||||
# have written to fd 1 by the time it moves.
|
||||
transport = claim_transport()
|
||||
anyio.run(serve, build(Runner()), transport)
|
||||
anyio.run(serve, build(Runner(), toolsets), transport)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
+148
-140
@@ -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)
|
||||
Reference in new issue
Block a user