Merge feat/mcp-server (9708154) into feat/mcp-auth
The base branch moved twelve commits while this work was in flight --
including the per-session live stream and its own contract bump -- so this
integrates rather than leaving a PR nobody can merge. Six files
conflicted; the interesting resolutions are the two that were not
textual.
**The contract is mcp-v3.1, not v2.1.** This branch bumped v2 -> v2.1 for
an additive change; `feat/mcp-server` bumped v2 -> v3 for the live stream,
also additive. Both point releases, both correct, and they cannot both be
the same document. So v3 stands as written and the HTTP transport is the
point release on top of it, by the same rule each of us applied
independently: v2 is still the only major bump, because it is still the
only one that removed anything.
**The counts are no longer literals.** This branch asserted `21 tools` and
`5 resources` in `checks/vm-mcp-http.nix` and `5` in `test_mcp_http.py`;
the stream added two tools and one fixed resource, so the surface is 23
and 6. Rather than re-hardcode numbers that will go stale again, the
check now counts against `--list-tools` and `--list-resources` -- the
server's own table -- and the unit test against `resources.FIXED`. That
is the lesson 9708154 ("count the unnarrowed resources against the
listing, not a literal") had already learned on the other side of this
merge, arrived at twice. A stale number here would have failed in a way
indistinguishable from the HTTP transport dropping tools, which is the
one thing those subtests exist to catch.
The rest were additive on both sides and both halves are kept: the TODO
table, the checks wiring, the README check rows, the architecture diagram
(their 23/10 counts with this branch's two-transport annotation).
`nix/module.nix` needed reconstructing -- git interleaved the bodies of
`hhstream-live` and `hhstream-mcp` because both units land between the
same surrounding lines -- so the live unit is taken verbatim and the MCP
unit placed after it, with this branch's options, tmpfiles entry,
firewall rule, two assertions and two warnings re-applied on top.
One thing deliberately NOT touched: the v3 change table cites `§6` for the
idle-clock exception, but the rule it means is `§8`. That is the other
branch's prose and its author's call, not something to quietly rewrite in
a merge.
Verified after resolution: 394 unit tests pass, and the module evaluates
with both units, the right ExecStart, one firewall port and both
warnings.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KchcvnbfhhZhUHy83YL3Ya
This commit is contained in:
commit
f83717ba71
37 files changed
+4241
-101
No files matched your search
Executable
+148
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""``hhs-mjpeg-read`` -- read a real MJPEG stream, and optionally keep watching.
|
||||
|
||||
What `checks/vm-stream.nix` uses as the *person with a phone*. Two jobs, and the
|
||||
second is the one that matters:
|
||||
|
||||
1. Read N frames off ``multipart/x-mixed-replace`` and report their sizes, so
|
||||
"the stream works" is a statement about bytes a client actually received
|
||||
rather than about a 200.
|
||||
2. **Hold the connection open** for a while afterwards. The broker counts
|
||||
connected viewers and treats one as activity, so proving that needs a viewer
|
||||
that is still there a minute later -- a client that read three frames and
|
||||
exited would make the sweep correct and untested.
|
||||
|
||||
Standard library only, and a hand-rolled multipart reader rather than anything
|
||||
that understands HTTP for us: the framing is this repository's own
|
||||
(`hhstream_live.server`), and a parser that shared code with it could not tell
|
||||
you the boundary was wrong.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
SOI = b"\xff\xd8"
|
||||
EOI = b"\xff\xd9"
|
||||
|
||||
|
||||
def connect(url: str, timeout: float) -> socket.socket:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
host = parsed.hostname or "127.0.0.1"
|
||||
port = parsed.port or 80
|
||||
path = parsed.path or "/"
|
||||
sock = socket.create_connection((host, port), timeout=timeout)
|
||||
request = (
|
||||
f"GET {path} HTTP/1.1\r\n"
|
||||
f"Host: {host}:{port}\r\n"
|
||||
"Accept: */*\r\n"
|
||||
"Connection: close\r\n\r\n"
|
||||
)
|
||||
sock.sendall(request.encode("ascii"))
|
||||
return sock
|
||||
|
||||
|
||||
def read_headers(sock: socket.socket) -> tuple[int, dict[str, str], bytes]:
|
||||
buffer = b""
|
||||
while b"\r\n\r\n" not in buffer:
|
||||
chunk = sock.recv(4096)
|
||||
if not chunk:
|
||||
raise SystemExit("the server closed the connection before any headers")
|
||||
buffer += chunk
|
||||
head, rest = buffer.split(b"\r\n\r\n", 1)
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
status = int(lines[0].split()[1])
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
if ":" in line:
|
||||
name, _, value = line.partition(":")
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
return status, headers, rest
|
||||
|
||||
|
||||
def frames(sock: socket.socket, rest: bytes, wanted: int, deadline: float) -> list[int]:
|
||||
"""Sizes of the JPEGs read off the multipart body, by SOI/EOI.
|
||||
|
||||
Framed on the markers rather than on ``Content-Length``: a stream that sent
|
||||
the right lengths and the wrong bytes would pass a length-based reader, and
|
||||
what the check is about is whether a browser would paint this.
|
||||
"""
|
||||
|
||||
sizes: list[int] = []
|
||||
buffer = rest
|
||||
while len(sizes) < wanted:
|
||||
if time.monotonic() > deadline:
|
||||
raise SystemExit(
|
||||
f"only {len(sizes)} of {wanted} frames arrived before the deadline"
|
||||
)
|
||||
start = buffer.find(SOI)
|
||||
end = buffer.find(EOI, start + 2) if start != -1 else -1
|
||||
if start != -1 and end != -1:
|
||||
sizes.append(end + 2 - start)
|
||||
buffer = buffer[end + 2 :]
|
||||
continue
|
||||
try:
|
||||
chunk = sock.recv(65536)
|
||||
except TimeoutError:
|
||||
raise SystemExit("the stream went quiet") from None
|
||||
if not chunk:
|
||||
raise SystemExit("the stream ended before enough frames arrived")
|
||||
buffer += chunk
|
||||
return sizes
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="hhs-mjpeg-read", description=__doc__)
|
||||
parser.add_argument("url", help="the stream.mjpg URL")
|
||||
parser.add_argument("--frames", type=int, default=2, help="how many to read")
|
||||
parser.add_argument(
|
||||
"--hold",
|
||||
type=float,
|
||||
default=0.0,
|
||||
metavar="SECONDS",
|
||||
help="keep the connection open this long after reading, so the broker "
|
||||
"counts a viewer for that whole time",
|
||||
)
|
||||
parser.add_argument("--timeout", type=float, default=30.0)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
sock = connect(args.url, args.timeout)
|
||||
sock.settimeout(args.timeout)
|
||||
try:
|
||||
status, headers, rest = read_headers(sock)
|
||||
content_type = headers.get("content-type", "")
|
||||
if status != 200:
|
||||
print(json.dumps({"status": status}), flush=True)
|
||||
raise SystemExit(f"the stream answered {status}, not 200")
|
||||
if "multipart/x-mixed-replace" not in content_type:
|
||||
raise SystemExit(f"content-type is {content_type!r}, not multipart")
|
||||
sizes = frames(sock, rest, args.frames, time.monotonic() + args.timeout)
|
||||
print(
|
||||
json.dumps(
|
||||
{"status": status, "content_type": content_type, "frames": sizes}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
if args.hold > 0:
|
||||
# Still connected, and still reading: a viewer that stopped reading
|
||||
# would have its socket buffer fill and the server would see it go.
|
||||
deadline = time.monotonic() + args.hold
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if not sock.recv(65536):
|
||||
break
|
||||
except TimeoutError:
|
||||
continue
|
||||
print(json.dumps({"held_for_s": args.hold}), flush=True)
|
||||
finally:
|
||||
sock.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user