From 4ff4f22ac1554eff1d15e4f3707eea13731e1463 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 21 Nov 2026 15:12:27 -0800 Subject: [PATCH] feat: read-only MCP server (wodify mcp) and list mine wodify mcp serves every CLI command over MCP stdio, stdlib-only. Tools run cli.main in-process, so the allowlist, write guard and SQLite cache are the CLI's by construction. list mine / the my_classes tool returns the account's reserved classes with roster and workout in one call, and says so plainly when none is reserved. Co-Authored-By: Claude Mythos 5.2 --- CLAUDE.md | 40 ++++- README.md | 30 ++++ src/wodify/cli.py | 7 + src/wodify/listcmd.py | 167 ++++++++++++++---- src/wodify/mcpserver.py | 375 ++++++++++++++++++++++++++++++++++++++++ tests/test_mcpserver.py | 303 ++++++++++++++++++++++++++++++++ 6 files changed, 886 insertions(+), 36 deletions(-) create mode 100644 src/wodify/mcpserver.py create mode 100644 tests/test_mcpserver.py diff --git a/CLAUDE.md b/CLAUDE.md index 48bfb66..e3cfa18 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -78,7 +78,8 @@ src/wodify/ store.py SQLite cache (sqlite3, stdlib) service.py cache-through data access -- all fetches go through here render.py compact text output (token-efficient, not a DOM dump) - listcmd.py the `list date` / `list workout` commands + listcmd.py the `list date` / `list workout` / `list mine` commands + mcpserver.py `wodify mcp` -- the same commands as a stdio MCP server (stdlib) cli.py python -m wodify ``` @@ -87,8 +88,14 @@ src/wodify/ ``` wodify list date 2026-07-25 # classes: time, coach, booked/max, title, duration, ID wodify list workout 190917816 # attendee names + the workout for that class +wodify list mine [2026-07-25] # the account's own classes that day, each with + # roster + workout; "No class reserved on …" if none ``` +`list mine` takes `--days N` (1-14) to look ahead. "Mine" is any class whose schedule +`Status` is non-empty: reserved, waitlist (printed as NOT a confirmed spot) or signed in. +No class is a normal answer and exits 0. + `list date` prints IDs; `list workout ` consumes one. Both accept `--refresh` (bypass cache), `--json`, and `list workout` also takes `--notes` for the coach's brief. @@ -96,6 +103,37 @@ A class ID resolves to nothing on its own — it is per-occurrence, and carries nor program. `list date` indexes the day's classes into SQLite, and `list workout` looks the ID up there. Querying an ID for a day never listed returns a message saying exactly that. +## MCP server + +`wodify mcp` serves the CLI over MCP's stdio transport (newline-delimited JSON-RPC). +It is **stdlib-only** -- no `mcp` SDK -- so it needs no install step, like the query path. + +Each tool builds an argv and calls `cli.main` in-process with stdout captured. That is +the whole design: there is no second code path, so the allowlist, the write guard, the +SQLite cache and the output wording are the CLI's by construction. Do not add a tool that +fetches on its own; add a CLI command and wrap it. + +| Tool | Runs | +|------|------| +| `my_classes` | `list mine` -- reserved class material in one call, incl. "none reserved" | +| `list_date`, `list_workout` | the `list` commands (cached) | +| one per `actions.keys()` | the generic action commands (live, as in the CLI) | +| `doctor`, `prime` | same | + +- Single-user: it answers as whoever `prime` captured. No account parameter exists. +- A non-zero CLI exit becomes `isError: true` with `[wodify exit N]` appended; the code is + from whichever exit table that command uses (see "Exit codes"). +- Every argument is validated (date regex, digits, real booleans) before it reaches an + argv, so a string can never be read as a flag. Unknown arguments are refused. +- `prime` is the one tool not annotated `readOnlyHint`: it rewrites the local session + cache. It still changes nothing in Wodify. It is exposed so an agent can heal STALE. +- While serving, `sys.stdout` is pointed at stderr -- stdout is the protocol channel and a + stray `print` would corrupt it. + +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. + ## SQLite cache `~/.cache/wodify/wodify.db` (override with `WODIFY_DB`), created mode 600 — it holds other diff --git a/README.md b/README.md index d59235a..3c4252d 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,13 @@ Then feed an ID back in for the workout and the named attendee list: wodify list workout 190918189 ``` +Your own classes for a day — roster and workout included — in one command: + +```bash +wodify list mine # today; "No class reserved on …" if there is none +wodify list mine 2026-07-25 --days 7 +``` + Other commands: ```bash @@ -71,6 +78,29 @@ A class ID carries neither its date nor its program — it is per-occurrence. `l indexes the day into SQLite; `list workout` resolves the ID from there. Ask for an ID on a day you never listed and it says so rather than guessing. +## MCP server + +```bash +wodify mcp +``` + +serves the same commands over MCP (stdio), stdlib-only, for one user: whoever is logged +in. Register it with any MCP client: + +```json +{"mcpServers": {"wodify": {"command": "wodify", "args": ["mcp"]}}} +``` + +| Tool | What it answers | +|------|-----------------| +| `my_classes` | your reserved classes with roster + workout, in one call; says so plainly when nothing is reserved | +| `list_date`, `list_workout` | a day's classes; one class's roster + workout | +| `bookings`, `schedule`, `workout`, `attendees`, `classdetail`, `coach`, `waitlist`, `wodflags` | the raw read-only actions | +| `doctor`, `prime` | status; re-capture the session after a Wodify redeploy | + +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. + ## Local SQLite cache `~/.cache/wodify/wodify.db` (override with `WODIFY_DB`), created mode `600` because it holds diff --git a/src/wodify/cli.py b/src/wodify/cli.py index ff3ff19..6871d1f 100644 --- a/src/wodify/cli.py +++ b/src/wodify/cli.py @@ -5,6 +5,8 @@ python -m wodify bookings python -m wodify workout --date 2026-07-25 --program 133059 python -m wodify attendees --class-id 192000647 + python -m wodify list mine # your reserved classes + their workouts + python -m wodify mcp # the same commands as an MCP server """ from __future__ import annotations @@ -139,6 +141,8 @@ 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") 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", @@ -177,6 +181,9 @@ def main(argv: list[str] | None = None) -> int: if args.command == "list": from . import listcmd return listcmd.dispatch(args) + if args.command == "mcp": + from . import mcpserver + return mcpserver.serve() if args.command == "doctor": return cmd_doctor(args) if args.command == "prime": diff --git a/src/wodify/listcmd.py b/src/wodify/listcmd.py index 175d849..96149d7 100644 --- a/src/wodify/listcmd.py +++ b/src/wodify/listcmd.py @@ -1,4 +1,5 @@ -"""The `list` command group: `list date ` and `list workout `. +"""The `list` command group: `list date `, `list workout ` and +`list mine [YYYY-MM-DD]`. Both go through :mod:`wodify.service`, so a repeat query on the same calendar day is served from SQLite and touches the network not at all. @@ -23,6 +24,45 @@ def _source_note(*results) -> str: return "(fetched from Wodify and cached)" +def _fail(exc: Exception) -> int: + """Print a session-layer failure and return the `list` exit code for it.""" + if isinstance(exc, client.SessionExpiredError): + print(f"SESSION EXPIRED: {exc}") + return 3 + if isinstance(exc, client.VersionStaleError): + print(f"STALE: {exc}\nRun: wodify prime") + return 4 + print(f"NOT PRIMED: {exc}") + return 5 + + +_SESSION_ERRORS = (client.SessionExpiredError, client.VersionStaleError, + client.NotPrimedError) + + +def _print_class(klass: dict, wod, att, *, notes: bool, status: str = "") -> None: + """One class: header, roster, workout. Shared by `list workout` and `list mine`.""" + mins = render.duration_minutes(klass.get("start", ""), klass.get("finish", "")) + head = f"{klass.get('name') or 'class'} — {klass['date']} " \ + f"{render._hhmm(klass.get('start', ''))}" + if mins: + head += f" ({mins}min)" + print(head) + if status: + line = f"You: {status.lower()}" + if status.strip().lower().startswith("waitlist"): + line += " — NOT a confirmed spot" + print(line) + if klass.get("coach"): + print(f"Coach: {klass['coach']}") + print(f"Program: {klass.get('program_id') or '-'} ID: {klass['class_id']}") + print() + print(render.attendee_block(att.data, booked=klass.get("booked"), + limit=klass.get("class_limit"))) + print() + print(render.workout(wod.data, notes=notes)) + + def cmd_date(args: argparse.Namespace) -> int: date = args.value or _dt.date.today().isoformat() try: @@ -34,15 +74,8 @@ def cmd_date(args: argparse.Namespace) -> int: conn = store.connect() try: rows, result = service.day_classes(conn, date, refresh=args.refresh) - except client.SessionExpiredError as exc: - print(f"SESSION EXPIRED: {exc}") - return 3 - except client.VersionStaleError as exc: - print(f"STALE: {exc}\nRun: wodify prime") - return 4 - except client.NotPrimedError as exc: - print(f"NOT PRIMED: {exc}") - return 5 + except _SESSION_ERRORS as exc: + return _fail(exc) finally: conn.close() @@ -76,15 +109,8 @@ def cmd_workout(args: argparse.Namespace) -> int: refresh=args.refresh) att = service.attendees(conn, class_id, klass.get("class_limit"), refresh=args.refresh) - except client.SessionExpiredError as exc: - print(f"SESSION EXPIRED: {exc}") - return 3 - except client.VersionStaleError as exc: - print(f"STALE: {exc}\nRun: wodify prime") - return 4 - except client.NotPrimedError as exc: - print(f"NOT PRIMED: {exc}") - return 5 + except _SESSION_ERRORS as exc: + return _fail(exc) finally: conn.close() @@ -93,25 +119,88 @@ def cmd_workout(args: argparse.Namespace) -> int: "attendees": att.data}, indent=1)) return 0 - mins = render.duration_minutes(klass.get("start", ""), klass.get("finish", "")) - head = f"{klass.get('name') or 'class'} — {klass['date']} " \ - f"{render._hhmm(klass.get('start', ''))}" - if mins: - head += f" ({mins}min)" - print(head) - if klass.get("coach"): - print(f"Coach: {klass['coach']}") - print(f"Program: {klass.get('program_id') or '-'} ID: {class_id}") - print() - print(render.attendee_block(att.data, booked=klass.get("booked"), - limit=klass.get("class_limit"))) - print() - print(render.workout(wod.data, notes=args.notes)) + _print_class(klass, wod, att, notes=args.notes) print() print(_source_note(wod, att)) return 0 +MINE_MAX_DAYS = 14 + + +def cmd_mine(args: argparse.Namespace) -> int: + """The account's own classes, with roster and workout, in one go. + + "Mine" is whatever the schedule's `Status` says about the logged-in account: + reserved, waitlisted, or signed in. A day with none is a normal answer, not + an error -- it exits 0 and says so. + """ + start_text = args.value or _dt.date.today().isoformat() + try: + start = _dt.date.fromisoformat(start_text) + except ValueError: + print(f"not a date: {start_text!r} (expected YYYY-MM-DD)") + return 2 + days = args.days + if not 1 <= days <= MINE_MAX_DAYS: + print(f"--days must be between 1 and {MINE_MAX_DAYS}, got {days}") + return 2 + last = start + _dt.timedelta(days=days - 1) + span = (f"on {start}" if days == 1 + else f"from {start} through {last} ({days} days)") + + found: list[tuple[dict, str, object, object]] = [] + results: list = [] + conn = store.connect() + try: + for offset in range(days): + date = (start + _dt.timedelta(days=offset)).isoformat() + rows, sched = service.day_classes(conn, date, refresh=args.refresh) + results.append(sched) + for row in rows: + status = str(row.get("status") or "").strip() + if not status: + continue + # day_classes just indexed it; read it back in the stored shape + # so this renders exactly like `list workout`. + klass = service.resolve_class(conn, row["class_id"]) + if klass is None: + continue + wod = service.workout(conn, klass["date"], klass["program_id"], + refresh=args.refresh) + att = service.attendees(conn, klass["class_id"], + klass.get("class_limit"), + refresh=args.refresh) + results += [wod, att] + found.append((klass, status, wod, att)) + except _SESSION_ERRORS as exc: + return _fail(exc) + finally: + conn.close() + + if args.json: + print(json.dumps({ + "from": start.isoformat(), "through": last.isoformat(), + "classes": [{"class": k, "status": s, "workout": w.data, + "attendees": a.data} for k, s, w, a in found], + }, indent=1)) + return 0 + + if not found: + print(f"No class reserved {span}.") + print(_source_note(*results)) + return 0 + + n = len(found) + print(f"{n} class{'es' if n != 1 else ''} of yours {span}.") + for klass, status, wod, att in found: + print("\n" + "=" * 60) + _print_class(klass, wod, att, notes=args.notes, status=status) + print() + print(_source_note(*results)) + return 0 + + def add_parser(sub) -> None: p = sub.add_parser("list", help="list a day's classes, or one class's workout") inner = p.add_subparsers(dest="what", required=True) @@ -119,19 +208,27 @@ def add_parser(sub) -> None: for name, help_text, metavar in ( ("date", "classes on a day (default: today)", "YYYY-MM-DD"), ("workout", "workout + attendees for one class id", "CLASS_ID"), + ("mine", "your own reserved classes, with workout + attendees " + "(default: today)", "YYYY-MM-DD"), ): q = inner.add_parser(name, help=help_text) - q.add_argument("value", nargs="?" if name == "date" else None, + q.add_argument("value", nargs=None if name == "workout" else "?", metavar=metavar) q.add_argument("--refresh", action="store_true", help="ignore the local cache and re-read from Wodify") q.add_argument("--json", action="store_true", help="raw JSON") - if name == "workout": + if name in ("workout", "mine"): q.add_argument("--notes", action="store_true", help="include the coach's brief (long)") + if name == "mine": + q.add_argument("--days", type=int, default=1, metavar="N", + help=f"look this many days ahead, starting at the " + f"date (1-{MINE_MAX_DAYS}, default 1)") def dispatch(args: argparse.Namespace) -> int: if args.what == "date": return cmd_date(args) + if args.what == "mine": + return cmd_mine(args) return cmd_workout(args) diff --git a/src/wodify/mcpserver.py b/src/wodify/mcpserver.py new file mode 100644 index 0000000..bbbd555 --- /dev/null +++ b/src/wodify/mcpserver.py @@ -0,0 +1,375 @@ +"""MCP server over stdio: `wodify mcp`. + +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 io +import json +import re +import sys +from typing import Any, Callable + +from . import __version__, actions +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." +) + + +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 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 diff --git a/tests/test_mcpserver.py b/tests/test_mcpserver.py new file mode 100644 index 0000000..09aaa65 --- /dev/null +++ b/tests/test_mcpserver.py @@ -0,0 +1,303 @@ +"""The MCP server: protocol, CLI parity, read-only-ness, and `my_classes`.""" +from __future__ import annotations + +import io +import json + +import pytest + +from wodify import actions, cli, mcpserver, service, store + + +@pytest.fixture() +def tools(): + return mcpserver.build_tools() + + +def rpc(tools, method, params=None, msg_id=1): + return mcpserver.handle( + {"jsonrpc": "2.0", "id": msg_id, "method": method, "params": params or {}}, + tools) + + +def call(tools, name, arguments=None): + return rpc(tools, "tools/call", {"name": name, "arguments": arguments or {}})["result"] + + +# -------------------------------------------------------------------- protocol + +def test_initialize_echoes_a_supported_version(tools): + res = rpc(tools, "initialize", {"protocolVersion": "2024-11-05"})["result"] + assert res["protocolVersion"] == "2024-11-05" + assert res["serverInfo"]["name"] == "wodify" + assert "tools" in res["capabilities"] + + +def test_initialize_falls_back_on_an_unknown_version(tools): + res = rpc(tools, "initialize", {"protocolVersion": "1999-01-01"})["result"] + assert res["protocolVersion"] == mcpserver.PROTOCOL_VERSIONS[0] + + +def test_notifications_get_no_reply(tools): + assert mcpserver.handle( + {"jsonrpc": "2.0", "method": "notifications/initialized"}, tools) is None + + +def test_unknown_method_is_an_error(tools): + assert rpc(tools, "resources/list")["error"]["code"] == -32601 + + +def test_tools_list_is_serializable_and_hides_internals(tools): + listed = rpc(tools, "tools/list")["result"]["tools"] + json.dumps(listed) + assert all(set(t) == {"name", "description", "inputSchema", "annotations"} + for t in listed) + + +def test_serve_speaks_newline_delimited_json(monkeypatch): + monkeypatch.setattr(mcpserver, "run_cli", lambda argv: (0, "ok " + " ".join(argv))) + stdin = io.StringIO("\n".join([ + json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}), + json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}), + "not json", + json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/call", + "params": {"name": "doctor", "arguments": {}}}), + ]) + "\n") + stdout = io.StringIO() + assert mcpserver.serve(stdin, stdout) == 0 + replies = [json.loads(line) for line in stdout.getvalue().splitlines()] + assert [r.get("id") for r in replies] == [1, None, 2] + assert replies[1]["error"]["code"] == -32700 + assert replies[2]["result"]["content"][0]["text"] == "ok doctor" + + +def test_tool_output_never_reaches_the_protocol_channel(monkeypatch): + """A tool that prints must not corrupt stdout, which carries JSON-RPC.""" + monkeypatch.setattr(cli, "main", lambda argv: print("printed by the cli") or 0) + stdin = io.StringIO(json.dumps( + {"jsonrpc": "2.0", "id": 7, "method": "tools/call", + "params": {"name": "doctor"}}) + "\n") + stdout = io.StringIO() + mcpserver.serve(stdin, stdout) + (line,) = stdout.getvalue().splitlines() + assert json.loads(line)["result"]["content"][0]["text"] == "printed by the cli" + + +# ------------------------------------------------------------------ CLI parity + +def test_every_cli_command_has_a_tool(tools): + """`mcp` itself is the only CLI command without an MCP tool.""" + commands = set(actions.keys()) | {"doctor", "prime"} + assert commands <= set(tools) + assert {"list_date", "list_workout", "my_classes"} <= set(tools) + + +def test_every_tool_builds_an_argv_the_cli_parser_accepts(tools): + samples = {"class_id": "190917816", "date": "2026-07-20", "days": 3, + "since": "2026-07-01", "until": "2026-07-31", + "workout_date": "2026-07-20", "program": 133059} + for name, tool in tools.items(): + args = {} + for prop, spec in tool["inputSchema"]["properties"].items(): + args[prop] = True if spec.get("type") == "boolean" else samples[prop] + argv = tool["_argv"](args) + cli.build_parser().parse_args(argv) # raises SystemExit if not + + +def test_tools_route_to_the_expected_argv(tools, monkeypatch): + seen = [] + monkeypatch.setattr(mcpserver, "run_cli", lambda argv: seen.append(argv) or (0, "x")) + call(tools, "my_classes") + call(tools, "my_classes", {"date": "2026-07-20", "days": 7, "refresh": True}) + call(tools, "list_workout", {"class_id": 190917816, "notes": True}) + call(tools, "bookings", {"since": "2026-07-18", "attended": True}) + assert seen == [ + ["list", "mine"], + ["list", "mine", "2026-07-20", "--days", "7", "--refresh"], + ["list", "workout", "190917816", "--notes"], + ["bookings", "--since", "2026-07-18", "--attended"], + ] + + +def test_nonzero_exit_is_reported_as_an_error(tools, monkeypatch): + monkeypatch.setattr(mcpserver, "run_cli", lambda argv: (4, "STALE: redeployed")) + res = call(tools, "list_date") + assert res["isError"] is True + assert "STALE" in res["content"][0]["text"] + assert "exit 4" in res["content"][0]["text"] + + +# ------------------------------------------------------------------- read-only + +@pytest.mark.parametrize("name,arguments", [ + ("list_date", {"date": "--refresh"}), + ("list_date", {"date": "2026-07-20; rm -rf"}), + ("list_workout", {"class_id": "--json"}), + ("list_workout", {}), + ("my_classes", {"days": "--notes"}), + ("my_classes", {"refresh": "yes"}), + ("workout", {"program": "1 --json"}), + ("doctor", {"anything": 1}), + ("reserve", {}), +]) +def test_bad_arguments_never_reach_the_cli(tools, monkeypatch, name, arguments): + monkeypatch.setattr(mcpserver, "run_cli", + lambda argv: pytest.fail(f"cli was run with {argv}")) + res = call(tools, name, arguments) + assert res["isError"] is True + assert res["content"][0]["text"].startswith("bad arguments") + + +def test_no_tool_name_looks_like_a_write(tools): + for name in tools: + if name in ("list_workout", "workout"): # 'work' is not 'book' + continue + for marker in ("reserve", "cancel", "signin", "checkin", "book", "pay", + "create", "update", "delete", "save"): + if name == "bookings" and marker == "book": + continue # the read-only history action + assert marker not in name.lower(), name + + +def test_only_prime_is_not_marked_read_only(tools): + not_ro = [n for n, t in tools.items() if not t["annotations"]["readOnlyHint"]] + assert not_ro == ["prime"] + assert all(t["annotations"]["destructiveHint"] is False for t in tools.values()) + + +def test_the_server_can_only_reach_allowlisted_actions(tools, monkeypatch, tmp_path): + """Whatever a tool is asked, the only wire calls are allowlisted keys.""" + monkeypatch.setenv("WODIFY_DB", str(tmp_path / "t.db")) + seen = [] + + def fake_call(key, overrides=None, **kw): + actions.get(key) # raises on anything not allowlisted + seen.append(key) + return {} + + monkeypatch.setattr(service.client, "call", fake_call) + monkeypatch.setattr(cli.client, "call", fake_call) + for name, tool in tools.items(): + if name in ("prime", "doctor"): + continue + call(tools, name, {"class_id": "1"} if "class_id" in + tool["inputSchema"].get("required", []) else {}) + assert seen and set(seen) <= set(actions.keys()) + + +# ------------------------------------------------------------------ my_classes + +def _schedule(*rows): + return {"Response": {"ResponseClassList": {"Class": {"List": list(rows)}}}} + + +def _class(cid, time, status="", program="133059"): + return {"Id": cid, "Name": f"CrossFit: {time}", "StartTime": f"{time}:00", + "EndTime": "18:30:00", "StartDate": "2026-07-20", "ProgramId": program, + "ClassLimit": 10, "ReservationCount": 3, "WaitlistCount": 0, + "Status": status, "Coaches": {"List": [{"Name": "Pat Doyle"}]}} + + +WORKOUT = {"Response": {"ResponseWOD": {"ResponseWorkout": { + "Id": "9", "Name": "Monday grinder", "Notes": "", + "WorkoutComponents": {"List": [ + {"Id": "1", "Name": "Metcon", "Comment": "", "IsSection": False, + "Description": "21-15-9 thrusters and pull-ups"}]}}}}} + +ATTENDEES = {"Response": {"ClassDetailAttendee": {"List": [ + {"Id": "5", "PersonName": "Robin Vance", "StatusInClass": "Reserved"}]}}} + + +@pytest.fixture() +def wire(tmp_path, monkeypatch): + """A fake Wodify: schedules by date, plus a log of what was asked.""" + monkeypatch.setenv("WODIFY_DB", str(tmp_path / "t.db")) + days: dict[str, dict] = {} + log: list[str] = [] + + def fake_call(key, overrides=None, **kw): + log.append(key) + if key == "schedule": + return days.get(overrides["FromDate"], _schedule()) + return WORKOUT if key == "workout" else ATTENDEES + + monkeypatch.setattr(service.client, "call", fake_call) + return days, log + + +def test_my_classes_returns_the_reserved_class_material_in_one_call(tools, wire): + days, log = wire + days["2026-07-20"] = _schedule(_class("11", "07:00"), + _class("22", "17:30", "Reserved")) + res = call(tools, "my_classes", {"date": "2026-07-20"}) + text = res["content"][0]["text"] + assert res["isError"] is False + assert "CrossFit: 17:30" in text and "CrossFit: 07:00" not in text + assert "You: reserved" in text + assert "Pat Doyle" in text and "Robin Vance" in text + assert "thrusters" in text + assert log == ["schedule", "workout", "attendees"] + + +def test_my_classes_with_nothing_reserved_says_so_and_is_not_an_error(tools, wire): + days, log = wire + days["2026-07-20"] = _schedule(_class("11", "07:00")) + res = call(tools, "my_classes", {"date": "2026-07-20"}) + assert res["isError"] is False + assert res["content"][0]["text"].startswith("No class reserved on 2026-07-20.") + assert log == ["schedule"], "no workout or roster fetch when nothing is booked" + + +def test_my_classes_on_a_day_with_no_classes_at_all(tools, wire): + res = call(tools, "my_classes", {"date": "2026-07-20"}) + assert res["isError"] is False + assert "No class reserved on 2026-07-20." in res["content"][0]["text"] + + +def test_my_classes_flags_a_waitlist_as_unconfirmed(tools, wire): + days, _ = wire + days["2026-07-20"] = _schedule(_class("22", "17:30", "Waitlist")) + text = call(tools, "my_classes", {"date": "2026-07-20"})["content"][0]["text"] + assert "You: waitlist — NOT a confirmed spot" in text + + +def test_my_classes_looks_ahead_over_days(tools, wire): + days, log = wire + days["2026-07-22"] = _schedule(_class("33", "17:30", "Reserved")) + text = call(tools, "my_classes", + {"date": "2026-07-20", "days": 3})["content"][0]["text"] + assert "from 2026-07-20 through 2026-07-22 (3 days)" in text + assert "1 class of yours" in text + assert log.count("schedule") == 3 + + log.clear() + text = call(tools, "my_classes", {"date": "2026-07-20", "days": 2})["content"][0]["text"] + assert text.startswith("No class reserved from 2026-07-20 through 2026-07-21") + + +def test_my_classes_is_served_from_cache_the_second_time(tools, wire): + days, log = wire + today = store.today() + days[today] = _schedule(_class("22", "17:30", "Reserved")) + call(tools, "my_classes") + log.clear() + text = call(tools, "my_classes")["content"][0]["text"] + assert log == [], "second call inside the TTL must not touch the network" + assert "from local cache" in text + + call(tools, "my_classes", {"refresh": True}) + assert log == ["schedule", "workout", "attendees"] + + +def test_my_classes_rejects_an_out_of_range_span(tools, wire): + res = call(tools, "my_classes", {"days": 99}) + assert res["isError"] is True and "--days must be between" in res["content"][0]["text"] + + +def test_my_classes_reports_a_stale_session(tools, wire, monkeypatch): + def boom(key, overrides=None, **kw): + raise service.client.VersionStaleError("redeployed") + monkeypatch.setattr(service.client, "call", boom) + 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"]