commit 225f65e3bd106a8ea4ce7c4648a16087e22ac80a Author: Konrad Date: Fri Nov 6 17:59:15 2026 +0000 tasksd: initial import diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..774050f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.o +tasksd +*.bak +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a678671 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..44b887b --- /dev/null +++ b/Makefile @@ -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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..38ae4bb --- /dev/null +++ b/README.md @@ -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 +``` diff --git a/hermes-primed.py b/hermes-primed.py new file mode 100644 index 0000000..246d790 --- /dev/null +++ b/hermes-primed.py @@ -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()) diff --git a/tasks-mcp-bridge b/tasks-mcp-bridge new file mode 100644 index 0000000..63e2083 --- /dev/null +++ b/tasks-mcp-bridge @@ -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() diff --git a/tasksd.c b/tasksd.c new file mode 100644 index 0000000..e74e1e5 --- /dev/null +++ b/tasksd.c @@ -0,0 +1,1022 @@ +/* strdup/strndup are POSIX; ask before any header. */ +#define _POSIX_C_SOURCE 200809L + +/* + * tasksd - one central todo store, served over MCP. + * + * Two transports out of one binary: + * + * tasksd stdio, newline JSON-RPC (a local client) + * tasksd --http 8780 Streamable HTTP, so every host in the fleet can use + * the SAME store instead of each keeping its own + * + * Work is separated by a free-form `scope` string that the model chooses: + * "makronix", "fleet/console", "studio/mastering". A scope matches itself and + * anything below it, so task_next(scope="fleet") also picks "fleet/console" + * work. There is no list object: the scope IS the category. + * + * Storage is one JSON file per task under $TASKDIR (default ~/.hermes/tasks): + * + * t0001.json {"id","title","goal","scope","tags","state","priority", + * "created","started","ended","result"} + * + * States: pending -> running -> done + * ^ | + * | v + * paused dropped + */ +#define MCP_IMPLEMENTATION +#include "../libmcp/mcp.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_BODY (1 << 20) + +/* ------------------------------------------------------------------ paths */ + +static char *tasks_root(void) +{ + const char *env = getenv("TASKDIR"); + const char *home; + mcp_buf b; + + mcp_buf_init(&b); + if (env != NULL && *env != '\0') { + mcp_buf_puts(&b, env); + return b.p; + } + home = getenv("HOME"); + if (home == NULL) + home = "/tmp"; + mcp_buf_printf(&b, "%s/.hermes/tasks", home); + return b.p; +} + +static int is_dir(const char *p) +{ + struct stat st; + + return stat(p, &st) == 0 && S_ISDIR(st.st_mode); +} + +static int mkdir_p(const char *path) +{ + char tmp[PATH_MAX]; + size_t i, len; + + if (strlen(path) >= sizeof(tmp)) + return -1; + strcpy(tmp, path); + len = strlen(tmp); + for (i = 1; i < len; i++) { + if (tmp[i] != '/') + continue; + tmp[i] = '\0'; + if (!is_dir(tmp) && mkdir(tmp, 0755) != 0 && errno != EEXIST) + return -1; + tmp[i] = '/'; + } + if (!is_dir(tmp) && mkdir(tmp, 0755) != 0 && errno != EEXIST) + return -1; + return 0; +} + +static int valid_id(const char *s) +{ + const char *p; + + if (s == NULL || *s == '\0' || strlen(s) > 40) + return 0; + for (p = s; *p; p++) + if (!isalnum((unsigned char)*p) && *p != '-' && *p != '_') + return 0; + return 1; +} + +static char *task_path(const char *id) +{ + char *root = tasks_root(); + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s/%s.json", root, id); + free(root); + return b.p; +} + +static char *read_file(const char *path) +{ + FILE *f = fopen(path, "rb"); + mcp_buf b; + char tmp[4096]; + size_t n; + + if (f == NULL) + return NULL; + mcp_buf_init(&b); + while ((n = fread(tmp, 1, sizeof(tmp), f)) > 0) + mcp_buf_add(&b, tmp, n); + fclose(f); + if (b.p == NULL) + mcp_buf_add(&b, "", 0); + return b.p; +} + +static int write_file_atomic(const char *path, const char *data) +{ + mcp_buf tmp; + FILE *f; + int rc = 0; + size_t len = strlen(data); + + mcp_buf_init(&tmp); + mcp_buf_printf(&tmp, "%s.tmp.%d", path, (int)getpid()); + f = fopen(tmp.p, "wb"); + if (f == NULL) { + mcp_buf_free(&tmp); + return -1; + } + if (len > 0 && fwrite(data, 1, len, f) != len) + rc = -1; + if (fclose(f) != 0) + rc = -1; + if (rc == 0 && rename(tmp.p, path) != 0) + rc = -1; + if (rc != 0) + unlink(tmp.p); + mcp_buf_free(&tmp); + return rc; +} + +/* Claim the next free id atomically: whoever creates the file owns the number, + * which keeps two concurrent servers from handing out the same id. */ +static char *claim_id(void) +{ + char *root = tasks_root(); + int n; + + mkdir_p(root); + for (n = 1; n < 100000; n++) { + mcp_buf path; + int fd; + + mcp_buf_init(&path); + mcp_buf_printf(&path, "%s/t%04d.json", root, n); + fd = open(path.p, O_CREAT | O_EXCL | O_WRONLY, 0644); + mcp_buf_free(&path); + if (fd >= 0) { + char *out = malloc(16); + + close(fd); + if (out != NULL) + snprintf(out, 16, "t%04d", n); + free(root); + return out; + } + if (errno != EEXIST) { + free(root); + return NULL; + } + } + free(root); + return NULL; +} + +/* ------------------------------------------------------------------ task */ + +struct task { + char *id; + char *title; + char *goal; + char *scope; + char *tags; + char *state; + char *result; + int priority; + long created; + long started; + long ended; +}; + +static void free_task(struct task *t) +{ + free(t->id); + free(t->title); + free(t->goal); + free(t->scope); + free(t->tags); + free(t->state); + free(t->result); + memset(t, 0, sizeof(*t)); +} + +static const char *js(const mcp_json *v, const char *k) +{ + const char *s = mcp_arg_string(v, k); + + return s != NULL ? s : ""; +} + +static long jn(const mcp_json *v, const char *k) +{ + const mcp_json *x = mcp_arg(v, k); + + return (x != NULL && x->t == MCP_NUM) ? (long)x->n : 0; +} + +static int task_load(const char *id, struct task *out) +{ + char *p; + char *raw; + mcp_json *v; + + memset(out, 0, sizeof(*out)); + if (!valid_id(id)) + return -1; + p = task_path(id); + raw = read_file(p); + free(p); + if (raw == NULL) + return -1; + v = mcp_parse(raw); + free(raw); + if (v == NULL) + return -1; + out->id = strdup(id); + out->title = strdup(js(v, "title")); + out->goal = strdup(js(v, "goal")); + out->scope = strdup(js(v, "scope")); + out->tags = strdup(js(v, "tags")); + out->state = strdup(*js(v, "state") ? js(v, "state") : "pending"); + out->result = strdup(js(v, "result")); + out->priority = (int)jn(v, "priority"); + out->created = jn(v, "created"); + out->started = jn(v, "started"); + out->ended = jn(v, "ended"); + mcp_json_free(v); + if (out->id == NULL || out->title == NULL || out->goal == NULL || + out->scope == NULL || out->tags == NULL || out->state == NULL || + out->result == NULL) { + free_task(out); + return -1; + } + return 0; +} + +static void put_s(mcp_buf *b, const char *key, const char *val) +{ + mcp_buf_printf(b, "%s\"", key); + mcp_json_escape(b, val != NULL ? val : ""); + mcp_buf_puts(b, "\""); +} + +static int task_save(const struct task *t) +{ + char *p = task_path(t->id); + mcp_buf b; + int rc; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"id\":"); + put_s(&b, "", t->id); + mcp_buf_puts(&b, ", \"title\":"); + put_s(&b, "", t->title); + mcp_buf_puts(&b, ", \"goal\":"); + put_s(&b, "", t->goal); + mcp_buf_puts(&b, ", \"scope\":"); + put_s(&b, "", t->scope); + mcp_buf_puts(&b, ", \"tags\":"); + put_s(&b, "", t->tags); + mcp_buf_puts(&b, ", \"state\":"); + put_s(&b, "", t->state); + mcp_buf_puts(&b, ", \"result\":"); + put_s(&b, "", t->result); + mcp_buf_printf(&b, ", \"priority\": %d, \"created\": %ld, \"started\": %ld, \"ended\": %ld}\n", + t->priority, t->created, t->started, t->ended); + rc = write_file_atomic(p, b.p); + mcp_buf_free(&b); + free(p); + return rc; +} + +static void task_json(mcp_buf *b, const struct task *t) +{ + mcp_buf_puts(b, "{\"id\":"); + put_s(b, "", t->id); + mcp_buf_puts(b, ",\"title\":"); + put_s(b, "", t->title); + mcp_buf_puts(b, ",\"goal\":"); + put_s(b, "", t->goal); + mcp_buf_puts(b, ",\"scope\":"); + put_s(b, "", t->scope); + mcp_buf_puts(b, ",\"state\":"); + put_s(b, "", t->state); + mcp_buf_printf(b, ",\"priority\":%d,\"created\":%ld,\"started\":%ld,\"ended\":%ld", + t->priority, t->created, t->started, t->ended); + if (t->tags != NULL && *t->tags != '\0') { + mcp_buf_puts(b, ",\"tags\":"); + put_s(b, "", t->tags); + } + if (t->result != NULL && *t->result != '\0') { + mcp_buf_puts(b, ",\"result\":"); + put_s(b, "", t->result); + } + mcp_buf_puts(b, "}"); +} + +/* A scope matches itself and everything below it: "fleet" also selects + * "fleet/console". An empty filter matches everything. */ +static int scope_matches(const char *task_scope, const char *filter) +{ + size_t n; + + if (filter == NULL || *filter == '\0') + return 1; + if (task_scope == NULL || *task_scope == '\0') + return 0; + n = strlen(filter); + if (strncmp(task_scope, filter, n) != 0) + return 0; + return task_scope[n] == '\0' || task_scope[n] == '/'; +} + +static size_t scan_tasks(char ***outp) +{ + char *root = tasks_root(); + DIR *dp = opendir(root); + struct dirent *e; + char **ids = NULL; + size_t n = 0; + + *outp = NULL; + if (dp == NULL) { + free(root); + return 0; + } + while ((e = readdir(dp)) != NULL) { + size_t len = strlen(e->d_name); + char id[64]; + + if (len < 7 || e->d_name[0] != 't' || strcmp(e->d_name + len - 5, ".json") != 0) + continue; + if (len - 5 >= sizeof(id)) + continue; + memcpy(id, e->d_name, len - 5); + id[len - 5] = '\0'; + if (!valid_id(id)) + continue; + ids = realloc(ids, (n + 1) * sizeof(*ids)); + if (ids == NULL) + break; + ids[n] = malloc(strlen(id) + 1); + if (ids[n] == NULL) + break; + strcpy(ids[n], id); + n++; + } + closedir(dp); + free(root); + *outp = ids; + return n; +} + +static void free_ids(char **ids, size_t n) +{ + size_t i; + + if (ids == NULL) + return; + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); +} + +/* ------------------------------------------------------------------ replies */ + +static void say(mcp_conn *c, const char *fmt, ...) +{ + char tmp[512]; + mcp_buf b; + va_list ap; + int n; + + mcp_buf_init(&b); + va_start(ap, fmt); + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); + va_end(ap); + if (n > 0 && (size_t)n < sizeof(tmp)) + mcp_buf_puts(&b, tmp); + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); +} + +/* ------------------------------------------------------------------ tools */ + +static void t_create(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *title = mcp_arg_string(args, "title"); + const char *goal = mcp_arg_string(args, "goal"); + const char *scope = mcp_arg_string(args, "scope"); + const char *tags = mcp_arg_string(args, "tags"); + int prio = mcp_arg_int(args, "priority", 0); + struct task t; + char *id; + mcp_buf b; + + (void)user; + if (title == NULL || *title == '\0') { + mcp_reply_error(c, "a task needs a title"); + return; + } + if (goal == NULL || *goal == '\0') { + mcp_reply_error(c, "a task needs a goal: say why it exists, not only what to do"); + return; + } + if (scope == NULL || *scope == '\0') { + mcp_reply_error(c, "a task needs a scope, e.g. \"makronix\" or \"fleet/console\""); + return; + } + id = claim_id(); + if (id == NULL) { + mcp_reply_error(c, "cannot allocate a task id in the store"); + return; + } + memset(&t, 0, sizeof(t)); + t.id = id; + t.title = (char *)title; + t.goal = (char *)goal; + t.scope = (char *)scope; + t.tags = (char *)(tags ? tags : ""); + t.state = (char *)"pending"; + t.result = (char *)""; + t.priority = prio; + t.created = (long)time(NULL); + if (task_save(&t) != 0) { + mcp_reply_error(c, "cannot write the task file"); + free(id); + return; + } + mcp_buf_init(&b); + task_json(&b, &t); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(id); +} + +static void t_get(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *id = mcp_arg_string(args, "id"); + struct task t; + mcp_buf b; + + (void)user; + if (task_load(id, &t) != 0) { + mcp_reply_error(c, "no such task"); + return; + } + mcp_buf_init(&b); + task_json(&b, &t); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free_task(&t); +} + +static void t_next(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *scope = mcp_arg_string(args, "scope"); + char **ids = NULL; + size_t n, i; + struct task chosen; + int have = 0; + mcp_buf b; + + (void)user; + n = scan_tasks(&ids); + memset(&chosen, 0, sizeof(chosen)); + for (i = 0; i < n; i++) { + struct task t; + + if (task_load(ids[i], &t) != 0) + continue; + if (strcmp(t.state, "pending") != 0 || !scope_matches(t.scope, scope)) { + free_task(&t); + continue; + } + if (!have || t.priority > chosen.priority || + (t.priority == chosen.priority && t.created < chosen.created)) { + if (have) + free_task(&chosen); + chosen = t; + have = 1; + continue; + } + free_task(&t); + } + free_ids(ids, n); + + if (!have) { + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"task\":null,\"note\":\"nothing pending in this scope\"}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + return; + } + free(chosen.state); + chosen.state = strdup("running"); + chosen.started = (long)time(NULL); + task_save(&chosen); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"task\":"); + task_json(&b, &chosen); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free_task(&chosen); +} + +static void t_list(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *scope = mcp_arg_string(args, "scope"); + const char *want = mcp_arg_string(args, "state"); + int limit = mcp_arg_int(args, "limit", 50); + char **ids = NULL; + size_t n, i; + mcp_buf b; + int first = 1, shown = 0; + + (void)user; + if (limit <= 0 || limit > 500) + limit = 50; + n = scan_tasks(&ids); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"tasks\":["); + for (i = 0; i < n && shown < limit; i++) { + struct task t; + + if (task_load(ids[i], &t) != 0) + continue; + if (!scope_matches(t.scope, scope) || + (want != NULL && *want != '\0' && strcmp(t.state, want) != 0)) { + free_task(&t); + continue; + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + task_json(&b, &t); + shown++; + free_task(&t); + } + free_ids(ids, n); + mcp_buf_printf(&b, "],\"count\":%d}", shown); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +static void t_scopes(mcp_conn *c, const mcp_json *args, void *user) +{ + char **ids = NULL; + size_t n, i, s, nscopes = 0; + char **scopes = NULL; + mcp_buf b; + + (void)args; + (void)user; + n = scan_tasks(&ids); + for (i = 0; i < n; i++) { + struct task t; + size_t k; + int found = 0; + + if (task_load(ids[i], &t) != 0) + continue; + for (k = 0; k < nscopes; k++) + if (strcmp(scopes[k], t.scope) == 0) + found = 1; + if (!found) { + char **grown = realloc(scopes, (nscopes + 1) * sizeof(*scopes)); + + if (grown == NULL) { + free_task(&t); + break; + } + scopes = grown; + scopes[nscopes] = malloc(strlen(t.scope) + 1); + if (scopes[nscopes] != NULL) { + strcpy(scopes[nscopes], t.scope); + nscopes++; + } + } + free_task(&t); + } + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"scopes\":["); + for (s = 0; s < nscopes; s++) { + int pending = 0, running = 0, paused = 0, done = 0, dropped = 0; + + for (i = 0; i < n; i++) { + struct task t; + + if (task_load(ids[i], &t) != 0) + continue; + if (strcmp(t.scope, scopes[s]) == 0) { + if (strcmp(t.state, "pending") == 0) pending++; + else if (strcmp(t.state, "running") == 0) running++; + else if (strcmp(t.state, "paused") == 0) paused++; + else if (strcmp(t.state, "done") == 0) done++; + else if (strcmp(t.state, "dropped") == 0) dropped++; + } + free_task(&t); + } + if (s > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"scope\":"); + put_s(&b, "", scopes[s]); + mcp_buf_printf(&b, ",\"pending\":%d,\"running\":%d,\"paused\":%d," + "\"done\":%d,\"dropped\":%d}", pending, running, paused, done, dropped); + free(scopes[s]); + } + free(scopes); + free_ids(ids, n); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +static void set_state(mcp_conn *c, const mcp_json *args, const char *want, const char *note_field) +{ + const char *id = mcp_arg_string(args, "id"); + const char *note = mcp_arg_string(args, note_field); + struct task t; + mcp_buf b; + + if (task_load(id, &t) != 0) { + mcp_reply_error(c, "no such task"); + return; + } + free(t.state); + t.state = strdup(want); + if (strcmp(want, "running") == 0) { + t.started = (long)time(NULL); + t.ended = 0; + } + if (strcmp(want, "done") == 0 || strcmp(want, "dropped") == 0) + t.ended = (long)time(NULL); + if (note != NULL && *note != '\0') { + free(t.result); + t.result = strdup(note); + } + if (task_save(&t) != 0) { + mcp_reply_error(c, "cannot write the task file"); + free_task(&t); + return; + } + mcp_buf_init(&b); + task_json(&b, &t); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free_task(&t); +} + +static void t_pause(mcp_conn *c, const mcp_json *args, void *user) +{ + (void)user; + set_state(c, args, "paused", "note"); +} + +static void t_resume(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *id = mcp_arg_string(args, "id"); + struct task t; + + (void)user; + if (task_load(id, &t) != 0) { + mcp_reply_error(c, "no such task"); + return; + } + if (strcmp(t.state, "paused") != 0) { + say(c, "task %s is '%s', not paused - nothing to resume", id, t.state); + free_task(&t); + return; + } + free_task(&t); + set_state(c, args, "running", "note"); +} + +static void t_done(mcp_conn *c, const mcp_json *args, void *user) +{ + (void)user; + set_state(c, args, "done", "result"); +} + +static void t_drop(mcp_conn *c, const mcp_json *args, void *user) +{ + (void)user; + set_state(c, args, "dropped", "result"); +} + +/* ------------------------------------------------------------------ table */ + +static const mcp_tool TOOLS[] = { + { "task_create", + "Add a task to the central store. Every task needs three things: a title, a " + "GOAL (why it exists, one sentence, written for the agent who picks it up " + "later) and a SCOPE - a free string you choose that groups this work, e.g. " + "\"makronix\", \"fleet/console\", \"studio/mastering\". Reuse an existing " + "scope when the work belongs to it; invent a new one only for a new area. " + "Higher priority is claimed first.", + "{\"type\":\"object\",\"properties\":{" + "\"title\":{\"type\":\"string\",\"description\":\"what to do, one line\"}," + "\"goal\":{\"type\":\"string\",\"description\":\"why it exists - required\"}," + "\"scope\":{\"type\":\"string\",\"description\":\"category string, e.g. makronix or fleet/console\"}," + "\"priority\":{\"type\":\"integer\",\"description\":\"higher runs first, default 0\"}," + "\"tags\":{\"type\":\"string\",\"description\":\"extra keywords, comma separated\"}}," + "\"required\":[\"title\",\"goal\",\"scope\"]}", + t_create }, + { "task_next", + "Claim the next pending task in a scope and mark it running. Use this instead " + "of picking work by eye: it honours priority and never hands out a task " + "another agent already holds. A scope also selects its children, so " + "scope=\"fleet\" covers \"fleet/console\". Returns task null when nothing is " + "pending there - that means done, not broken. Call task_scopes first if you " + "do not know which scopes exist.", + "{\"type\":\"object\",\"properties\":{" + "\"scope\":{\"type\":\"string\",\"description\":\"empty or omitted matches every scope\"}}}", + t_next }, + { "task_scopes", + "Overview of every scope that has tasks, with counts of pending, running, " + "paused, done and dropped. Read this when you join work you have not done " + "before: it shows where things are waiting for an agent.", + "{\"type\":\"object\",\"properties\":{}}", + t_scopes }, + { "task_list", + "List tasks filtered by scope and, optionally, by state. Use it to see the " + "whole picture of one area, or to review what is paused.", + "{\"type\":\"object\",\"properties\":{" + "\"scope\":{\"type\":\"string\"}," + "\"state\":{\"type\":\"string\",\"description\":\"pending|running|paused|done|dropped\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"default 50\"}}}", + t_list }, + { "task_get", + "Read one task with its scope, goal, state, timestamps and result.", + "{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\"}}," + "\"required\":[\"id\"]}", + t_get }, + { "task_pause", + "Park a task you cannot finish now. It keeps its place, its scope and its " + "goal, and task_resume brings it back. Say in note what is left and why you " + "stopped - that note is all the next agent gets.", + "{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\"}," + "\"note\":{\"type\":\"string\",\"description\":\"why parked, and what is left\"}}," + "\"required\":[\"id\"]}", + t_pause }, + { "task_resume", + "Take a paused task back up: same id, running again. Refuses with the real " + "state in the reply if the task is not paused, so you learn where it stands.", + "{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\"},\"note\":{\"type\":\"string\"}}," + "\"required\":[\"id\"]}", + t_resume }, + { "task_done", + "Close a task as done and record what came out of it. The result is the " + "evidence: what changed, where, and how you know.", + "{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\"},\"result\":{\"type\":\"string\"}}," + "\"required\":[\"id\"]}", + t_done }, + { "task_drop", + "Close a task as dropped: it is not worth doing any more. Give the reason. " + "Prefer this over leaving it pending forever, and over deleting it.", + "{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\"},\"result\":{\"type\":\"string\"}}," + "\"required\":[\"id\"]}", + t_drop }, +}; + +/* ------------------------------------------------------------------ http */ + +/* strcasestr is a GNU extension, not POSIX: do it here. */ +static char *ci_strstr(const char *hay, const char *needle) +{ + size_t nl = strlen(needle); + const char *p; + + if (nl == 0) + return (char *)hay; + for (p = hay; *p; p++) { + size_t i; + + for (i = 0; i < nl; i++) { + if (p[i] == '\0' || + tolower((unsigned char)p[i]) != tolower((unsigned char)needle[i])) + break; + } + if (i == nl) + return (char *)p; + } + return NULL; +} + +static void http_reply(int fd, int code, const char *ctype, const char *body, + const char *session) +{ + mcp_buf out; + size_t len = body != NULL ? strlen(body) : 0; + size_t sent = 0; + + mcp_buf_init(&out); + mcp_buf_printf(&out, "HTTP/1.1 %d %s\r\n", code, + code == 200 ? "OK" : (code == 202 ? "Accepted" : "Method Not Allowed")); + if (ctype != NULL) + mcp_buf_printf(&out, "Content-Type: %s\r\n", ctype); + if (session != NULL) + mcp_buf_printf(&out, "Mcp-Session-Id: %s\r\n", session); + mcp_buf_printf(&out, "Content-Length: %lu\r\n", (unsigned long)len); + mcp_buf_puts(&out, "Connection: close\r\n\r\n"); + if (len > 0) + mcp_buf_add(&out, body, len); + while (sent < out.len) { + ssize_t w = write(fd, out.p + sent, out.len - sent); + + if (w <= 0) + break; + sent += (size_t)w; + } + mcp_buf_free(&out); +} + +static void serve_one(int fd, mcp_server *srv, const char *session) +{ + char buf[8192]; + mcp_buf head; + int header_done = 0; + long content_length = 0; + char *body = NULL; + char *reply; + + mcp_buf_init(&head); + for (;;) { + ssize_t r = read(fd, buf, sizeof(buf)); + + if (r <= 0) + break; + mcp_buf_add(&head, buf, (size_t)r); + { + char *sep = strstr(head.p, "\r\n\r\n"); + + if (sep != NULL) { + char *cl = ci_strstr(head.p, "Content-Length:"); + size_t header_len = (size_t)(sep + 4 - head.p); + size_t have = head.len > header_len ? head.len - header_len : 0; + + header_done = 1; + if (cl != NULL) + content_length = strtol(cl + 15, NULL, 10); + if (content_length < 0 || content_length > MAX_BODY) { + http_reply(fd, 405, "text/plain", "body too large\n", NULL); + mcp_buf_free(&head); + close(fd); + return; + } + body = calloc((size_t)content_length + 1, 1); + if (body == NULL) { + mcp_buf_free(&head); + close(fd); + return; + } + if (have > (size_t)content_length) + have = (size_t)content_length; + memcpy(body, head.p + header_len, have); + while (have < (size_t)content_length) { + ssize_t r2 = read(fd, body + have, (size_t)content_length - have); + + if (r2 <= 0) + break; + have += (size_t)r2; + } + body[have] = '\0'; + break; + } + } + if (head.len > MAX_BODY) + break; + } + + if (!header_done) { + http_reply(fd, 405, "text/plain", "want POST /mcp\n", NULL); + mcp_buf_free(&head); + close(fd); + return; + } + if (strncmp(head.p, "GET ", 4) == 0 || strncmp(head.p, "DELETE ", 7) == 0) { + /* the SSE stream is not offered: this server answers per request */ + http_reply(fd, 202, NULL, "", session); + free(body); + mcp_buf_free(&head); + close(fd); + return; + } + if (strncmp(head.p, "POST ", 5) != 0) { + http_reply(fd, 405, "text/plain", "only POST\n", NULL); + free(body); + mcp_buf_free(&head); + close(fd); + return; + } + + reply = mcp_handle(srv, body != NULL ? body : "{}"); + free(body); + if (reply == NULL) { + http_reply(fd, 202, NULL, "", session); /* notification: nothing to say */ + } else { + http_reply(fd, 200, "application/json", reply, session); + free(reply); + } + mcp_buf_free(&head); + close(fd); +} + +static int serve_http(mcp_server *srv, int port) +{ + int ls; + struct sockaddr_in addr; + int one = 1; + char session[40]; + + snprintf(session, sizeof(session), "%08x-%08x", + (unsigned)time(NULL), (unsigned)getpid()); + ls = socket(AF_INET, SOCK_STREAM, 0); + if (ls < 0) { + perror("socket"); + return 1; + } + setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_ANY); + addr.sin_port = htons((unsigned short)port); + if (bind(ls, (struct sockaddr *)&addr, sizeof(addr)) != 0) { + perror("bind"); + close(ls); + return 1; + } + if (listen(ls, 64) != 0) { + perror("listen"); + close(ls); + return 1; + } + /* fork per connection: without this every finished child stays a zombie */ + signal(SIGCHLD, SIG_IGN); + fprintf(stderr, "tasksd: http mcp on 0.0.0.0:%d (session %s)\n", port, session); + for (;;) { + int fd = accept(ls, NULL, NULL); + pid_t pid; + + if (fd < 0) + continue; + pid = fork(); + if (pid == 0) { + close(ls); + serve_one(fd, srv, session); + _exit(0); + } + if (pid > 0) + close(fd); + else + serve_one(fd, srv, session); + } +} + +int main(int argc, char **argv) +{ + mcp_server srv; + + srv.name = "tasksd"; + srv.version = "2.0.0"; + srv.tools = TOOLS; + srv.ntools = sizeof(TOOLS) / sizeof(TOOLS[0]); + srv.user = NULL; + + if (argc >= 3 && strcmp(argv[1], "--http") == 0) + return serve_http(&srv, atoi(argv[2])); + return mcp_serve_stdio(&srv); +} diff --git a/tests/run.py b/tests/run.py new file mode 100644 index 0000000..777cc9f --- /dev/null +++ b/tests/run.py @@ -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) diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..ca38e0f --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,2 @@ +#!/bin/sh +exec python3 "$(dirname "$0")/run.py"