Files
tasksd/tasksd.c
T
2026-11-06 17:59:15 +00:00

1023 lines
25 KiB
C

/* 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 <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#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);
}