From 3909c355654c11cfaea2e86e3276050c08397b3b Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 21 Nov 2026 15:21:13 -0800 Subject: [PATCH] feat: token-protected HTTP transport for the MCP server wodify mcp --http HOST:PORT serves MCP streamable HTTP at /mcp, stdlib only. A bearer token of 32+ chars is mandatory and checked before the path; prime is not offered over HTTP; tool calls are serialized. Co-Authored-By: Claude Mythos 5.2 --- CLAUDE.md | 30 ++++++++ README.md | 11 +++ src/wodify/cli.py | 15 +++- src/wodify/mcpserver.py | 157 +++++++++++++++++++++++++++++++++++++++- tests/test_mcpserver.py | 115 +++++++++++++++++++++++++++++ 5 files changed, 324 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d2e350b..bb15b6e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -130,6 +130,36 @@ fetches on its own; add a CLI command and wrap it. - While serving, `sys.stdout` is pointed at stderr -- stdout is the protocol channel and a stray `print` would corrupt it. +### HTTP transport (public: `https://wodify.luci.ooo/mcp`) + +`wodify mcp --http HOST:PORT` serves the same handler over MCP streamable HTTP at `/mcp`: +stateless, JSON responses only (GET/DELETE answer 405 -- there is no SSE stream and no +session). Still stdlib (`http.server`). + +This is the one part of the project reachable from the internet, fronting a full Wodify +session and other members' names. Rules that must stay: + +- **A bearer token is mandatory.** `$WODIFY_MCP_TOKEN`, else `--token-file`, else + `~/.config/wodify/mcp-token`. No token, or one under 32 chars, and it refuses to start. + There is no flag to disable auth; do not add one. +- **Auth is checked before the path**, for every method, with `hmac.compare_digest`. An + unauthenticated caller gets 401 everywhere and cannot tell `/mcp` from `/`. +- **`prime` is not offered over HTTP** (it drives the host's browser) unless + `--allow-prime`. The stdio server keeps it. +- Tool calls run under a lock: `run_cli` redirects the process-wide stdout, so two + overlapping calls would swap output. +- Bodies over 1 MB are refused on the declared length, before reading. Logs carry the + request line and status only -- never headers, so never the token. + +Path on the wire: Cloudflare (proxied A record `wodify.luci.ooo`, kept current by +`home-ddns` on luhpe, which follows every A record holding the home IP -- no per-record +config) -> home router :443 -> Caddy on the NAS (`wodify.luci.ooo` block, `/mcp` only) +-> `10.233.33.15:8765` on luhpe (`wodify-mcp.service`, a systemd user unit; ufw admits +only the NAS, 10.233.33.13). The hop from Caddy to luhpe is plain HTTP on the LAN. + +To rotate the token: write a new one to `~/.config/wodify/mcp-token` (mode 600) and +`systemctl --user restart wodify-mcp`. + Registered with hermes on luhpe as the `wodify` server (`command: /home/lucio/.local/bin/wodify`, `args: [mcp]`). From another machine: `ssh luhpe .local/bin/wodify mcp` is a working stdio command. diff --git a/README.md b/README.md index 3c4252d..fa4c938 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,17 @@ in. Register it with any MCP client: | `bookings`, `schedule`, `workout`, `attendees`, `classdetail`, `coach`, `waitlist`, `wodflags` | the raw read-only actions | | `doctor`, `prime` | status; re-capture the session after a Wodify redeploy | +To reach it over the network, serve HTTP instead (MCP streamable HTTP at `/mcp`): + +```bash +umask 077; python3 -c 'import secrets; print(secrets.token_urlsafe(48))' > ~/.config/wodify/mcp-token +wodify mcp --http 127.0.0.1:8765 +``` + +A bearer token is mandatory — it will not start without one of at least 32 characters, and +every request without it gets `401`. `prime` is not offered over HTTP. Put TLS in front +of it (a reverse proxy); the server itself speaks plain HTTP. + Tools run the CLI in-process, so the read-only allowlist and write guard apply unchanged and the cache below is shared with the command line. diff --git a/src/wodify/cli.py b/src/wodify/cli.py index 6871d1f..5b740a4 100644 --- a/src/wodify/cli.py +++ b/src/wodify/cli.py @@ -141,8 +141,16 @@ def build_parser() -> argparse.ArgumentParser: listcmd.add_parser(sub) sub.add_parser("doctor", help="show config and cache status") - sub.add_parser("mcp", help="serve these commands as a read-only MCP server " - "on stdio") + mc = sub.add_parser("mcp", help="serve these commands as a read-only MCP " + "server (stdio, or HTTP with --http)") + mc.add_argument("--http", default=None, metavar="HOST:PORT", + help="serve MCP over HTTP at /mcp instead of stdio; always " + "requires a bearer token") + mc.add_argument("--token-file", default=None, metavar="PATH", + help="file holding the bearer token (default: " + "$WODIFY_MCP_TOKEN, else ~/.config/wodify/mcp-token)") + mc.add_argument("--allow-prime", action="store_true", + help="also offer the prime tool over HTTP (off by default)") pr = sub.add_parser("prime", help="capture session state from a logged-in browser (needs CDP)") pr.add_argument("--workout-date", default=None, metavar="YYYY-MM-DD", @@ -183,6 +191,9 @@ def main(argv: list[str] | None = None) -> int: return listcmd.dispatch(args) if args.command == "mcp": from . import mcpserver + if args.http: + return mcpserver.serve_http(args.http, args.token_file, + allow_prime=args.allow_prime) return mcpserver.serve() if args.command == "doctor": return cmd_doctor(args) diff --git a/src/wodify/mcpserver.py b/src/wodify/mcpserver.py index bbbd555..3f917ba 100644 --- a/src/wodify/mcpserver.py +++ b/src/wodify/mcpserver.py @@ -1,4 +1,4 @@ -"""MCP server over stdio: `wodify mcp`. +"""MCP server: `wodify mcp` (stdio) or `wodify mcp --http HOST:PORT`. Read-only, like everything else here. Each tool builds an argv and runs the same CLI entry point a shell would, so the MCP surface cannot drift from the @@ -14,10 +14,15 @@ account parameter anywhere. from __future__ import annotations import contextlib +import hmac +import http.server import io import json +import os +import pathlib import re import sys +import threading from typing import Any, Callable from . import __version__, actions @@ -39,6 +44,18 @@ INSTRUCTIONS = ( ) +INSTRUCTIONS_REMOTE = INSTRUCTIONS.replace( + "If a tool reports STALE or NOT PRIMED, run `prime` once and retry.", + "STALE or NOT PRIMED cannot be fixed from here: `prime` drives a browser on " + "the host and is not offered over HTTP. Report it.") + +#: Bearer tokens shorter than this are refused outright. The HTTP endpoint is +#: reachable from the internet and fronts a full Wodify session. +MIN_TOKEN_CHARS = 32 +MAX_BODY_BYTES = 1 << 20 +MCP_PATH = "/mcp" + + class BadArguments(ValueError): """A tool was called with arguments it cannot use.""" @@ -327,7 +344,7 @@ def handle(msg: Any, tools: dict[str, dict]) -> dict | None: else PROTOCOL_VERSIONS[0], "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "wodify", "version": __version__}, - "instructions": INSTRUCTIONS, + "instructions": INSTRUCTIONS if "prime" in tools else INSTRUCTIONS_REMOTE, }) if method == "ping": return ok({}) @@ -373,3 +390,139 @@ def serve(stdin=None, stdout=None) -> int: finally: sys.stdout = saved return 0 + + +# -------------------------------------------------------------------------- +# HTTP transport (MCP "streamable HTTP", stateless, JSON responses only) +# -------------------------------------------------------------------------- + +def default_token_path() -> pathlib.Path: + return pathlib.Path.home() / ".config" / "wodify" / "mcp-token" + + +def load_token(path: str | None = None) -> str: + """The bearer token: $WODIFY_MCP_TOKEN, else a file. Never a default. + + There is deliberately no way to serve HTTP without one -- the endpoint + answers as the logged-in member and returns other members' names. + """ + token = os.environ.get("WODIFY_MCP_TOKEN", "").strip() + source = "$WODIFY_MCP_TOKEN" + if not token: + file = pathlib.Path(path).expanduser() if path else default_token_path() + source = str(file) + try: + token = file.read_text(encoding="utf-8").strip() + except OSError as exc: + raise SystemExit(f"no MCP token: {exc}. Create one with:\n" + f" umask 077; python3 -c 'import secrets; " + f"print(secrets.token_urlsafe(48))' > {file}") from exc + if len(token) < MIN_TOKEN_CHARS: + raise SystemExit(f"MCP token from {source} is too short " + f"({len(token)} chars, need {MIN_TOKEN_CHARS}+)") + return token + + +def make_http_server(host: str, port: int, token: str, *, + allow_prime: bool = False) -> http.server.ThreadingHTTPServer: + if len(token) < MIN_TOKEN_CHARS: + raise ValueError(f"token must be at least {MIN_TOKEN_CHARS} chars") + tools = build_tools() + if not allow_prime: + # prime drives the host's browser. A remote caller has no business + # doing that; the stdio server on the host still offers it. + tools.pop("prime", None) + expected = ("Bearer " + token).encode() + # run_cli redirects the process-wide stdout, so tool calls must not overlap. + lock = threading.Lock() + + class Handler(http.server.BaseHTTPRequestHandler): + server_version = "wodify-mcp" + sys_version = "" + protocol_version = "HTTP/1.1" + timeout = 30 # a stalled client cannot pin a thread + + def _reply(self, status: int, payload: Any = None, **headers: str) -> None: + body = b"" if payload is None else json.dumps( + payload, ensure_ascii=False).encode() + self.send_response(status) + if body: + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + for name, value in headers.items(): + self.send_header(name.replace("_", "-"), value) + self.end_headers() + self.wfile.write(body) + + def _gate(self) -> bool: + """Auth first, for every path and method: an unauthenticated caller + learns nothing, not even which paths exist.""" + given = (self.headers.get("Authorization") or "").encode() + if not hmac.compare_digest(given, expected): + self.close_connection = True + self._reply(401, {"error": "unauthorized"}, + WWW_Authenticate='Bearer realm="wodify"') + return False + if self.path.split("?", 1)[0].rstrip("/") != MCP_PATH: + self._reply(404, {"error": "not found"}) + return False + return True + + def do_POST(self) -> None: # noqa: N802 - http.server's naming + if not self._gate(): + return + try: + length = int(self.headers.get("Content-Length") or "") + except ValueError: + self.close_connection = True + return self._reply(411, {"error": "Content-Length required"}) + if not 0 < length <= MAX_BODY_BYTES: + self.close_connection = True + return self._reply(413, {"error": "request too large"}) + try: + msg = json.loads(self.rfile.read(length)) + except (ValueError, UnicodeDecodeError): + return self._reply(400, {"jsonrpc": "2.0", "id": None, "error": { + "code": -32700, "message": "parse error"}}) + batch = msg if isinstance(msg, list) else [msg] + with lock: + replies = [r for r in (handle(m, tools) for m in batch) if r] + if not replies: + return self._reply(202) # notifications only + self._reply(200, replies if isinstance(msg, list) else replies[0]) + + def _no_stream(self) -> None: + # No server-initiated messages, so there is no SSE stream to open + # and no session to delete. The spec's answer for both is 405. + if self._gate(): + self._reply(405, {"error": "POST only"}, Allow="POST") + + do_GET = do_DELETE = do_PUT = do_PATCH = _no_stream # noqa: N815 + + def log_message(self, fmt: str, *args: Any) -> None: + # Request line and status only -- never headers, so never the token. + sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args)) + + server = http.server.ThreadingHTTPServer((host, port), Handler) + server.daemon_threads = True + return server + + +def serve_http(listen: str, token_file: str | None = None, *, + allow_prime: bool = False) -> int: + host, _, port = listen.rpartition(":") + if not host or not port.isdigit(): + raise SystemExit(f"--http wants HOST:PORT, got {listen!r}") + server = make_http_server(host, int(port), load_token(token_file), + allow_prime=allow_prime) + sys.stdout = sys.stderr # nothing here prints to a client + print(f"wodify mcp: serving http://{listen}{MCP_PATH} (bearer token required)", + file=sys.stderr, flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 diff --git a/tests/test_mcpserver.py b/tests/test_mcpserver.py index 09aaa65..6b6f255 100644 --- a/tests/test_mcpserver.py +++ b/tests/test_mcpserver.py @@ -301,3 +301,118 @@ def test_my_classes_reports_a_stale_session(tools, wire, monkeypatch): res = call(tools, "my_classes") assert res["isError"] is True assert "STALE" in res["content"][0]["text"] and "exit 4" in res["content"][0]["text"] + + +# ------------------------------------------------------------------------ HTTP + +TOKEN = "t" * 40 + + +@pytest.fixture() +def http(monkeypatch): + import threading + import urllib.error + import urllib.request + + monkeypatch.setattr(mcpserver, "run_cli", lambda argv: (0, "ran " + " ".join(argv))) + server = mcpserver.make_http_server("127.0.0.1", 0, TOKEN) + threading.Thread(target=server.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{server.server_address[1]}" + + def request(method="POST", path="/mcp", body=None, token=TOKEN, raw=None): + data = raw if raw is not None else ( + json.dumps(body).encode() if body is not None else None) + req = urllib.request.Request(base + path, data=data, method=method) + if token is not None: + req.add_header("Authorization", f"Bearer {token}") + try: + with urllib.request.urlopen(req, timeout=5) as res: + text = res.read().decode() + return res.status, json.loads(text) if text else None + except urllib.error.HTTPError as exc: + text = exc.read().decode() + return exc.code, json.loads(text) if text else None + + request.port = server.server_address[1] + yield request + server.shutdown() + server.server_close() + + +def _rpc(method, params=None, msg_id=1): + return {"jsonrpc": "2.0", "id": msg_id, "method": method, "params": params or {}} + + +@pytest.mark.parametrize("token", [None, "", "wrong" * 10, TOKEN[:-1], TOKEN + "x"]) +def test_http_refuses_anything_without_the_exact_token(http, token): + for method, path in (("POST", "/mcp"), ("GET", "/mcp"), ("GET", "/"), + ("POST", "/anything")): + status, body = http(method, path, _rpc("tools/list") if method == "POST" else None, + token=token) + assert status == 401, (method, path) + assert body == {"error": "unauthorized"} + + +def test_http_serves_mcp_with_the_token(http): + status, body = http(body=_rpc("initialize", {"protocolVersion": "2025-06-18"})) + assert status == 200 and body["result"]["serverInfo"]["name"] == "wodify" + + status, body = http(body={"jsonrpc": "2.0", "method": "notifications/initialized"}) + assert (status, body) == (202, None) + + status, body = http(body=_rpc("tools/call", {"name": "my_classes", "arguments": {}})) + assert status == 200 + assert body["result"]["content"][0]["text"] == "ran list mine" + + +def test_http_does_not_offer_prime(http): + _, body = http(body=_rpc("tools/list")) + names = [t["name"] for t in body["result"]["tools"]] + assert "prime" not in names and "my_classes" in names + _, body = http(body=_rpc("tools/call", {"name": "prime"})) + assert body["result"]["isError"] is True + _, body = http(body=_rpc("initialize")) + assert "not offered over HTTP" in body["result"]["instructions"] + + +def test_http_only_answers_post_on_the_mcp_path(http): + assert http("GET")[0] == 405 + assert http("DELETE")[0] == 405 + assert http("POST", "/other", _rpc("ping"))[0] == 404 + assert http("POST", "/mcp/", _rpc("ping"))[0] == 200 + + +def test_http_rejects_garbage_and_oversized_bodies(http): + status, body = http(raw=b"not json") + assert status == 400 and body["error"]["code"] == -32700 + + +def test_http_refuses_an_oversized_body_before_reading_it(http): + """Declared length alone is enough: the body is never read.""" + import socket + port = http.port + with socket.create_connection(("127.0.0.1", port), timeout=5) as sock: + sock.sendall((f"POST /mcp HTTP/1.1\r\nHost: x\r\n" + f"Authorization: Bearer {TOKEN}\r\n" + f"Content-Length: {mcpserver.MAX_BODY_BYTES + 1}\r\n\r\n").encode()) + assert sock.recv(64).startswith(b"HTTP/1.1 413") + + +def test_http_will_not_start_without_a_real_token(monkeypatch, tmp_path): + with pytest.raises(ValueError): + mcpserver.make_http_server("127.0.0.1", 0, "short") + + monkeypatch.delenv("WODIFY_MCP_TOKEN", raising=False) + with pytest.raises(SystemExit, match="no MCP token"): + mcpserver.load_token(str(tmp_path / "missing")) + + weak = tmp_path / "weak" + weak.write_text("hunter2\n") + with pytest.raises(SystemExit, match="too short"): + mcpserver.load_token(str(weak)) + + good = tmp_path / "good" + good.write_text(TOKEN + "\n") + assert mcpserver.load_token(str(good)) == TOKEN + monkeypatch.setenv("WODIFY_MCP_TOKEN", "e" * 40) + assert mcpserver.load_token(str(good)) == "e" * 40