Files
tasksd/tests/run.py
T
Hermes 5e28b21f47 libmcp: arguments that arrive as a string no longer mean "no filter"
Refresh the vendored header to libmcp 6d2fcb4. A client in the OpenAI
function-call shape sends arguments as a JSON string; until now every handler
saw no argument at all, so task_next(scope="splinter") claimed the
highest-priority task of the whole store - t0352, makronix/mcde, priority 630 -
because scope was invisible to it (2026-11-22, written up in that task).

The new test replays exactly that: two tasks, one at priority 900 in
makronix/mcde and one at 1 in splinter, then tools/call with
"arguments":"{\"scope\": \"splinter\"}". It must claim the splinter task.
tests/run.py 27 PASS, 0 FAIL; test-http.sh ok.
2026-11-23 08:13:53 +00:00

217 lines
9.6 KiB
Python

#!/usr/bin/env python3
"""tasksd: scope model, state machine, file storage, and the HTTP transport."""
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BIN = os.path.join(HERE, "tasksd")
ROOT = tempfile.mkdtemp(prefix="tasksd-test-")
fails = []
def check(name, cond, detail=""):
print(("PASS " if cond else "FAIL ") + name + ("" if cond else " " + str(detail)))
if not cond:
fails.append(name)
def run(msgs):
env = dict(os.environ)
env["TASKDIR"] = ROOT
proc = subprocess.run([BIN], input="\n".join(json.dumps(m) for m in msgs) + "\n",
capture_output=True, text=True, env=env, timeout=60)
return [json.loads(l) for l in proc.stdout.splitlines() if l.strip()]
def run_in(root, msgs):
env = dict(os.environ)
env["TASKDIR"] = root
proc = subprocess.run([BIN], input="\n".join(json.dumps(m) for m in msgs) + "\n",
capture_output=True, text=True, env=env, timeout=60)
return [json.loads(l) for l in proc.stdout.splitlines() if l.strip()]
def txt(r):
try:
return r["result"]["content"][0]["text"]
except Exception:
return ""
def call(i, tool, **args):
return {"jsonrpc": "2.0", "id": i, "method": "tools/call",
"params": {"name": tool, "arguments": args}}
res = run([
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
{"jsonrpc": "2.0", "method": "notifications/initialized"},
call(2, "task_create", title="no goal", scope="fleet"),
call(3, "task_create", title="no scope", goal="test the guard"),
call(4, "task_create", title="board columns", goal="Kanban must show the pipeline",
scope="fleet/board", priority=5),
call(5, "task_create", title="console widgets", goal="The fleet needs a live view",
scope="fleet/console", priority=1),
call(6, "task_create", title="kernel set", goal="Without kern.tgz nothing boots",
scope="makronix", priority=3),
call(7, "task_scopes"),
call(8, "task_next", scope="fleet"),
call(9, "task_pause", id="t0001", note="needs the lease logic first"),
call(10, "task_resume", id="t0001"),
call(11, "task_done", id="t0001", result="board view shipped"),
call(12, "task_next", scope="fleet"),
call(13, "task_next", scope="makronix"),
call(14, "task_list", scope="fleet"),
call(15, "task_get", id="t0003"),
call(16, "task_list", scope="fleet", state="done"),
])
by = {r.get("id"): r for r in res}
tools = by.get(1, {}).get("result", {}).get("tools", [])
check("ten tools", len(tools) == 10, len(tools))
check("create says the scope is free-form",
any(t["name"] == "task_create" and "free string you choose" in t["description"] for t in tools))
check("notification got no answer", len(res) == 16,
"%d answers for 16 requests + 1 notification" % len(res))
check("task without goal refused", by.get(2, {}).get("result", {}).get("isError") is True,
txt(by.get(2, {}))[:60])
check("task without scope refused", by.get(3, {}).get("result", {}).get("isError") is True,
txt(by.get(3, {}))[:60])
check("scope is stored on the task",
'"scope":"fleet/board"' in txt(by.get(4, {})).replace(" ", ""), txt(by.get(4, {}))[:100])
scopes = {s["scope"]: s for s in json.loads(txt(by.get(7, {})))["scopes"]}
check("overview lists three scopes", len(scopes) == 3, list(scopes))
check("nested scopes stay separate rows",
scopes.get("fleet/board", {}).get("pending") == 1 and
scopes.get("fleet/console", {}).get("pending") == 1, scopes)
first = json.loads(txt(by.get(8, {})))["task"]
check("scope filter is a prefix match", first.get("scope") == "fleet/board", first.get("scope"))
check("priority decides inside the scope", first.get("priority") == 5, first.get("priority"))
check("claimed task is running", first.get("state") == "running" and first.get("started"), first)
check("pause stores the note", "lease logic" in (json.loads(txt(by.get(9, {}))).get("result") or ""))
check("resume sets it running again", json.loads(txt(by.get(10, {}))).get("state") == "running")
done = json.loads(txt(by.get(11, {})))
check("done records the evidence",
done.get("state") == "done" and "shipped" in (done.get("result") or ""), done)
second = json.loads(txt(by.get(12, {})))["task"]
check("next skips the finished task and takes the other fleet task",
second.get("id") == "t0002", second.get("id"))
check("a different scope is independent",
json.loads(txt(by.get(13, {}))).get("task", {}).get("scope") == "makronix")
listed = json.loads(txt(by.get(14, {})))
check("list filters by scope prefix", listed["count"] == 2, listed["count"])
only_done = json.loads(txt(by.get(16, {})))
check("list filters by state", only_done["count"] == 1 and only_done["tasks"][0]["state"] == "done",
only_done)
files = sorted(f for f in os.listdir(ROOT) if f.endswith(".json"))
check("one flat file per task", files[:3] == ["t0001.json", "t0002.json", "t0003.json"], files)
on_disk = json.load(open(os.path.join(ROOT, "t0002.json")))
check("the scope lives in the file", on_disk.get("scope") == "fleet/console", on_disk.get("scope"))
check("the goal lives in the file",
on_disk.get("goal") == "The fleet needs a live view", on_disk.get("goal"))
check("no database anywhere",
not any(f.endswith((".db", ".sqlite", ".sqlite3")) for _, _, fs in os.walk(ROOT) for f in fs),
[f for _, _, fs in os.walk(ROOT) for f in fs])
# ---- HTTP transport ------------------------------------------------------
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
env = dict(os.environ)
env["TASKDIR"] = ROOT
proc = subprocess.Popen([BIN, "--http", str(port)], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
url = "http://127.0.0.1:%d/mcp" % port
def post(payload, session=None):
data = json.dumps(payload).encode()
req = urllib.request.Request(url, data=data, method="POST",
headers={"Content-Type": "application/json",
"Accept": "application/json, text/event-stream"})
if session:
req.add_header("Mcp-Session-Id", session)
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, r.headers.get("Mcp-Session-Id"), r.read()
ready = False
sess = None
body = b""
for _ in range(40):
try:
st, sess, body = post({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2024-11-05", "capabilities": {}}})
ready = True
break
except Exception:
time.sleep(0.1)
check("http: server answers initialize", ready)
if ready:
init = json.loads(body)
check("http: serverInfo is tasksd", init["result"]["serverInfo"]["name"] == "tasksd", init)
check("http: a session id comes back", bool(sess), sess)
st2, _, b2 = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, session=sess)
check("http: tools/list over http", st2 == 200 and len(json.loads(b2)["result"]["tools"]) == 10)
st3, _, b3 = post(call(3, "task_scopes"), session=sess)
scopes_http = json.loads(json.loads(b3)["result"]["content"][0]["text"])["scopes"]
check("http: the SAME store answers", len(scopes_http) == 3, scopes_http)
st4, _, _ = post({"jsonrpc": "2.0", "method": "notifications/initialized"}, session=sess)
check("http: notification is accepted without a body", st4 == 202, st4)
st5, _, b5 = post(call(5, "task_create", title="via http",
goal="prove the http transport writes", scope="fleet"), session=sess)
written = json.loads(json.loads(b5)["result"]["content"][0]["text"])
check("http: a write lands", written.get("title") == "via http" and written.get("scope") == "fleet",
written)
check("http: the write is in the same files",
os.path.isfile(os.path.join(ROOT, "t0004.json")), sorted(os.listdir(ROOT)))
# ---- arguments that arrive as a JSON string ------------------------------
# A client in the OpenAI/Anthropic function-call shape sends
# "arguments":"{\"scope\": \"fleet\"}" - a string, not an object. Until
# libmcp parsed that, every handler saw no argument at all and task_next with
# scope="splinter" handed out the highest-priority task of ANOTHER project
# (found 2026-11-22: t0352 makronix/mcde claimed by an agent that asked for
# scope="splinter"). Its own store, so the counts above stay predictable.
string_root = tempfile.mkdtemp(prefix="tasksd-string-")
string_run = run_in(string_root, [
{"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2024-11-05", "capabilities": {}}},
{"jsonrpc": "2.0", "method": "notifications/initialized"},
call(2, "task_create", title="big elsewhere", goal="other project",
scope="makronix/mcde", priority=900),
call(3, "task_create", title="mine", goal="this project", scope="splinter", priority=1),
# arguments as a string: the shape a proxy in the OpenAI format produces
{"jsonrpc": "2.0", "id": 4, "method": "tools/call",
"params": {"name": "task_next", "arguments": "{\"scope\": \"splinter\"}"}},
])
sby = {r.get("id"): r for r in string_run}
claimed = json.loads(txt(sby.get(4, {}))).get("task")
check("arguments sent as a string are still a scope filter",
claimed is not None and claimed.get("scope") == "splinter",
claimed if claimed is None else claimed.get("scope"))
shutil.rmtree(string_root, ignore_errors=True)
proc.terminate()
proc.wait(timeout=10)
shutil.rmtree(ROOT, ignore_errors=True)
print()
print("FAILURES: %d" % len(fails))
sys.exit(1 if fails else 0)