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 <[email protected]>
This commit is contained in:
lucioandClaude Mythos 5.2 committed 2026-11-21 15:12:27 -08:00
1 parent a15efa0874
commit 4ff4f22ac1
6 files changed
+886 -36

No files matched your search

+7
View File
@@ -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":
+132 -35
View File
@@ -1,4 +1,5 @@
"""The `list` command group: `list date <YYYY-MM-DD>` and `list workout <id>`.
"""The `list` command group: `list date <YYYY-MM-DD>`, `list workout <id>` 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)
+375
View File
@@ -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