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

+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