"""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 CLI: same allowlist, same write guard, same SQLite cache, same wording. stdlib only. MCP's stdio transport is newline-delimited JSON-RPC 2.0, which needs nothing a `json` import does not provide -- so the query path stays free of an install step, and this runs under any Python the CLI runs under. Single-user by design: it answers as whoever `prime` captured. There is no 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 from .accessjwt import InvalidToken from .listcmd import MINE_MAX_DAYS PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05") _DATE = re.compile(r"\d{4}-\d{2}-\d{2}\Z") INSTRUCTIONS = ( "Read-only view of the logged-in member's Wodify gym account. Nothing here " "can reserve, cancel, check in or log results. Start with `my_classes` for " "\"what am I doing today\"; use `list_date` then `list_workout` for any " "other class. Schedules and rosters are cached for an hour and workouts for " "the day -- every answer says whether it came from cache; pass refresh=true " "when a reservation may have just changed. If a tool reports STALE or NOT " "PRIMED, run `prime` once and retry. SESSION EXPIRED needs the human to log " "in to Wodify in the browser profile first." ) 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.""" # -------------------------------------------------------------------------- # argument helpers -- every value is validated before it reaches an argv, so a # string argument can never be read as a flag # -------------------------------------------------------------------------- def _date(args: dict, key: str) -> str | None: value = args.get(key) if value in (None, ""): return None if not isinstance(value, str) or not _DATE.match(value): raise BadArguments(f"{key} must be YYYY-MM-DD, got {value!r}") return value def _digits(args: dict, key: str, *, required: bool = False) -> str | None: value = args.get(key) if value in (None, ""): if required: raise BadArguments(f"{key} is required") return None text = str(value).strip() if isinstance(value, bool) or not text.isdigit(): raise BadArguments(f"{key} must be a number, got {value!r}") return text def _flag(args: dict, key: str) -> bool: value = args.get(key, False) if not isinstance(value, bool): raise BadArguments(f"{key} must be true or false, got {value!r}") return value def _flags(args: dict, *names: str) -> list[str]: return [f"--{n}" for n in names if _flag(args, n)] # -------------------------------------------------------------------------- # tools # -------------------------------------------------------------------------- _D = {"type": "string", "pattern": r"^\d{4}-\d{2}-\d{2}$"} _B = {"type": "boolean", "default": False} _REFRESH = {**_B, "description": "Bypass the local cache and re-read from Wodify."} _NOTES = {**_B, "description": "Include the coach's brief (several thousand " "characters; off by default)."} _JSON = {**_B, "description": "Raw JSON payload instead of compact text. Large."} _CLASS_ID = {"type": ["string", "integer"], "description": "Class id from list_date / my_classes / bookings. " "Per-occurrence: it changes every day."} def _argv_my_classes(a: dict) -> list[str]: argv = ["list", "mine"] if (d := _date(a, "date")): argv.append(d) if (n := _digits(a, "days")): argv += ["--days", n] return argv + _flags(a, "notes", "refresh", "json") def _argv_list_date(a: dict) -> list[str]: argv = ["list", "date"] if (d := _date(a, "date")): argv.append(d) return argv + _flags(a, "refresh", "json") def _argv_list_workout(a: dict) -> list[str]: return (["list", "workout", _digits(a, "class_id", required=True)] + _flags(a, "notes", "refresh", "json")) def _argv_doctor(a: dict) -> list[str]: return ["doctor"] def _argv_prime(a: dict) -> list[str]: argv = ["prime"] if (d := _date(a, "workout_date")): argv += ["--workout-date", d] return argv def _argv_action(key: str) -> Callable[[dict], list[str]]: def build(a: dict) -> list[str]: argv = [key] if (d := _date(a, "date")): argv += ["--date", d] if (c := _digits(a, "class_id")): argv += ["--class-id", c] if (p := _digits(a, "program")): argv += ["--program", p] if key == "bookings": for name in ("since", "until"): if (d := _date(a, name)): argv += [f"--{name}", d] argv += _flags(a, "attended") if key == "workout": argv += _flags(a, "notes") return argv + _flags(a, "json") return build def _action_schema(key: str) -> dict: props: dict[str, Any] = { "date": {**_D, "description": "Target date (default: today, where the " "action is date-scoped)."}, "class_id": _CLASS_ID, "program": {"type": ["string", "integer"], "description": "Program id."}, "json": _JSON, } if key == "bookings": props = { "since": {**_D, "description": "Only classes on/after this date."}, "until": {**_D, "description": "Only classes on/before this date."}, "attended": {**_B, "description": "Only classes actually attended."}, "json": _JSON, } if key == "workout": props["notes"] = _NOTES return {"type": "object", "properties": props, "additionalProperties": False} _ACTION_NOTES = { "bookings": " Always read live (never cached). Emits class_id per row.", "workout": " Read live; `list_workout` / `my_classes` are the cached route.", "schedule": " Read live; `list_date` is the cached route and prints a table.", "attendees": " Needs class_id. Read live; `list_workout` is the cached route.", "classdetail": " Needs class_id. Raw JSON.", "coach": " Needs class_id. Raw JSON.", "waitlist": " Needs class_id. Raw JSON.", "wodflags": " Raw JSON.", } def _tool(name: str, description: str, schema: dict, argv: Callable[[dict], list[str]], *, read_only: bool = True) -> dict: return { "name": name, "description": description, "inputSchema": schema, "annotations": {"readOnlyHint": read_only, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True}, "_argv": argv, } def _obj(props: dict, required: list[str] | None = None) -> dict: schema = {"type": "object", "properties": props, "additionalProperties": False} if required: schema["required"] = required return schema def build_tools() -> dict[str, dict]: tools = [ _tool( "my_classes", "The logged-in member's own classes with everything needed to show up: " "time, coach, who else is going, and the full workout -- in one call. " "Covers classes that are reserved, waitlisted (flagged: not a confirmed " "spot) or already signed in. Defaults to today; set `days` to look " "ahead. If nothing is reserved it says exactly that ('No class " "reserved ...') and is not an error.", _obj({ "date": {**_D, "description": "First day to check (default: today)."}, "days": {"type": "integer", "minimum": 1, "maximum": MINE_MAX_DAYS, "default": 1, "description": "How many days to cover, starting at `date`."}, "notes": _NOTES, "refresh": _REFRESH, "json": _JSON, }), _argv_my_classes, ), _tool( "list_date", "All classes on a day: time, coach, booked/limit, title, duration, the " "member's own status (YOU column) and the class ID. Run this before " "`list_workout` -- it is what makes a class ID resolvable.", _obj({"date": {**_D, "description": "Day to list (default: today)."}, "refresh": _REFRESH, "json": _JSON}), _argv_list_date, ), _tool( "list_workout", "One class by ID: attendee names plus the workout for that class. The " "ID must come from a `list_date` of that class's day.", _obj({"class_id": _CLASS_ID, "notes": _NOTES, "refresh": _REFRESH, "json": _JSON}, ["class_id"]), _argv_list_workout, ), ] for key in actions.keys(): tools.append(_tool( key, actions.ACTIONS[key].summary + "." + _ACTION_NOTES.get(key, ""), _action_schema(key), _argv_action(key))) tools += [ _tool("doctor", "Configuration, session and cache status. Prints sizes and " "versions only, never credentials.", _obj({}), _argv_doctor), _tool("prime", "Re-capture the session from the logged-in Chrome on this host. " "Run only after a tool reports STALE or NOT PRIMED. Reads from " "Wodify and rewrites the local session cache; changes nothing in " "the Wodify account. Takes up to a minute or two.", _obj({"workout_date": { **_D, "description": "A date that has a posted workout " "(default: today)."}}), _argv_prime, read_only=False), ] return {t["name"]: t for t in tools} # -------------------------------------------------------------------------- # running a tool # -------------------------------------------------------------------------- def run_cli(argv: list[str]) -> tuple[int, str]: """Run the CLI in-process, returning (exit code, everything it printed).""" from . import cli out = io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): try: code = cli.main(argv) except SystemExit as exc: # argparse rejecting an argument code = exc.code if isinstance(exc.code, int) else 2 except Exception as exc: # noqa: BLE001 - must not kill the server print(f"{type(exc).__name__}: {exc}") code = 1 return int(code or 0), out.getvalue().strip() def call_tool(tools: dict[str, dict], name: str, arguments: Any) -> dict: tool = tools.get(name) if tool is None: raise BadArguments(f"unknown tool {name!r}; known: {', '.join(tools)}") arguments = arguments or {} if not isinstance(arguments, dict): raise BadArguments("arguments must be an object") allowed = tool["inputSchema"]["properties"] extra = sorted(set(arguments) - set(allowed)) if extra: raise BadArguments(f"{name} does not take {', '.join(extra)}; " f"it takes: {', '.join(allowed) or 'nothing'}") code, text = run_cli(tool["_argv"](arguments)) if code != 0: text = f"{text}\n\n[wodify exit {code}]".strip() return {"content": [{"type": "text", "text": text or "(no output)"}], "isError": code != 0} # -------------------------------------------------------------------------- # JSON-RPC # -------------------------------------------------------------------------- def _public(tool: dict) -> dict: return {k: v for k, v in tool.items() if not k.startswith("_")} def handle(msg: Any, tools: dict[str, dict]) -> dict | None: """One JSON-RPC message in, one response out (None for notifications).""" if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0": return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request"}} method, msg_id = msg.get("method"), msg.get("id") if "id" not in msg: return None # notification: never answered if method is None: return None # a response to us; we send no requests def ok(result: dict) -> dict: return {"jsonrpc": "2.0", "id": msg_id, "result": result} def err(code: int, message: str) -> dict: return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}} params = msg.get("params") or {} if method == "initialize": wanted = params.get("protocolVersion") return ok({ "protocolVersion": wanted if wanted in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "wodify", "version": __version__}, "instructions": INSTRUCTIONS if "prime" in tools else INSTRUCTIONS_REMOTE, }) if method == "ping": return ok({}) if method == "tools/list": return ok({"tools": [_public(t) for t in tools.values()]}) if method == "tools/call": try: return ok(call_tool(tools, params.get("name"), params.get("arguments"))) except BadArguments as exc: return ok({"content": [{"type": "text", "text": f"bad arguments: {exc}"}], "isError": True}) return err(-32601, f"method not found: {method}") def serve(stdin=None, stdout=None) -> int: """Serve until stdin closes.""" stdin = stdin or sys.stdin stdout = stdout or sys.stdout # stdout is the protocol channel. Anything else that prints must not land # on it, so the process-wide stdout points at stderr for the duration. saved, sys.stdout = sys.stdout, sys.stderr tools = build_tools() try: for line in stdin: line = line.strip() if not line: continue try: msg = json.loads(line) except json.JSONDecodeError: replies = [{"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}] else: batch = msg if isinstance(msg, list) else [msg] replies = [r for r in (handle(m, tools) for m in batch) if r] if isinstance(msg, list) and replies: replies = [replies] # a batch is answered as one array for reply in replies: stdout.write(json.dumps(reply, ensure_ascii=False) + "\n") stdout.flush() except KeyboardInterrupt: pass 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, access=None) -> http.server.ThreadingHTTPServer: """``access`` is an optional ``accessjwt.AccessVerifier``. With it, a request is also accepted when it carries a valid Cloudflare Access assertion -- that is how OAuth clients arrive. The bearer token keeps working either way.""" 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() self.who = "token" allowed = hmac.compare_digest(given, expected) if not allowed and access is not None: try: claims = access.verify(self.headers.get("Cf-Access-Jwt-Assertion")) except InvalidToken as exc: self.who = f"access refused: {exc}" else: allowed = True self.who = "access:" + str( claims.get("email") or claims.get("common_name") or "?") if not allowed: 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] %s\n" % ( self.address_string(), getattr(self, "who", "-"), 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, access=None) -> 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, access=access) sys.stdout = sys.stderr # nothing here prints to a client how = "bearer token" + ( f" or Cloudflare Access ({access.issuer})" if access else "") print(f"wodify mcp: serving http://{listen}{MCP_PATH} ({how} required)", file=sys.stderr, flush=True) try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() return 0