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

+303
View File
@@ -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"]