Files
hyprland-headless-stream-pl…/src/hhstream_mcp/server.py
T
HermenixandClaude Opus 5 f4485f7a63 feat(mcp)!: a second transport, and the token it exists for
`hhstream-mcp serve --http` serves the surface over Streamable HTTP behind
a bearer token, and `hhstream-mcp token mint|list|revoke|prune` issues
those tokens.  stdio stays the default and stays unauthenticated.

The two are one feature, because neither works alone.  A token checked by
a process the caller spawned is a lock whose key is in the same pocket:
over stdio the client starts the server and already holds the broker's
0660 control socket, which is why `mcp.enable`'s own option text says it
"grants no access the `hhstream` CLI does not already grant".  A port is
the first time the caller is someone who passed no filesystem check on
the way in, and that is the moment a credential starts meaning something.
So the transport arrives with the credential, and the contract's "stdio,
and only stdio" is rewritten rather than quietly broken.

The store (`authorizations.py`) keeps SHA-256 digests, not tokens:
nothing ever needs the secret back, so `authorizations.json` is not
itself a credential.  No salt and no KDF -- a token is 256 bits of
`secrets`, so there is no dictionary to attack and a work factor would
only slow the request path.  Expiry is wall clock, the one place in this
project where that is right: every broker deadline is CLOCK_BOOTTIME so
an idle window survives an NTP step, but "valid for thirty days" is a
calendar statement that has to outlive a reboot.  Every read-modify-write
takes a flock, because two processes write this file -- the server
stamping `last_used` and an operator running `token mint` -- and the
atomic replace alone prevents a torn read, not a lost update.

`--toolsets` on a token, not just at launch, because the flag is
per-process and one HTTP server has many callers: a per-process tool
budget stops being a per-caller one the moment the transport is shared.
The intersection applies, so a token cannot widen what the unit was
started with.  `server.build` takes a chooser instead of a fixed list to
make that possible; the stdio path passes none and closes over its
selection exactly as before.

Three things in the request path are deliberate.  `default_allowed_hosts`
exists because the SDK's DNS-rebinding check is allowlist-only with no
implicit localhost -- protection on with an empty list 421s *every*
request -- so the allowlist is derived from the bind address rather than
the protection being switched off to get a working default; a wildcard
bind derives nothing and is refused, which makes binding every interface
the case where the hostnames must be said out loud.  The grant travels in
the ASGI scope and not a contextvar, because in stateful mode the session
manager runs the handler in a task owned by its own lifespan and a
contextvar set in middleware would not be visible there.  And a refusal
is a 401 with an empty body that never echoes the token and never says
which of unknown, revoked or expired it was -- the discipline
`hhstream_live.server` already applies to a wrong phrase, with that app's
own RateLimiter reused rather than a second one grown.

This is 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.  Documented as a limit rather than hidden, beside the two the SDK
already imposes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KchcvnbfhhZhUHy83YL3Ya
2026-10-12 17:53:31 +00:00

703 lines
28 KiB
Python

"""The MCP wiring. The only module here that imports the SDK.
Transport is **stdio** and nothing else: one process per client, spawned by the
client, no port and no daemon. There is already a daemon in this system
(`hhstreamd`) and it owns all the state; a second long-lived process in front of
it would be a second place for a lease to be remembered.
The low-level :class:`mcp.server.Server` rather than FastMCP, for two reasons.
The schemas here are written by hand -- ``pointer_move``'s exclusive ``to``/``by``
pair, ``additionalProperties: false`` on every tool -- and deriving them from
Python type hints would mean writing the signatures that happen to produce them.
And ``shot`` returns image content beside its text, which is a content list, not
a return value.
**The transport does not stay on file descriptor 1**, and that is load-bearing
rather than tidy: the tools run the CLI's handlers *in this process*
(:mod:`hhstream_mcp.invoke`), those handlers ``print``, and ``record`` spawns an
``ffmpeg`` whose output the CLI does not capture. Any one of those writing on
fd 1 would put a line of prose in the middle of a JSON-RPC stream, which a
client reports as a parse failure with no hint of where it came from. So
:func:`claim_transport` takes a private duplicate of stdin and stdout before
anything else runs and then points fd 1 at the log and fd 0 at ``/dev/null``.
After that the protocol is on descriptors nothing else in the process knows
about, and a stray write is a log line.
"""
from __future__ import annotations
import argparse
import io
import logging
import os
import sys
from collections.abc import Callable
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 (
DEFAULT_HTTP_ADDRESS,
DEFAULT_HTTP_PATH,
DEFAULT_HTTP_PORT,
SERVER_NAME,
__version__,
authorizations,
resources,
tokencli,
tools,
)
from .invoke import Runner
log = logging.getLogger("hhstream.mcp")
#: Shown by a client that surfaces server instructions, and the one place the
#: whole surface can be introduced at once. The two rules are repeated on the
#: individual tools, because a per-tool description is what a client shows at
#: the point of use.
INSTRUCTIONS = """\
Drive this machine's headless Hyprland desktop: look at it, put applications on
it, and aim its one pointer and keyboard at them.
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.
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.
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 (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.
"""
def annotations_for(tool: tools.Tool) -> types.ToolAnnotations:
"""Hints, and only honest ones.
``readOnlyHint`` is set from the verb's own behaviour, which is why
``session_container`` does not get it: with a session id that verb runs
``container.reconcile`` and writes the record back. ``openWorldHint`` is
false throughout -- the world here is one desktop on one machine.
"""
return types.ToolAnnotations(
title=tool.title,
readOnlyHint=tool.read_only,
# Meaningful only when `readOnlyHint` is false, and then stated rather
# than left out: the spec's default for it is *true*, so omitting it
# would mark `session_touch` and `record` as possibly destructive.
destructiveHint=None if tool.read_only else tool.destructive,
openWorldHint=False,
)
def describe(tool: tools.Tool) -> types.Tool:
return types.Tool(
name=tool.name,
title=tool.title,
description=tool.description,
inputSchema=tool.schema,
annotations=annotations_for(tool),
)
def listing() -> list[types.Tool]:
return [describe(tool) for tool in tools.TOOLS]
def content_for(result: tools.Result) -> list[types.ContentBlock]:
blocks: list[types.ContentBlock] = [types.TextContent(type="text", text=result.text)]
if result.image is not None and result.media_type:
import base64
blocks.append(
types.ImageContent(
type="image",
data=base64.b64encode(result.image).decode("ascii"),
mimeType=result.media_type,
)
)
return blocks
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
preference: the SDK's own ``call_tool`` handler catches whatever this raises
and turns it into an ``isError`` result anyway, and for the CLI's refusals
it is the right channel regardless -- "another session holds the lease" is
something the calling agent has to read and act on, and a JSON-RPC error
reaches the client's log rather than the agent. So the error text is
written for the agent, including for the two cases that are not the CLI's
verdict at all: a tool name that does not exist, and this layer's own bug.
"""
# 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:
# Two things can have narrowed the offer and the agent cannot tell
# them apart from here, so both are named: `--toolsets` at launch,
# and -- on the HTTP transport -- the toolsets carried by the token
# the request presented. Neither is the agent's to change, which is
# why the remedy is "ask whoever runs this" and not a retry.
hint = (
f" {name!r} exists but is not offered to this caller: either "
"this server was started without its toolset (--toolsets), or "
"the authorization this request used does not carry it. "
"Neither is yours to change from here."
)
return types.CallToolResult(
content=[
types.TextContent(
type="text",
text=f"no such tool: {name!r}.{hint} This server exposes: {known}",
)
],
structuredContent={"ok": False, "error": "no_such_tool"},
isError=True,
)
try:
result = tool.invoke(runner, arguments)
except (OSError, ValueError, KeyError) as exc:
# `Runner.run` already turns a handler's own exception into exit 1 with
# its traceback, so what reaches here is this layer's own fault -- a
# schema and an argv builder that disagree about a field name. Reported
# to the agent rather than only logged, because an agent that is told
# nothing retries forever.
log.exception("tool %s failed", name)
result = tools.Result(
text=f"the {name} tool failed before the CLI was called: {exc!r}",
data={"ok": False, "error": "tool_failed"},
is_error=True,
)
return types.CallToolResult(
content=content_for(result),
structuredContent=result.data,
isError=result.is_error,
)
# ── 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,
*,
offered: Callable[[], tuple[tools.Tool, ...]] | None = None,
) -> Server:
"""The MCP server over the selected tools.
``offered`` is how the HTTP transport narrows the listing per *caller*: a
token can carry its own toolsets, and ``--toolsets`` is a launch-time flag
that stops being a per-caller budget the moment one process serves several
of them (:mod:`hhstream_mcp.http`). It is called on every ``tools/list``
and every ``tools/call``, so it must be cheap and must not block.
Omitted -- which is the stdio case -- the selection is fixed at build time
and the handlers close over it, exactly as before.
"""
server: Server = Server(
SERVER_NAME, version=__version__, instructions=INSTRUCTIONS
)
fixed = tools.selected(toolsets)
chooser: Callable[[], tuple[tools.Tool, ...]] = offered or (lambda: fixed)
@server.list_tools()
async def _list() -> list[types.Tool]:
return [describe(tool) for tool in chooser()]
@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.
@server.call_tool()
async def _call(name: str, arguments: dict[str, Any]) -> types.CallToolResult:
# The CLI call is blocking and can take seconds (`record`, a `start`
# with a readiness budget), so it goes to a worker thread: the event
# 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.
by_name = {tool.name: tool for tool in chooser()}
return await anyio.to_thread.run_sync(lambda: call(runner, name, arguments, by_name))
return server
def claim_transport() -> tuple[Any, Any]:
"""Take stdin and stdout for the protocol, then make fd 0 and 1 harmless.
Returns the pair of streams to hand to ``stdio_server``. After this call
the process's own ``sys.stdout`` writes to the log beside ``sys.stderr``,
and nothing that reads stdin can eat a request: both are the right answer
for a server whose tools run a CLI in-process.
"""
stdin = anyio.wrap_file(
io.TextIOWrapper(os.fdopen(os.dup(0), "rb"), encoding="utf-8", errors="replace")
)
stdout = anyio.wrap_file(
io.TextIOWrapper(os.fdopen(os.dup(1), "wb"), encoding="utf-8")
)
sys.stdout.flush()
# The literal descriptor 2, not `sys.stderr.fileno()`: what is wanted is
# "whatever the log is at the file-descriptor level", so that a grandchild
# which never heard of `sys` writes there too.
os.dup2(2, 1)
null = os.open(os.devnull, os.O_RDONLY)
try:
os.dup2(null, 0)
finally:
os.close(null)
return stdin, stdout
async def serve(server: Server, transport: tuple[Any, Any] | None = None) -> None:
stdin, stdout = transport if transport is not None else claim_transport()
async with stdio_server(stdin, stdout) as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options(NotificationOptions()),
)
def common_options() -> argparse.ArgumentParser:
"""The flags both ``hhstream-mcp`` and ``hhstream-mcp serve`` accept.
A parent parser, so ``--toolsets`` works on either side of the subcommand
and there is one help text for it. Every option here defaults to
``SUPPRESS``: argparse copies a subparser's namespace over the top-level
one, so a plain default on the subcommand copy would overwrite a value
given *before* the subcommand with ``None``. Suppressed, an option that was
not typed is simply absent, and callers read it with ``getattr``.
"""
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
"--toolsets",
metavar="NAMES",
default=argparse.SUPPRESS,
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.",
)
common.add_argument(
"--list-tools",
action="store_true",
default=argparse.SUPPRESS,
help="print the tool names and exit, without serving. Honours "
"--toolsets, so it is also how to see what a selection would offer.",
)
common.add_argument(
"--list-resources",
action="store_true",
default=argparse.SUPPRESS,
help="print the resource URIs and templates and exit, without serving.",
)
return common
def add_serve_parser(subparsers: Any, common: argparse.ArgumentParser) -> None:
"""``serve`` -- the transports. stdio unless ``--http`` says otherwise."""
serve_cmd = subparsers.add_parser(
"serve",
parents=[common],
help="serve the tools (stdio by default, --http for a port)",
description=(
"Serve the surface. With no flags this is the stdio transport and "
"is identical to running `hhstream-mcp` with no subcommand at all, "
"which is what an MCP client's `command` entry should keep doing."
),
)
http = serve_cmd.add_argument_group(
"http transport",
description=(
"Streamable HTTP instead of stdio, behind a bearer token minted by "
"`hhstream-mcp token mint`. Every request carries one or gets a "
"401. stdio stays unauthenticated on purpose: the client spawns it, "
"so the caller has already passed a filesystem permission check "
"and holds the broker's socket either way."
),
)
http.add_argument(
"--http",
action="store_true",
help="serve Streamable HTTP on --address:--port instead of stdio",
)
http.add_argument(
"--address",
default=DEFAULT_HTTP_ADDRESS,
metavar="HOST",
help="the address to bind (default: %(default)s). Loopback by default, "
"deliberately: reaching the LAN is a second decision and wants a "
"firewall rule to go with it.",
)
http.add_argument(
"--port",
type=int,
default=DEFAULT_HTTP_PORT,
help="the port to bind (default: %(default)s)",
)
http.add_argument(
"--path",
default=DEFAULT_HTTP_PATH,
help="the path the endpoint is mounted at (default: %(default)s)",
)
http.add_argument(
"--state-dir",
metavar="DIR",
help="where the authorization table lives. Defaults to "
"$HHSTREAM_MCP_STATE_DIR, then /var/lib/hhstream-mcp.",
)
http.add_argument(
"--allowed-host",
action="append",
default=[],
metavar="HOST",
help="a Host header to accept. Repeatable. DNS-rebinding protection is "
"on, so a host this does not name is refused by the transport before "
"the token is even looked at.",
)
http.add_argument(
"--allowed-origin",
action="append",
default=[],
metavar="ORIGIN",
help="an Origin header to accept. Repeatable. Nothing needs this unless "
"a browser is the client; a token in a page is a token in a page.",
)
http.add_argument(
"--stateless",
action="store_true",
help="handle every request on its own, with no session to pin. For a "
"deployment behind a load balancer that cannot keep a client on one "
"process.",
)
http.add_argument(
"--allow-no-tokens",
action="store_true",
help="start even though the authorization table is empty, which means "
"refusing every request until a token is minted. For provisioning the "
"unit before its first token exists; without it, an empty table is a "
"usage error, because it is almost always a forgotten `token mint`.",
)
http.add_argument(
"--json-response",
action="store_true",
help="answer with a single JSON body instead of an SSE stream",
)
def build_parser() -> argparse.ArgumentParser:
common = common_options()
parser = argparse.ArgumentParser(
prog="hhstream-mcp",
parents=[common],
description=(
"Serve the hhstream CLI as Model Context Protocol tools. The "
"default transport is stdio: spawned by an MCP client, speaking "
"JSON-RPC on stdin/stdout and logging to stderr. `serve --http` "
"binds a port instead and requires a bearer token; `token` mints "
"and revokes those."
),
epilog=(
"There is no --socket flag here, deliberately: the sockets are the "
"CLI's own environment -- $HHSTREAM_FRAME_SOCKET for the frame "
"socket and $HHSTREAM_SOCKET for the broker's control socket -- and "
"a second place to configure them is a second place for them to "
"disagree. Set them in the MCP client's `env` block."
),
)
# Not required: `hhstream-mcp` and `hhstream-mcp --toolsets=...` have to go
# on serving stdio exactly as they did before this file grew subcommands.
# An MCP client's `command` entry is a configuration someone else wrote.
subparsers = parser.add_subparsers(dest="command", metavar="COMMAND")
add_serve_parser(subparsers, common)
tokencli.add_parser(subparsers)
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:
parser = build_parser()
args = parser.parse_args(argv)
# stderr, never stdout: on the stdio transport stdout *is* the transport,
# and one stray print on it is a protocol error the client reports as a
# parse failure. The HTTP transport does not share that hazard, but the
# same binary serves both and one rule is easier to keep than two.
logging.basicConfig(
level=os.environ.get("HHSTREAM_MCP_LOG", "WARNING").upper(),
stream=sys.stderr,
format="%(levelname)s %(name)s: %(message)s",
)
if args.command == "token":
# Before anything claims the transport, which is the whole reason this
# returns here: `token mint` prints a secret on stdout.
token_parser = parser_for(parser, "token")
return tokencli.run(args, token_parser)
try:
toolsets = chosen_toolsets(getattr(args, "toolsets", None))
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 getattr(args, "list_tools", False):
for tool in offered:
print(f"{tool.name}\t{tool.title}")
return 0
if getattr(args, "list_resources", False):
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
if getattr(args, "http", False):
return serve_http(args, toolsets, parser)
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(), toolsets), transport)
return 0
def parser_for(parser: argparse.ArgumentParser, name: str) -> argparse.ArgumentParser:
"""The subparser called ``name``, for a handler that wants to print its help.
argparse keeps no public index of these, so it is dug out of the one
``_SubParsersAction`` this parser has. A miss returns the top-level parser:
a slightly wrong help text is a better failure than an AttributeError in
place of a usage message.
"""
for action in parser._actions: # noqa: SLF001 -- argparse has no public accessor
if isinstance(action, argparse._SubParsersAction): # noqa: SLF001
found = action.choices.get(name)
if found is not None:
return found
return parser # pragma: no cover
def serve_http(
args: argparse.Namespace,
toolsets: list[str] | None,
parser: argparse.ArgumentParser,
) -> int:
"""Run the HTTP transport. Refuses to start with nothing that can connect.
The empty-table check is the one piece of policy in this function, and it
is here rather than in :mod:`hhstream_mcp.http` because it is a *launch*
decision: a server bound to a port that every request will 401 is almost
always a missing `token mint`, and discovering that from the far side of an
HTTP client is far more work than reading one line on stderr. `--allow-no-
tokens` is the escape hatch for the one case where it is deliberate --
provisioning the unit before its first token exists.
"""
# Imported here: `starlette` and `uvicorn` are only needed by this path,
# and the stdio transport must not pay for them or fail on them.
from . import http as http_transport
store = authorizations.Store.at(getattr(args, "state_dir", None))
try:
grants = store.load()
except authorizations.StoreError as exc:
print(f"error: {exc}", file=sys.stderr)
return tokencli.EXIT_STORE
if not grants and not args.allow_no_tokens:
parser.error(
f"no tokens in {store.path}: every request would be refused. Mint "
"one with `hhstream-mcp token mint`, or pass --allow-no-tokens to "
"start anyway."
)
return tokencli.EXIT_USAGE # pragma: no cover -- parser.error exits
# The Host allowlist, which cannot be left empty: the SDK's DNS-rebinding
# check is allowlist-only with no implicit localhost, so an empty list
# refuses every request with a 421 (see `http.default_allowed_hosts`).
hosts = list(args.allowed_host) or http_transport.default_allowed_hosts(
args.address, args.port
)
if not hosts:
parser.error(
f"--address {args.address} binds every interface, so the Host "
"header a client will send cannot be derived and DNS-rebinding "
"protection has nothing to check against. Name the hostnames with "
"--allowed-host (repeatable), or bind one address."
)
return tokencli.EXIT_USAGE # pragma: no cover -- parser.error exits
log.info(
"serving %d tools and %d resources over http on %s:%d%s, %d token(s), "
"hosts %s",
len(tools.selected(toolsets)),
len(resources.ENTRIES),
args.address,
args.port,
args.path,
len(grants),
",".join(hosts),
)
http_transport.serve(
Runner(),
store,
address=args.address,
port=args.port,
path=args.path,
toolsets=toolsets,
allowed_hosts=hosts,
allowed_origins=args.allowed_origin,
stateless=args.stateless,
json_response=args.json_response,
)
return 0
if __name__ == "__main__": # pragma: no cover
raise SystemExit(main())