wodify mcp --http HOST:PORT serves MCP streamable HTTP at /mcp, stdlib only. A bearer token of 32+ chars is mandatory and checked before the path; prime is not offered over HTTP; tool calls are serialized. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
419 lines
16 KiB
Python
419 lines
16 KiB
Python
"""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"]
|
|
|
|
|
|
# ------------------------------------------------------------------------ HTTP
|
|
|
|
TOKEN = "t" * 40
|
|
|
|
|
|
@pytest.fixture()
|
|
def http(monkeypatch):
|
|
import threading
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
monkeypatch.setattr(mcpserver, "run_cli", lambda argv: (0, "ran " + " ".join(argv)))
|
|
server = mcpserver.make_http_server("127.0.0.1", 0, TOKEN)
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
base = f"http://127.0.0.1:{server.server_address[1]}"
|
|
|
|
def request(method="POST", path="/mcp", body=None, token=TOKEN, raw=None):
|
|
data = raw if raw is not None else (
|
|
json.dumps(body).encode() if body is not None else None)
|
|
req = urllib.request.Request(base + path, data=data, method=method)
|
|
if token is not None:
|
|
req.add_header("Authorization", f"Bearer {token}")
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=5) as res:
|
|
text = res.read().decode()
|
|
return res.status, json.loads(text) if text else None
|
|
except urllib.error.HTTPError as exc:
|
|
text = exc.read().decode()
|
|
return exc.code, json.loads(text) if text else None
|
|
|
|
request.port = server.server_address[1]
|
|
yield request
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
|
|
def _rpc(method, params=None, msg_id=1):
|
|
return {"jsonrpc": "2.0", "id": msg_id, "method": method, "params": params or {}}
|
|
|
|
|
|
@pytest.mark.parametrize("token", [None, "", "wrong" * 10, TOKEN[:-1], TOKEN + "x"])
|
|
def test_http_refuses_anything_without_the_exact_token(http, token):
|
|
for method, path in (("POST", "/mcp"), ("GET", "/mcp"), ("GET", "/"),
|
|
("POST", "/anything")):
|
|
status, body = http(method, path, _rpc("tools/list") if method == "POST" else None,
|
|
token=token)
|
|
assert status == 401, (method, path)
|
|
assert body == {"error": "unauthorized"}
|
|
|
|
|
|
def test_http_serves_mcp_with_the_token(http):
|
|
status, body = http(body=_rpc("initialize", {"protocolVersion": "2025-06-18"}))
|
|
assert status == 200 and body["result"]["serverInfo"]["name"] == "wodify"
|
|
|
|
status, body = http(body={"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
assert (status, body) == (202, None)
|
|
|
|
status, body = http(body=_rpc("tools/call", {"name": "my_classes", "arguments": {}}))
|
|
assert status == 200
|
|
assert body["result"]["content"][0]["text"] == "ran list mine"
|
|
|
|
|
|
def test_http_does_not_offer_prime(http):
|
|
_, body = http(body=_rpc("tools/list"))
|
|
names = [t["name"] for t in body["result"]["tools"]]
|
|
assert "prime" not in names and "my_classes" in names
|
|
_, body = http(body=_rpc("tools/call", {"name": "prime"}))
|
|
assert body["result"]["isError"] is True
|
|
_, body = http(body=_rpc("initialize"))
|
|
assert "not offered over HTTP" in body["result"]["instructions"]
|
|
|
|
|
|
def test_http_only_answers_post_on_the_mcp_path(http):
|
|
assert http("GET")[0] == 405
|
|
assert http("DELETE")[0] == 405
|
|
assert http("POST", "/other", _rpc("ping"))[0] == 404
|
|
assert http("POST", "/mcp/", _rpc("ping"))[0] == 200
|
|
|
|
|
|
def test_http_rejects_garbage_and_oversized_bodies(http):
|
|
status, body = http(raw=b"not json")
|
|
assert status == 400 and body["error"]["code"] == -32700
|
|
|
|
|
|
def test_http_refuses_an_oversized_body_before_reading_it(http):
|
|
"""Declared length alone is enough: the body is never read."""
|
|
import socket
|
|
port = http.port
|
|
with socket.create_connection(("127.0.0.1", port), timeout=5) as sock:
|
|
sock.sendall((f"POST /mcp HTTP/1.1\r\nHost: x\r\n"
|
|
f"Authorization: Bearer {TOKEN}\r\n"
|
|
f"Content-Length: {mcpserver.MAX_BODY_BYTES + 1}\r\n\r\n").encode())
|
|
assert sock.recv(64).startswith(b"HTTP/1.1 413")
|
|
|
|
|
|
def test_http_will_not_start_without_a_real_token(monkeypatch, tmp_path):
|
|
with pytest.raises(ValueError):
|
|
mcpserver.make_http_server("127.0.0.1", 0, "short")
|
|
|
|
monkeypatch.delenv("WODIFY_MCP_TOKEN", raising=False)
|
|
with pytest.raises(SystemExit, match="no MCP token"):
|
|
mcpserver.load_token(str(tmp_path / "missing"))
|
|
|
|
weak = tmp_path / "weak"
|
|
weak.write_text("hunter2\n")
|
|
with pytest.raises(SystemExit, match="too short"):
|
|
mcpserver.load_token(str(weak))
|
|
|
|
good = tmp_path / "good"
|
|
good.write_text(TOKEN + "\n")
|
|
assert mcpserver.load_token(str(good)) == TOKEN
|
|
monkeypatch.setenv("WODIFY_MCP_TOKEN", "e" * 40)
|
|
assert mcpserver.load_token(str(good)) == "e" * 40
|