feat(nix): mcp.http, its unit, and a state directory of its own

`mcp.http.enable` is the fourth unit and the first that listens on a
port.  The comment on the `mcp` block said anything that started a daemon
here "would be inventing a second thing to supervise", so it is rewritten
rather than deleted: what changed is not the cost of supervising it but
what it buys -- a port is reachable by a caller who never touched this
filesystem, which is the first time a token on this surface means
anything.  The two options stay independent and neither implies the
other.

`mcp.stateDir` defaults to /var/lib/hhstream-mcp and is deliberately NOT
`sessions.stateDir`.  That directory is 0700 owned by the broker's user
and holds `events.jsonl`; parking a token file in it would grant this
shim write access to the audit trail's directory for no reason, and the
two have different lifetimes besides.  A tmpfiles entry rather than
`StateDirectory=`, for the reason the broker's state dir is one --
`StateDirectory=` can only name a path under /var/lib and would stop
applying the moment the option is pointed elsewhere.

The unit runs as sessions.user with sessions.group, because its tools are
the CLI's handlers called in process and that CLI opens a 0660 control
socket owned by that user and a compositor runtime directory owned by
that group.  `Wants`/`After` the broker and not `BindsTo`: the frame
verbs answer with the broker down and the rest answer exit 5, which is a
true answer, whereas a listener that vanished with the broker would turn
that into a connection refused and tell a client nothing.  The systemd
default KillMode is right here and `KillMode=process` -- which the broker
and the driver both need -- would be wrong, because every process this
unit starts is part of answering one request.

Two assertions and two warnings, each for a failure that is otherwise
discovered from the far side of an HTTP client:

* http.enable without sessions.enable is an assertion, not the warning
  `mcp.enable` gets against the same condition, because there the frame
  tools still work and here `User=` names an account that does not exist.
* a wildcard bind with no allowedHosts is an assertion, because the
  SDK's rebinding allowlist has no implicit localhost and the unit would
  come up refusing everything with a 421.
* a non-loopback address warns that the token crosses the wire in clear
  text, since the option reads like a bind address and not like a
  decision about what is on it.
* openFirewall warns and is not implied by http.enable, the same way
  sessions.stream.openFirewall is not implied by the stream.

`mcp.http.enable` also puts the binary on PATH, because `token mint` is
how the credential that unit demands gets issued.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KchcvnbfhhZhUHy83YL3Ya
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-11 20:40:37 +00:00
1 parent 242a2b9413
commit 9347e31705
1 file changed
+337 -11
+337 -11
View File
@@ -778,11 +778,22 @@ in {
#
# Its own top-level block rather than one under `sessions`, because it is
# not the broker's: four of its tools (`status`, `shot`, `record`, `run`)
# are frame-socket verbs that work with the broker switched off. It is also
# not a unit. The transport is stdio, one process per client, spawned by
# whichever client wants it -- so "installing" it means exactly putting the
# binary on PATH, and anything that started a daemon here would be
# inventing a second thing to supervise.
# are frame-socket verbs that work with the broker switched off.
#
# `mcp.enable` is still not a unit, and that is still the point: the stdio
# transport is one process per client, spawned by whichever client wants
# it, so "installing" it means exactly putting the binary on PATH.
#
# `mcp.http.enable` IS a unit, and it is the second thing to supervise that
# the comment here used to say was never worth inventing. What changed is
# not the cost of supervising it but what it buys: a port can be reached by
# a caller who never touched this filesystem, which is the first time an
# authorization token on this surface means anything at all. Over stdio the
# client spawns the server and already holds the broker's socket, so a
# token there guards a lock whose key is in the same pocket. The two
# options are therefore independent -- one is a binary on PATH for a local
# client, the other is a listener with a credential -- and neither implies
# the other.
mcp = {
enable = lib.mkOption {
type = lib.types.bool;
@@ -813,6 +824,151 @@ in {
are the same build.
'';
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/hhstream-mcp";
description = ''
Where `hhstream-mcp` keeps its authorization table — the SHA-256
digests of the bearer tokens {option}`mcp.http.enable` accepts, and
nothing else.
Deliberately **not** {option}`sessions.stateDir`. That directory is
`0700` owned by {option}`sessions.user` and holds `events.jsonl`, the
broker's audit trail; parking a token file in it would mean granting
this shim write access to the audit trail's directory for no reason.
The two also have different lifetimes: revoking every token should
not be able to touch a session record, and vice versa.
The file holds digests rather than tokens, so it is not itself a
credential — but it is the list of who may drive this desktop, and it
is created `0700`.
'';
};
http = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Serve the MCP surface over Streamable HTTP on
{option}`mcp.http.port`, as a system unit, authenticated by a
bearer token.
This is the one shape of this server where a credential means
something: the stdio transport is spawned by its client, so that
caller has already passed a filesystem permission check and holds
the broker's `0660` control socket either way. A port is reachable
by someone who did neither.
Mint a token with `hhstream-mcp token mint`, run as
{option}`sessions.user`, and give it to the client as an
`Authorization: Bearer …` header. **The unit refuses to start while
the table is empty**, because a listener that 401s every request is
almost always a forgotten mint; `--allow-no-tokens` is the escape
hatch for provisioning.
Not MCP's authorization specification, which is OAuth 2.1 plus
RFC 9728 metadata discovery. A client that can only *discover* an
authorization server will not connect; one that lets you set a
header will. See `docs/TODO/mcp-http-auth-is-not-oauth.md`.
'';
};
address = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = ''
The address to bind.
Loopback by default. Binding somewhere the LAN can reach means a
bearer token is the only thing between the network and a desktop
something can type into, over plain HTTP with no TLS — put a
reverse proxy in front if that is the intent.
`0.0.0.0` is accepted but then {option}`mcp.http.allowedHosts` must
be set: DNS-rebinding protection is on, the allowlist has no
implicit localhost, and the `Host` header a client will send cannot
be derived from a wildcard bind.
'';
};
port = lib.mkOption {
type = lib.types.port;
default = 9989;
description = ''
The port to bind. One past {option}`sessions.stream.port`'s default,
so a machine running both has no collision.
'';
};
path = lib.mkOption {
type = lib.types.str;
default = "/mcp";
description = "The path the endpoint is mounted at.";
};
allowedHosts = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
example = ["desk.lan:9989" "desk.lan:*"];
description = ''
`Host` header values to accept, for DNS-rebinding protection.
Empty, the server derives them from {option}`mcp.http.address` —
which covers the loopback default and fails for a wildcard bind,
where nothing can be derived. A trailing `:*` is a wildcard port.
'';
};
allowedOrigins = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = ''
`Origin` header values to accept. Nothing needs this unless a
browser is the client: a request with no `Origin` is allowed, and
any present one not named here is refused. A browser page is the
attacker in the DNS-rebinding story, not a user of this server.
'';
};
toolsets = lib.mkOption {
type = lib.types.nullOr (lib.types.listOf lib.types.str);
default = null;
example = ["frames" "sessions"];
description = ''
Families to offer as tools, process-wide: `frames`, `sessions`,
`pointer`, `keyboard`. `null` offers every tool.
A ceiling, not a grant: a token may carry its own narrower list
(`token mint --toolsets`), and a tool has to survive both. Resources
are not filtered by either.
'';
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Open {option}`mcp.http.port` in the firewall.
Off by default and not implied by {option}`mcp.http.enable`, the
same way {option}`sessions.stream.openFirewall` is not implied by
the stream: this port is a language model's path to starting
applications and typing on this desktop, and a bearer token over
plain HTTP is its only protection. Opening it is an explicit act.
'';
};
extraArgs = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
example = ["--stateless" "--allow-no-tokens"];
description = ''
Extra arguments for `hhstream-mcp serve --http`, appended last.
'';
};
};
};
};
@@ -826,6 +982,52 @@ in {
assertion = lib.hasPrefix "/" cfg.socketPath;
message = "services.hyprland-headless-stream.socketPath must be an absolute path.";
}
# The HTTP server is a unit, so it needs an account -- and the one it
# needs is the broker's, because its tools are the CLI's handlers and
# that CLI opens the broker's control socket and the compositor's runtime
# directory. `sessions.enable` is what declares that identity.
#
# An assertion and not a warning, unlike `mcp.enable` against the same
# condition: there, every session tool answers exit 5 and the frame tools
# still work, so it is a thing worth saying. Here the unit would fail to
# start at all, with `User=` naming an account that does not exist, and a
# listener that never comes up is not a degraded mode.
{
assertion = !cfg.mcp.http.enable || cfg.sessions.enable;
message = ''
services.hyprland-headless-stream.mcp.http.enable needs sessions.enable.
The HTTP transport runs as sessions.user with sessions.group, because
the tools it serves are the `hhstream` CLI's own handlers and that CLI
opens the broker's 0660 control socket and the compositor's runtime
directory. With sessions.enable off, that account is not declared and
the unit fails to start.
For a frame-only surface, use mcp.enable (stdio, no unit) instead.
'';
}
# `--address 0.0.0.0` and no allowedHosts is a server that 421s every
# request: DNS-rebinding protection is on, the allowlist has no implicit
# localhost, and the Host header a client will send cannot be derived
# from a wildcard bind. Caught here rather than at start-up, because a
# rebuild that produces a unit which refuses everything is worse than a
# rebuild that does not evaluate.
{
assertion =
!cfg.mcp.http.enable
|| !(builtins.elem cfg.mcp.http.address ["0.0.0.0" "::" "*"])
|| cfg.mcp.http.allowedHosts != [];
message = ''
services.hyprland-headless-stream.mcp.http.address is
"${cfg.mcp.http.address}", which binds every interface, so
mcp.http.allowedHosts must name the Host values to accept.
DNS-rebinding protection is on and its allowlist has no implicit
localhost, so an empty list refuses every request with a 421. Name the
hostnames clients will use (a trailing ":*" is a wildcard port), or
bind one address.
'';
}
# Structural, not cosmetic: see the `runtimeDirName` comment above. The
# ceiling exists so the compositor's *event* socket still fits in
# `sun_path`, and the symptom of breaking it is silent -- the request
@@ -912,17 +1114,44 @@ in {
services.hyprland-headless-stream.mcp.package =
lib.mkDefault (pkgs.callPackage ./mcp.nix { hhstream = cfg.package; });
# Installing it IS the whole of `mcp.enable`: the server is spawned by a
# client over stdio, so there is no unit, no socket and no state directory
# to declare.
environment.systemPackages = lib.mkIf cfg.mcp.enable [ cfg.mcp.package ];
# Installing it IS the whole of `mcp.enable`: the stdio server is spawned
# by a client, so that option declares no unit and no socket.
#
# `mcp.http.enable` also puts it on PATH, and not only because the unit
# needs it: `hhstream-mcp token mint` is how an operator issues the
# credential that unit demands, and a listener nobody can mint a token for
# is a listener that 401s for ever.
environment.systemPackages =
lib.mkIf (cfg.mcp.enable || cfg.mcp.http.enable) [ cfg.mcp.package ];
# 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) ''
warnings =
# Plain HTTP, no TLS, and one bearer token. Said out loud because the
# option that gets you here reads like a bind address and not like a
# decision about what is on the wire.
lib.optional
(cfg.mcp.http.enable && !(builtins.elem cfg.mcp.http.address ["127.0.0.1" "::1" "localhost"]))
''
services.hyprland-headless-stream.mcp.http.address is
"${cfg.mcp.http.address}", which is reachable beyond this machine.
There is no TLS here: the bearer token travels in a header in clear text,
and it authorizes starting applications, clicking and typing on this
desktop. Put a reverse proxy that terminates TLS in front of it, or keep
the bind on loopback and reach it through an SSH tunnel.
''
++ lib.optional (cfg.mcp.http.enable && cfg.mcp.http.openFirewall) ''
services.hyprland-headless-stream.mcp.http.openFirewall is on: port
${toString cfg.mcp.http.port} is open to the network, and a bearer token
is the only thing between it and a language model driving this desktop.
Mint tokens with an expiry (`hhstream-mcp token mint --expires-in 30d`)
and revoke them when a client is retired.
''
++ 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, and every
resource but hhstream://status and hhstream://screen, will fail because
@@ -964,6 +1193,22 @@ in {
mode = "0750";
};
})
# The MCP server's own state directory: the authorization table, and
# nothing else. A tmpfiles entry rather than `StateDirectory=` on the
# unit, for the reason the broker's is one -- `StateDirectory=` can only
# name a directory under /var/lib and would stop applying the moment
# `mcp.stateDir` is pointed anywhere else, whereas this is declarative
# for any path.
#
# `mcp.enable` alone does not create it. The stdio transport reads no
# tokens, so a directory for them would be a directory nothing opens.
(lib.mkIf cfg.mcp.http.enable {
"10-hhstream-mcp".${cfg.mcp.stateDir}.d = {
user = cfg.sessions.user;
group = cfg.sessions.group;
mode = "0700";
};
})
# Only needed when the socket was moved out of the runtime directory that
# `RuntimeDirectory=` already creates for us.
(lib.mkIf (socketDir != runtimeDir) {
@@ -984,7 +1229,8 @@ in {
# plan; this is the only part of the stream that a machine declares before
# any of that exists.
networking.firewall.allowedTCPPorts =
lib.optional cfg.sessions.stream.openFirewall cfg.sessions.stream.port;
lib.optional cfg.sessions.stream.openFirewall cfg.sessions.stream.port
++ lib.optional (cfg.mcp.http.enable && cfg.mcp.http.openFirewall) cfg.mcp.http.port;
users.users.${cfg.user} = {
isSystemUser = true;
@@ -1236,5 +1482,85 @@ in {
];
};
};
# ── the MCP server, over HTTP ──────────────────────────────────────
#
# The fourth unit, and the first one that listens on a port rather than a
# Unix socket. That is the whole reason it exists: `mcp.enable` puts a
# stdio binary on PATH and declares nothing, because a client spawns it and
# has already passed a filesystem permission check to do so. A port is
# reachable by a caller who has not, which is the first time the bearer
# token this unit demands means anything.
#
# It runs as the broker's user, with the broker's group, for the same
# reason the pointer driver does: its tools are the `hhstream` CLI's own
# handlers called in process, and that CLI talks to a `0660` control socket
# owned by that user and opens a compositor runtime directory owned by that
# group. Running it as anything else would mean a listener that
# authenticates a caller and then cannot do a thing for them.
systemd.services.hhstream-mcp = lib.mkIf cfg.mcp.http.enable {
description = "MCP server for the headless Hyprland desktop (HTTP)";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service" "hhstream-sessions.service"];
# `After` and `Wants`, not `BindsTo`: three of the twenty-one tools and
# two of the five resources are frame-socket verbs that answer with the
# broker down, and the rest answer exit 5, which is a true answer. A
# listener that vanished with the broker would turn that into a
# connection refused, which tells a client nothing.
wants = ["hhstream-sessions.service"];
environment = {
PYTHONUNBUFFERED = "1";
# The sockets are the CLI's own environment and there is no flag for
# them (`docs/CONTRACT-mcp.md` §2); this is the unit's half of that
# contract. The state directory is passed the same way rather than as
# `--state-dir`, so `hhstream-mcp token mint` run by an operator with
# this variable set and the unit agree by construction.
HHSTREAM_SOCKET = controlSocket;
HHSTREAM_FRAME_SOCKET = cfg.socketPath;
HHSTREAM_MCP_STATE_DIR = cfg.mcp.stateDir;
};
serviceConfig = {
Type = "simple";
User = cfg.sessions.user;
Group = cfg.sessions.group;
SupplementaryGroups = [cfg.sessions.group];
WorkingDirectory = cfg.mcp.stateDir;
UMask = "0077";
Restart = "on-failure";
RestartSec = 2;
NoNewPrivileges = true;
# This unit launches nothing and adopts nothing: it is a listener in
# front of a CLI, and every process it starts (`grim`, `ffmpeg`) is
# part of answering one request. So the systemd default is right here
# and `KillMode=process` -- which the broker and the driver both need
# -- would be wrong: stopping this unit should take its children with
# it. Sessions are the broker's and live in the broker's cgroup.
ExecStart = lib.escapeShellArgs (
[
(lib.getExe' cfg.mcp.package "hhstream-mcp")
"serve"
"--http"
"--address"
cfg.mcp.http.address
"--port"
(toString cfg.mcp.http.port)
"--path"
cfg.mcp.http.path
]
++ lib.optionals (cfg.mcp.http.toolsets != null) [
"--toolsets"
(lib.concatStringsSep "," cfg.mcp.http.toolsets)
]
++ lib.concatMap (host: ["--allowed-host" host]) cfg.mcp.http.allowedHosts
++ lib.concatMap (origin: ["--allowed-origin" origin]) cfg.mcp.http.allowedOrigins
++ cfg.mcp.http.extraArgs
);
};
};
};
}