tasksd: initial import
This commit is contained in:
commit
225f65e3bd
9 files changed
+1358
No files matched your search
@@ -0,0 +1,4 @@
|
||||
*.o
|
||||
tasksd
|
||||
*.bak
|
||||
*.log
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Build context is the parent directory (src/): tasksd includes ../libmcp/mcp.h.
|
||||
FROM python:3.14-slim AS build
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends build-essential make \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /src
|
||||
COPY libmcp libmcp
|
||||
COPY tasksd tasksd
|
||||
RUN make -C tasksd
|
||||
|
||||
FROM python:3.14-slim
|
||||
|
||||
COPY --from=build /src/tasksd/tasksd /usr/local/bin/tasksd
|
||||
|
||||
ENV TASKDIR=/data
|
||||
|
||||
EXPOSE 8781
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||
CMD python3 -c "import socket;socket.create_connection(('127.0.0.1',8781),4)" || exit 1
|
||||
|
||||
ENTRYPOINT ["tasksd", "--http", "8781"]
|
||||
@@ -0,0 +1,21 @@
|
||||
CC ?= cc
|
||||
CFLAGS ?= -std=c99 -O2 -Wall -Wextra
|
||||
LIBDIR ?= ../libmcp
|
||||
PREFIX ?= /usr/local
|
||||
|
||||
all: tasksd
|
||||
|
||||
tasksd: tasksd.c $(LIBDIR)/mcp.h
|
||||
$(CC) $(CFLAGS) -I$(LIBDIR) -o $@ tasksd.c
|
||||
|
||||
test: tasksd
|
||||
./tests/run.sh
|
||||
|
||||
install: tasksd
|
||||
mkdir -p $(DESTDIR)$(PREFIX)/bin
|
||||
cp tasksd $(DESTDIR)$(PREFIX)/bin/
|
||||
|
||||
clean:
|
||||
rm -f tasksd
|
||||
|
||||
.PHONY: all test install clean
|
||||
@@ -0,0 +1,21 @@
|
||||
# tasksd
|
||||
|
||||
Central task store for the agent fleet, C99/POSIX.
|
||||
|
||||
Tasks are JSON files under `$TASKDIR` -- one file per task, readable and
|
||||
diffable, never a database. Every task carries a free-form `scope`, a
|
||||
mandatory goal, and can be paused and resumed.
|
||||
|
||||
One binary, two modes:
|
||||
|
||||
```sh
|
||||
tasksd # MCP over stdio
|
||||
tasksd --http :8781 # central instance for the fleet
|
||||
```
|
||||
|
||||
`tasks-mcp-bridge` is the stdio shim that forwards to a central `tasksd`.
|
||||
|
||||
```sh
|
||||
make
|
||||
make test
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Start the Hermes CLI, but load the MCP SDK first.
|
||||
|
||||
tools/mcp_tool._ensure_mcp_sdk() returns early as soon as ClientSession is set.
|
||||
The CLI sets that name during its own import, so by the time a transport runs
|
||||
the HTTP/stdio symbols were never computed and every MCP server - new or old -
|
||||
fails with "requires HTTP transport" or "SDK not installed". Calling the very
|
||||
same helper once, before the CLI is imported, lets it do its work.
|
||||
|
||||
A failure here must never block the CLI: prime, then hand over regardless.
|
||||
"""
|
||||
import sys
|
||||
|
||||
APP = "/home/stdio/kitt/app/hermes-agent"
|
||||
|
||||
if APP not in sys.path:
|
||||
sys.path.insert(0, APP)
|
||||
|
||||
try:
|
||||
import tools.mcp_tool as _mcp
|
||||
|
||||
_mcp._ensure_mcp_sdk()
|
||||
except Exception: # noqa: BLE001 - CLI must start
|
||||
pass
|
||||
|
||||
from hermes_cli.main import main # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""stdio <-> central tasksd bridge.
|
||||
|
||||
A client that only speaks stdio MCP gets the central store anyway: one
|
||||
JSON-RPC line in, one POST to the shared endpoint, one JSON line out. Used on
|
||||
hosts whose MCP client build cannot open a Streamable-HTTP transport.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
URL = os.environ.get("TASKSD_URL", "http://172.25.206.2:8781/mcp")
|
||||
|
||||
|
||||
def send(payload):
|
||||
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"})
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
raw = r.read()
|
||||
return raw
|
||||
|
||||
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
msg = json.loads(line)
|
||||
except Exception:
|
||||
sys.stdout.write('{"jsonrpc":"2.0","id":null,"error":{"code":-32700,'
|
||||
'"message":"parse error"}}\n')
|
||||
sys.stdout.flush()
|
||||
continue
|
||||
try:
|
||||
raw = send(msg)
|
||||
except Exception as e:
|
||||
if "id" not in msg: # notification: nothing to answer
|
||||
continue
|
||||
sys.stdout.write(json.dumps({
|
||||
"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32603,
|
||||
"message": "bridge: %s: %s" % (type(e).__name__, str(e)[:120])}}) + "\n")
|
||||
sys.stdout.flush()
|
||||
continue
|
||||
if not raw.strip():
|
||||
continue # notification: the server sent no body
|
||||
sys.stdout.write(raw.decode() if isinstance(raw, bytes) else raw)
|
||||
if not raw.endswith(b"\n"):
|
||||
sys.stdout.write("\n")
|
||||
sys.stdout.flush()
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
#!/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 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("nine tools", len(tools) == 9, 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"]) == 9)
|
||||
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)))
|
||||
|
||||
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)
|
||||
Executable
+2
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
exec python3 "$(dirname "$0")/run.py"
|
||||
Reference in new issue
Block a user