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 <[email protected]>
This commit is contained in:
1 parent
7be931a712
commit
3909c35565
5 files changed
+324
-4
No files matched your search
+13
-2
@@ -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)
|
||||
|
||||
+155
-2
@@ -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
|
||||
Reference in new issue
Block a user