commit 5108636d84611fb2dc6487b6da8840a3eab87fc3 Author: Hermes Agent Date: Sun Nov 8 16:53:05 2026 +0000 memoryd: Erinnerungen mit Bedeutungssuche, als MCP-Dienst wie tasksd und skilld Ein Fakt je Datei, ein Embedding je Fakt, Suche über Vektornähe statt Volltext. Sieben Werkzeuge: add, search, list, get, update, delete, scopes. Ablage sind JSON-Dateien unter $MEMORYDIR (Standard ~/.hermes/memories), lesbar und sicherbar ohne Datenbank; ein Scope wählt sich selbst und seine Kinder (van deckt van/technik), wie bei tasksd. Der Embedder ist OpenAI-kompatibel (EMBED_URL, Standard http://127.0.0.1:8091/v1/embeddings, EMBED_MODEL nomic-embed-text, 768 Dimensionen) — und ausdrücklich nicht nötig: antwortet er nicht, wird ohne Vektor gespeichert, das Werkzeug sagt es (WITHOUT embedding) und die Suche fällt auf Teilstrings zurück, ebenfalls benannt. Ein Speicher, der Bedeutung behauptet, wo er Buchstaben vergleicht, wäre schlimmer als einer, der es zugibt. Drei Fehler, die auf dem Weg dorthin Zeit gekostet haben und jetzt im Code stehen: popen kennt nur eine Richtung ("r+" ist undefiniert, die Schreibseite verschwindet) — der Rumpf geht über eine temporäre Datei an curl. Diese Datei liegt im Speicherverzeichnis, nicht in /tmp: die Einheit läuft mit ProtectSystem=strict, dort ist /tmp schreibgeschützt, und ein Embedder, der an mkstemp scheitert, sieht wie ein toter Embedder aus. Und die Bind-Adresse wird aus "--http host:port" übernommen, sonst hörte der Dienst trotz 127.0.0.1 in der Einheit auf allen Adressen. Tests: 16 Prüfungen gegen den laufenden Dienst (HTTP-Transport mit Sitzung), mit einem deterministischen Embedder-Stub — die Suite hängt nicht davon ab, ob hier gerade ein Modell geladen ist. Geprüft werden unter anderem: sieben Werkzeuge, Reihenfolge nach Nähe, Scope-Vererbung, Re-Embedding beim Ändern, der gespeicherte Vektor auf der Platte, das Verhalten ohne Embedder und dass eine gelöschte Erinnerung wirklich weg ist. Auf n95 installiert: memoryd.service auf 127.0.0.1:8795, MEMORYDIR=/var/lib/memoryd, in junction als MCP-Server eingetragen (27 Werkzeuge über :8090/mcp, memoryd__memory_search liefert über junction einen Treffer mit score 0.69). diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b619c6f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +memoryd +*.o diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..09b37ee --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +CC ?= cc +CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror +LIBDIR ?= vendor/libmcp +PREFIX ?= /usr/local + +all: memoryd + +memoryd: memoryd.c $(LIBDIR)/mcp.h + $(CC) $(CFLAGS) -I$(LIBDIR) -o $@ memoryd.c -lm + +test: memoryd + ./tests/run.sh + +install: memoryd + mkdir -p $(DESTDIR)$(PREFIX)/bin + cp memoryd $(DESTDIR)$(PREFIX)/bin/ + +clean: + rm -f memoryd + +.PHONY: all test install clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..8beab4c --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# memoryd + +What an agent remembered, searchable by meaning. + +One fact per file, one embedding per fact, and a search that answers "how was it with the +frost protection" with the note that says "coolant down to -25 °C" — even though the word +frost never appears in it. Served over MCP, like `tasksd` and `skilld`. + +```sh +memoryd # stdio, JSON-RPC per line +memoryd --http 8795 # Streamable HTTP, so every host uses the same store +``` + +## Storage + +One JSON file per memory under `$MEMORYDIR` (default `~/.hermes/memories`): + +```json +{ + "id": "m00001", + "scope": "van/technik", + "text": "Der Frostschutz steht auf -25 Grad, aufgefüllt wird G12+ blau.", + "tags": "kühlmittel", + "source": "konrad", + "model": "nomic-embed-text", + "created": 1794147600, + "embedding": [0.0428, 0.0418, ...] +} +``` + +Readable, diffable, backupable without a database. A `scope` is a free string and selects +itself plus its children, so `van` covers `van/technik` — the same rule as tasksd. + +## Tools + +| tool | what it is for | +|---|---| +| `memory_add` | store one fact: text (required), scope, tags, source | +| `memory_search` | meaning-based search with scores; scope and limit optional | +| `memory_list` | what exists in a scope, newest first | +| `memory_get` | one memory in full | +| `memory_update` | correct a fact (re-embeds the new text) | +| `memory_delete` | remove what is wrong or obsolete | +| `memory_scopes` | which scopes exist, how many memories each | + +## The embedder + +OpenAI-compatible `/v1/embeddings`, `EMBED_URL` (default +`http://127.0.0.1:8091/v1/embeddings`), `EMBED_MODEL` (default `nomic-embed-text`, 768 +dimensions). + +**It is not required to run.** If it does not answer, the memory is stored without a +vector and the tool says so (`WITHOUT embedding`); search then falls back to a +case-insensitive substring match and labels the result `substring match`. A store that +silently pretends to understand meaning is worse than one that admits it is matching +letters. + +## What does not belong here + +Secrets, keys, passwords, long transcripts. The text is the conclusion, not the raw +material — one paragraph that still makes sense to an agent who was not there. A store +that keeps everything makes every search worse. + +## Build and test + +```sh +make # C99 + POSIX, no dependency beyond libc, libm, and curl at runtime +make test # 16 checks against the running service (HTTP + stdio), stub embedder +sudo make install +``` + +The suite starts its own embedder stub with deterministic vectors, so it does not depend +on a model being loaded on this machine. diff --git a/memoryd.c b/memoryd.c new file mode 100644 index 0000000..a3179cc --- /dev/null +++ b/memoryd.c @@ -0,0 +1,1019 @@ +/* strdup/POSIX: das Makro muss vor dem ersten Header stehen. */ +#define _POSIX_C_SOURCE 200809L + +/* + * memoryd - was ein Agent sich gemerkt hat, mit Bedeutungssuche statt Volltext. + * + * Zwei Transporte aus einem Programm: + * + * memoryd stdio, JSON-RPC je Zeile + * memoryd --http 8795 Streamable HTTP, damit jeder Host der Flotte denselben + * Speicher benutzt statt eines eigenen + * + * Der Unterschied zu tasksd und skilld ist die Suche: jede Erinnerung wird beim + * Schreiben in einen Vektor umgerechnet (Embedding), und gesucht wird über die Nähe + * dieser Vektoren. "Wie war das noch mit dem Frostschutz" findet dann auch die Notiz, + * die "Kühlmittel bis -25 Grad" sagt und das Wort Frostschutz nie enthält. + * + * Ablage sind Dateien, eine je Erinnerung, unter $MEMORYDIR: + * + * m0001.json {"id","scope","text","tags","source","created","model","embedding":[..]} + * + * Was NICHT hier hineingehört: Geheimnisse, Zugangsdaten, lange Gesprächsprotokolle. + * Ein Speicher, der alles behält, macht jede Suche schlechter und jede Sicherung + * größer — der Text ist das Ergebnis, nicht der Rohstoff. + * + * Ohne Embedder läuft der Dienst weiter: dann wird ohne Vektor gespeichert und die + * Suche fällt auf Teilstrings zurück. Das steht in der Antwort, damit niemand glaubt, + * eine Bedeutungssuche gesehen zu haben, die keine war. + */ +#define MCP_IMPLEMENTATION +#include "../libmcp/mcp.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_TEXT 16384 +#define MAX_DIM 4096 + +/* ------------------------------------------------------------------ small io */ + +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 char *mem_root(void) +{ + const char *env = getenv("MEMORYDIR"); + 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/memories", home); + 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; +} + +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 *mem_path(const char *id) +{ + char *root = mem_root(); + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s/%s.json", root, id); + free(root); + return b.p; +} + +/* Wer die Datei anlegt, besitzt die Nummer — zwei Server vergeben nie dieselbe. */ +static char *claim_id(void) +{ + char *root = mem_root(); + int n; + + mkdir_p(root); + for (n = 1; n < 1000000; n++) { + mcp_buf path; + int fd; + + mcp_buf_init(&path); + mcp_buf_printf(&path, "%s/m%05d.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, "m%05d", n); + free(root); + return out; + } + if (errno != EEXIST) { + free(root); + return NULL; + } + } + free(root); + return NULL; +} + +/* ------------------------------------------------------------------ embedder */ + +/* Der Embedder ist ein OpenAI-kompatibler Dienst (/v1/embeddings). Er läuft hier auf + * demselben Rechner; steht er woanders, sagt es $EMBED_URL. */ +static const char *embed_url(void) +{ + const char *u = getenv("EMBED_URL"); + + return (u != NULL && *u != '\0') ? u : "http://127.0.0.1:8091/v1/embeddings"; +} + +static const char *embed_model(void) +{ + const char *m = getenv("EMBED_MODEL"); + + return (m != NULL && *m != '\0') ? m : "nomic-embed-text"; +} + +/* Rumpf bauen, an curl geben, Antwort lesen. + * + * popen kann nur eine Richtung (POSIX kennt nur "r" und "w", "r+" ist undefiniert) — + * deshalb geht der Rumpf über eine temporäre Datei an curl statt über eine Pipe. Das + * ist der Unterschied zwischen "der Embedder antwortet nicht" und einem popen, das + * seine eigene Schreibseite verschluckt. */ +static int embed_fetch(const char *text, double **out_vec, int *out_dim) +{ + mcp_buf body, cmd; + /* Die temporäre Datei liegt im Speicherverzeichnis, nicht in /tmp: die Einheit + * läuft mit ProtectSystem=strict, dort ist /tmp schreibgeschützt — und ein + * Embedder, der an mkstemp scheitert, sieht wie ein toter Embedder aus. */ + char tmpname[PATH_MAX]; + char *root = mem_root(); + int fd; + FILE *f = NULL; + char chunk[4096]; + size_t got; + mcp_json *v = NULL, *data, *first, *emb; + size_t n, i; + double *vec; + int dim; + + *out_vec = NULL; + *out_dim = 0; + + mcp_buf_init(&body); + mcp_buf_puts(&body, "{\"model\":\""); + mcp_json_escape(&body, embed_model()); + mcp_buf_puts(&body, "\",\"input\":\""); + mcp_json_escape(&body, text); + mcp_buf_puts(&body, "\"}"); + + { + mcp_buf dir; + + mcp_buf_init(&dir); + mcp_buf_printf(&dir, "%s/.tmp", root); + mkdir_p(dir.p); + mcp_buf_free(&dir); + snprintf(tmpname, sizeof(tmpname), "%s/.tmp/embed-XXXXXX", root); + } + free(root); + fd = mkstemp(tmpname); + if (fd < 0) { + mcp_buf_free(&body); + return -1; + } + if (write(fd, body.p, body.len) != (ssize_t)body.len) { + close(fd); + unlink(tmpname); + mcp_buf_free(&body); + return -1; + } + close(fd); + mcp_buf_free(&body); + + mcp_buf_init(&cmd); + mcp_buf_printf(&cmd, "curl -sS -m 20 -H 'Content-Type: application/json' " + "--data-binary @%s '%s' 2>/dev/null", tmpname, embed_url()); + f = popen(cmd.p, "r"); + mcp_buf_free(&cmd); + if (f == NULL) { + unlink(tmpname); + return -1; + } + mcp_buf_init(&body); /* als Lesepuffer wiederverwendet */ + while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) + mcp_buf_add(&body, chunk, got); + pclose(f); + unlink(tmpname); + + if (body.p == NULL) { + mcp_buf_free(&body); + return -1; + } + v = mcp_parse(body.p); + mcp_buf_free(&body); + if (v == NULL) + return -1; + + data = (mcp_json *)mcp_arg(v, "data"); + first = (data != NULL) ? (mcp_json *)mcp_array_at(data, 0) : NULL; + emb = (first != NULL) ? (mcp_json *)mcp_arg(first, "embedding") : NULL; + n = (emb != NULL) ? mcp_array_len(emb) : 0; + if (n == 0 || n > MAX_DIM) { + mcp_json_free(v); + return -1; + } + dim = (int)n; + vec = malloc(sizeof(double) * (size_t)dim); + if (vec == NULL) { + mcp_json_free(v); + return -1; + } + for (i = 0; i < n; i++) { + const mcp_json *e = mcp_array_at(emb, i); + + vec[i] = (e != NULL && e->t == MCP_NUM) ? e->n : 0.0; + } + mcp_json_free(v); + *out_vec = vec; + *out_dim = dim; + return 0; +} + +static double cosine(const double *a, const double *b, int dim) +{ + double dot = 0.0, na = 0.0, nb = 0.0; + int i; + + for (i = 0; i < dim; i++) { + dot += a[i] * b[i]; + na += a[i] * a[i]; + nb += b[i] * b[i]; + } + if (na <= 0.0 || nb <= 0.0) + return 0.0; + return dot / (sqrt(na) * sqrt(nb)); +} + +/* ------------------------------------------------------------------ record */ + +struct mem { + char *id; + char *scope; + char *text; + char *tags; + char *source; + char *model; + long created; + double *vec; + int dim; +}; + +static void free_mem(struct mem *m) +{ + if (m == NULL) + return; + free(m->id); + free(m->scope); + free(m->text); + free(m->tags); + free(m->source); + free(m->model); + free(m->vec); + memset(m, 0, sizeof(*m)); +} + +static const char *js(const mcp_json *v, const char *key) +{ + const char *s = mcp_arg_string(v, key); + + return s != NULL ? s : ""; +} + +static int mem_load(const char *id, struct mem *out) +{ + char *path, *raw; + mcp_json *v; + const mcp_json *emb; + + memset(out, 0, sizeof(*out)); + if (!valid_id(id)) + return -1; + path = mem_path(id); + raw = read_file(path); + free(path); + if (raw == NULL) + return -1; + v = mcp_parse(raw); + free(raw); + if (v == NULL) + return -1; + + out->id = strdup(id); + out->scope = strdup(js(v, "scope")); + out->text = strdup(js(v, "text")); + out->tags = strdup(js(v, "tags")); + out->source = strdup(js(v, "source")); + out->model = strdup(js(v, "model")); + out->created = (long)mcp_arg_num(v, "created", 0); + emb = mcp_arg(v, "embedding"); + out->dim = (emb != NULL) ? (int)mcp_array_len(emb) : 0; + if (out->dim > 0 && out->dim <= MAX_DIM) { + size_t i; + + out->vec = malloc(sizeof(double) * (size_t)out->dim); + if (out->vec == NULL) { + out->dim = 0; + } else { + for (i = 0; i < (size_t)out->dim; i++) { + const mcp_json *e = mcp_array_at(emb, i); + + out->vec[i] = (e != NULL && e->t == MCP_NUM) ? e->n : 0.0; + } + } + } + mcp_json_free(v); + if (out->id == NULL || out->scope == NULL || out->text == NULL || + out->tags == NULL || out->source == NULL || out->model == NULL) { + free_mem(out); + return -1; + } + return 0; +} + +static void put_str(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 mem_save(const struct mem *m) +{ + mcp_buf b; + char *path; + int rc, i; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\n "); + put_str(&b, "id", m->id); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "scope", m->scope); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "text", m->text); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "tags", m->tags); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "source", m->source); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "model", m->model); + mcp_buf_printf(&b, ",\n \"created\":%ld", m->created); + mcp_buf_puts(&b, ",\n \"embedding\":["); + for (i = 0; i < m->dim; i++) + mcp_buf_printf(&b, "%s%.7f", i ? "," : "", m->vec[i]); + mcp_buf_puts(&b, "]\n}\n"); + + path = mem_path(m->id); + rc = write_file_atomic(path, b.p != NULL ? b.p : "{}"); + free(path); + mcp_buf_free(&b); + return rc; +} + +/* Alle IDs im Speicher, sortiert (die Sortierung ist die Reihenfolge der Namen). */ +static int list_ids(char ***out, size_t *out_n) +{ + char *root = mem_root(); + DIR *d; + struct dirent *e; + char **ids = NULL; + size_t n = 0, cap = 0; + + *out = NULL; + *out_n = 0; + d = opendir(root); + if (d == NULL) { + free(root); + return -1; + } + while ((e = readdir(d)) != NULL) { + size_t len = strlen(e->d_name); + char *id; + + if (len < 6 || strcmp(e->d_name + len - 5, ".json") != 0) + continue; + id = strndup(e->d_name, len - 5); + if (id == NULL) + continue; + if (n == cap) { + size_t ncap = cap ? cap * 2 : 32; + char **grown = realloc(ids, sizeof(char *) * ncap); + + if (grown == NULL) { + free(id); + continue; + } + ids = grown; + cap = ncap; + } + ids[n++] = id; + } + closedir(d); + free(root); + *out = ids; + *out_n = n; + return 0; +} + +/* ------------------------------------------------------------------ helper */ + +static const char *scope_arg(const mcp_json *args) +{ + const char *s = mcp_arg_string(args, "scope"); + + return (s != NULL) ? s : ""; +} + +static int scope_matches(const char *task_scope, const char *want) +{ + size_t len; + + if (want == NULL || *want == '\0') + return 1; /* kein Filter: alles */ + len = strlen(want); + if (strncmp(task_scope, want, len) != 0) + return 0; + /* "van" trifft "van" und "van/regeln", nicht "vansinnig" */ + return task_scope[len] == '\0' || task_scope[len] == '/'; +} + +static void say(mcp_conn *c, const char *fmt, ...) +{ + char line[2048]; + va_list ap; + + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + mcp_reply_text(c, line); +} + +struct hit { + struct mem m; + double score; +}; + +static int cmp_hit(const void *pa, const void *pb) +{ + const struct hit *a = pa; + const struct hit *b = pb; + + if (a->score < b->score) + return 1; + if (a->score > b->score) + return -1; + return strcmp(a->m.id, b->m.id); +} + +/* Teilstringsuche, wenn kein Vektor da ist (kein Embedder oder alter Eintrag ohne + * Vektor). strcasestr ist GNU, also selbst geschrieben. */ +static int text_has(const char *haystack, const char *needle) +{ + size_t nlen; + + if (needle == NULL || *needle == '\0') + return 1; + nlen = strlen(needle); + for (const char *p = haystack; *p != '\0'; p++) { + size_t i = 0; + + while (i < nlen && p[i] != '\0' && + tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) + i++; + if (i == nlen) + return 1; + } + return 0; +} + +static void fmt_mem(mcp_buf *b, const struct mem *m, double score, int with_score) +{ + mcp_buf_printf(b, "%s [%s]", m->id, m->scope); + if (with_score) + mcp_buf_printf(b, " score=%.3f", score); + mcp_buf_printf(b, " (%s)", m->model); + if (m->tags != NULL && *m->tags != '\0') + mcp_buf_printf(b, " tags=%s", m->tags); + mcp_buf_puts(b, "\n "); + mcp_buf_puts(b, m->text); + mcp_buf_puts(b, "\n"); +} + +/* ------------------------------------------------------------------ tools */ + +static void t_add(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *scope = scope_arg(args); + const char *text = mcp_arg_string(args, "text"); + const char *tags = mcp_arg_string(args, "tags"); + const char *source = mcp_arg_string(args, "source"); + struct mem m; + double *vec = NULL; + int dim = 0; + int embedded; + char *id; + + (void)user; + if (text == NULL || *text == '\0') { + mcp_reply_error(c, "memory_add needs a text"); + return; + } + if (*scope == '\0') + scope = "general"; + if (strlen(text) > MAX_TEXT) { + mcp_reply_error(c, "text too long (limit 16384 bytes) - store the conclusion, " + "not the transcript"); + return; + } + id = claim_id(); + if (id == NULL) { + mcp_reply_error(c, "could not allocate an id under the memory directory"); + return; + } + embedded = (embed_fetch(text, &vec, &dim) == 0); + + memset(&m, 0, sizeof(m)); + m.id = id; + m.scope = (char *)scope; + m.text = (char *)text; + m.tags = (char *)(tags != NULL ? tags : ""); + m.source = (char *)(source != NULL ? source : ""); + m.model = (char *)(embedded ? embed_model() : "none"); + m.created = (long)time(NULL); + m.vec = vec; + m.dim = dim; + + if (mem_save(&m) != 0) { + free(vec); + mcp_reply_error(c, "could not write the memory file"); + return; + } + if (embedded) + say(c, "stored %s in %s (embedded, %d dimensions)", id, scope, dim); + else + say(c, "stored %s in %s WITHOUT embedding: the embedder at %s did not answer. " + "Search will fall back to substrings for this entry.", id, scope, + embed_url()); + free(vec); + free(id); +} + +static void t_search(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *query = mcp_arg_string(args, "query"); + const char *scope = scope_arg(args); + int limit = mcp_arg_int(args, "limit", 5); + char **ids = NULL; + size_t n = 0, i; + struct hit *hits = NULL; + size_t nhits = 0; + double *qvec = NULL; + int qdim = 0; + int semantic; + mcp_buf b; + + (void)user; + if (query == NULL || *query == '\0') { + mcp_reply_error(c, "memory_search needs a query"); + return; + } + if (limit <= 0 || limit > 50) + limit = 5; + + semantic = (embed_fetch(query, &qvec, &qdim) == 0); + if (list_ids(&ids, &n) != 0) { + say(c, "no memories yet (nothing stored under %s)", mem_root()); + free(qvec); + return; + } + hits = calloc(n ? n : 1, sizeof(*hits)); + if (hits == NULL) { + mcp_reply_error(c, "out of memory"); + goto out; + } + for (i = 0; i < n; i++) { + struct mem m; + + if (mem_load(ids[i], &m) != 0) + continue; + if (!scope_matches(m.scope, scope)) { + free_mem(&m); + continue; + } + if (semantic && m.dim == qdim) { + hits[nhits].m = m; + hits[nhits].score = cosine(qvec, m.vec, qdim); + nhits++; + } else if (!semantic && text_has(m.text, query)) { + hits[nhits].m = m; + hits[nhits].score = 0.0; /* kein Maß, nur "kommt vor" */ + nhits++; + } else { + free_mem(&m); + } + } + qsort(hits, nhits, sizeof(*hits), cmp_hit); + + mcp_buf_init(&b); + if (nhits == 0) { + mcp_buf_printf(&b, "nothing found for \"%s\"%s%s\n", query, + *scope ? " in scope " : "", *scope ? scope : ""); + } else { + size_t show = (size_t)limit < nhits ? (size_t)limit : nhits; + + mcp_buf_printf(&b, "%zu hit(s) for \"%s\"%s%s%s%s:\n", show, query, + *scope ? " in " : "", *scope ? scope : "", + semantic ? "" : " (substring match - the embedder did not answer)", + ""); + for (i = 0; i < show; i++) + fmt_mem(&b, &hits[i].m, hits[i].score, semantic); + } + mcp_reply_text(c, b.p != NULL ? b.p : "nothing found"); + mcp_buf_free(&b); +out: + for (i = 0; i < nhits; i++) + free_mem(&hits[i].m); + free(hits); + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); + free(qvec); +} + +static void t_list(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *scope = scope_arg(args); + int limit = mcp_arg_int(args, "limit", 20); + char **ids = NULL; + size_t n = 0, i, shown = 0; + mcp_buf b; + + (void)user; + if (limit <= 0 || limit > 200) + limit = 20; + if (list_ids(&ids, &n) != 0 || n == 0) { + say(c, "no memories yet (nothing stored under %s)", mem_root()); + goto out; + } + mcp_buf_init(&b); + for (i = n; i > 0 && shown < (size_t)limit; i--) { + struct mem m; + + if (mem_load(ids[i - 1], &m) != 0) + continue; + if (!scope_matches(m.scope, scope)) { + free_mem(&m); + continue; + } + fmt_mem(&b, &m, 0.0, 0); + shown++; + free_mem(&m); + } + if (shown == 0) + mcp_buf_printf(&b, "nothing in scope \"%s\"\n", *scope ? scope : "*"); + else if (shown == (size_t)limit && n > shown) + mcp_buf_printf(&b, "(%zu of %zu, newest first)\n", shown, n); + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); +out: + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); +} + +static void t_get(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *id = mcp_arg_string(args, "id"); + struct mem m; + mcp_buf b; + + (void)user; + if (id == NULL || mem_load(id, &m) != 0) { + mcp_reply_error(c, "no such memory"); + return; + } + mcp_buf_init(&b); + fmt_mem(&b, &m, 0.0, 0); + mcp_buf_printf(&b, " created=%ld source=%s\n", m.created, m.source); + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); + free_mem(&m); +} + +static void t_update(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *id = mcp_arg_string(args, "id"); + const char *text = mcp_arg_string(args, "text"); + const char *tags = mcp_arg_string(args, "tags"); + const char *scope = mcp_arg_string(args, "scope"); + struct mem m; + int changed = 0; + + (void)user; + if (id == NULL || mem_load(id, &m) != 0) { + mcp_reply_error(c, "no such memory"); + return; + } + if (text != NULL && *text != '\0') { + double *vec = NULL; + int dim = 0; + + free(m.text); + m.text = strdup(text); + if (embed_fetch(text, &vec, &dim) == 0) { + free(m.vec); + m.vec = vec; + m.dim = dim; + free(m.model); + m.model = strdup(embed_model()); + } else { + free(m.vec); + m.vec = NULL; + m.dim = 0; + free(m.model); + m.model = strdup("none"); + } + changed = 1; + } + if (tags != NULL) { + free(m.tags); + m.tags = strdup(tags); + changed = 1; + } + if (scope != NULL && *scope != '\0') { + free(m.scope); + m.scope = strdup(scope); + changed = 1; + } + if (!changed) { + say(c, "nothing to change: give text, tags or scope"); + free_mem(&m); + return; + } + if (mem_save(&m) != 0) { + mcp_reply_error(c, "could not write the memory file"); + free_mem(&m); + return; + } + say(c, "updated %s (embedding: %s)", id, m.dim > 0 ? "yes" : "no"); + free_mem(&m); +} + +static void t_delete(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *id = mcp_arg_string(args, "id"); + char *path; + + (void)user; + if (id == NULL || !valid_id(id)) { + mcp_reply_error(c, "no such memory"); + return; + } + path = mem_path(id); + if (unlink(path) != 0) { + free(path); + mcp_reply_error(c, "no such memory"); + return; + } + free(path); + say(c, "deleted %s", id); +} + +static void t_scopes(mcp_conn *c, const mcp_json *args, void *user) +{ + char **ids = NULL; + size_t n = 0, i; + struct { char scope[128]; int count; } seen[256]; + int nseen = 0; + mcp_buf b; + + (void)args; + (void)user; + if (list_ids(&ids, &n) != 0 || n == 0) { + say(c, "no memories yet"); + goto out; + } + for (i = 0; i < n; i++) { + struct mem m; + int j, found = -1; + + if (mem_load(ids[i], &m) != 0) + continue; + for (j = 0; j < nseen; j++) + if (strcmp(seen[j].scope, m.scope) == 0) { + found = j; + break; + } + if (found < 0 && nseen < 256) { + found = nseen++; + snprintf(seen[found].scope, sizeof(seen[found].scope), "%s", m.scope); + seen[found].count = 0; + } + if (found >= 0) + seen[found].count++; + free_mem(&m); + } + mcp_buf_init(&b); + mcp_buf_printf(&b, "%zu memories in %d scope(s):\n", n, nseen); + for (i = 0; i < (size_t)nseen; i++) + mcp_buf_printf(&b, " %-32s %d\n", seen[i].scope, seen[i].count); + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); +out: + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); +} + +/* ------------------------------------------------------------------ table */ + +static const mcp_tool TOOLS[] = { + { "memory_add", + "Store one fact for later. Use it the moment something lasting is decided: a " + "preference, a rule, a measurement, an address, a mistake that must not repeat. " + "Write the CONCLUSION, not the conversation - one paragraph that still makes " + "sense to an agent who was not there. The text is embedded on write, so it can " + "be found by meaning later, not only by keyword. Never store secrets, keys or " + "passwords here.", + "{\"type\":\"object\",\"properties\":{" + "\"text\":{\"type\":\"string\",\"description\":\"the fact, self-contained, one paragraph\"}," + "\"scope\":{\"type\":\"string\",\"description\":\"category, e.g. van/regeln or fleet/junction (default general)\"}," + "\"tags\":{\"type\":\"string\",\"description\":\"extra keywords, comma separated\"}," + "\"source\":{\"type\":\"string\",\"description\":\"who or what this came from\"}}," + "\"required\":[\"text\"]}", + t_add }, + { "memory_search", + "Search what was stored, by meaning. This is the tool to call before asking the " + "user something they may already have told another agent: 'what did we decide " + "about the inverter', 'which rule applies in Portugal'. It returns the closest " + "entries with a score, so a weak match is visible as a weak score instead of " + "being presented as truth.", + "{\"type\":\"object\",\"properties\":{" + "\"query\":{\"type\":\"string\",\"description\":\"what you are looking for, in your own words\"}," + "\"scope\":{\"type\":\"string\",\"description\":\"restrict to a scope and its children\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"how many hits, default 5\"}}," + "\"required\":[\"query\"]}", + t_search }, + { "memory_list", + "List stored memories, newest first. Use it to see what exists in a scope before " + "writing something that may already be there.", + "{\"type\":\"object\",\"properties\":{" + "\"scope\":{\"type\":\"string\",\"description\":\"scope and its children\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"default 20\"}}}", + t_list }, + { "memory_get", + "Read one memory in full by id.", + "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"]}", + t_get }, + { "memory_update", + "Correct a memory: new text (re-embedded), new tags or a new scope. Use it instead " + "of writing a second, contradicting entry - a store with two truths is worse than " + "none.", + "{\"type\":\"object\",\"properties\":{" + "\"id\":{\"type\":\"string\"}," + "\"text\":{\"type\":\"string\"}," + "\"tags\":{\"type\":\"string\"}," + "\"scope\":{\"type\":\"string\"}},\"required\":[\"id\"]}", + t_update }, + { "memory_delete", + "Remove a memory that is wrong or obsolete. Deleting is honest; leaving a stale " + "fact in place is how an agent confidently repeats something that stopped being " + "true.", + "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"]}", + t_delete }, + { "memory_scopes", + "Overview: which scopes exist and how many memories each holds. Call it when you " + "do not know where something belongs.", + "{\"type\":\"object\",\"properties\":{}}", + t_scopes }, +}; + +int main(int argc, char **argv) +{ + mcp_server srv; + + srv.name = "memoryd"; + srv.version = "1.0.0"; + srv.tools = TOOLS; + srv.ntools = sizeof(TOOLS) / sizeof(TOOLS[0]); + srv.user = NULL; + + if (argc >= 3 && strcmp(argv[1], "--http") == 0) { + /* "--http 127.0.0.1:8795" bindet an 127.0.0.1, "--http 8795" an alle Adressen. + * Die Adresse aus der Zeile zu übernehmen ist der Unterschied zwischen "nur + * lokal" und "im ganzen Netz offen" — und eine Einheit, die 127.0.0.1 + * hinschreibt, soll auch 127.0.0.1 bedeuten. */ + char host[64] = ""; + const char *arg = argv[2]; + const char *colon = strrchr(arg, ':'); + int port; + + if (colon != NULL && colon != arg) { + size_t hl = (size_t)(colon - arg); + + if (hl >= sizeof(host)) + return 2; + memcpy(host, arg, hl); + host[hl] = '\0'; + port = mcp_parse_port(colon + 1); + } else { + port = mcp_parse_port(arg); + } + if (port < 0) + return 2; + return mcp_serve_http(&srv, host[0] ? host : NULL, port); + } + return mcp_serve_stdio(&srv); +} diff --git a/packaging/memoryd.service b/packaging/memoryd.service new file mode 100644 index 0000000..944604c --- /dev/null +++ b/packaging/memoryd.service @@ -0,0 +1,23 @@ +[Unit] +Description=memoryd — was ein Agent sich gemerkt hat, mit Bedeutungssuche (MCP über HTTP) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=lotherk +Group=lotherk +Environment=MEMORYDIR=/var/lib/memoryd +# Der Embedder läuft auf demselben Rechner; steht er woanders, hier eintragen. +Environment=EMBED_URL=http://127.0.0.1:8091/v1/embeddings +Environment=EMBED_MODEL=nomic-embed-text +ExecStart=/usr/local/bin/memoryd --http 127.0.0.1:8795 +Restart=always +RestartSec=3 +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths=/var/lib/memoryd +NoNewPrivileges=yes + +[Install] +WantedBy=multi-user.target diff --git a/tests/run.py b/tests/run.py new file mode 100644 index 0000000..0464f08 --- /dev/null +++ b/tests/run.py @@ -0,0 +1,261 @@ +#!/usr/bin/env python3 +"""memoryd — Prüfungen gegen den laufenden Dienst, nicht gegen die Funktion. + +Der Embedder wird durch einen Stub ersetzt: die Suite soll nicht davon abhängen, ob auf +diesem Rechner gerade ein Modell im Speicher liegt. Der Stub liefert deterministische +Vektoren (Zählung von Buchstabengruppen), damit Nähe berechenbar und die Reihenfolge +prüfbar ist. Ob nomic-embed-text Bedeutung gut trifft, ist eine andere Frage als die, +ob memoryd Vektoren richtig schreibt, liest und sortiert. +""" +import http.server +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import time +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +BIN = os.path.join(os.path.dirname(HERE), "memoryd") +FAILED = [] + + +def ok(msg): + print(" OK %s" % msg) + + +def bad(msg): + print(" FAIL %s" % msg) + FAILED.append(msg) + + +def free_port(): + s = socket.socket() + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +class EmbedStub(http.server.BaseHTTPRequestHandler): + """Zählt Buchstaben in 32 Eimern — ähnliche Wörter, ähnliche Vektoren.""" + + def log_message(self, format, *args): # noqa: A002 - Signatur der Basisklasse + pass + + def do_POST(self): + n = int(self.headers.get("Content-Length", "0")) + body = json.loads(self.rfile.read(n) or b"{}") + text = (body.get("input") or "").lower() + vec = [0.0] * 32 + for ch in text: + if ch.isalpha(): + vec[ord(ch) % 32] += 1.0 + norm = sum(v * v for v in vec) ** 0.5 or 1.0 + vec = [round(v / norm, 6) for v in vec] + out = json.dumps({"data": [{"embedding": vec, "index": 0}], + "model": body.get("model", "stub")}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + +class Mcp: + """Minimaler MCP-Client über Streamable HTTP (JSON-RPC 2.0 auf POST).""" + + def __init__(self, port): + self.url = "http://127.0.0.1:%d/mcp" % port + self.sid = None + self.n = 0 + + def _post(self, payload): + data = json.dumps(payload).encode() + h = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + if self.sid: + h["Mcp-Session-Id"] = self.sid + req = urllib.request.Request(self.url, data=data, headers=h) + with urllib.request.urlopen(req, timeout=30) as r: + self.sid = r.headers.get("Mcp-Session-Id", self.sid) + raw = r.read().decode() + if not raw.strip(): + return {} + # Streamable HTTP: entweder reines JSON oder SSE-Zeilen + for line in raw.splitlines(): + if line.startswith("data:"): + return json.loads(line[5:].strip()) + return json.loads(raw) + + def call(self, method, params=None): + self.n += 1 + return self._post({"jsonrpc": "2.0", "id": self.n, "method": method, + "params": params or {}}) + + def tool(self, name, **args): + r = self.call("tools/call", {"name": name, "arguments": args}) + res = r.get("result", {}) + content = res.get("content") or [] + text = content[0].get("text", "") if content else json.dumps(res) + return text, bool(res.get("isError")) + + +def wait_port(port, limit=10.0): + end = time.time() + limit + while time.time() < end: + try: + with socket.create_connection(("127.0.0.1", port), timeout=0.3): + return True + except OSError: + time.sleep(0.05) + return False + + +def main(): + work = tempfile.mkdtemp(prefix="memoryd-test-") + eport, mport = free_port(), free_port() + + stub = http.server.HTTPServer(("127.0.0.1", eport), EmbedStub) + threading.Thread(target=stub.serve_forever, daemon=True).start() + + env = dict(os.environ) + env["MEMORYDIR"] = os.path.join(work, "memories") + env["EMBED_URL"] = "http://127.0.0.1:%d/v1/embeddings" % eport + env["EMBED_MODEL"] = "stub" + + srv = subprocess.Popen([BIN, "--http", "127.0.0.1:%d" % mport], + env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + try: + if not wait_port(mport): + print(srv.stdout.read().decode()[:400] if srv.stdout else "") + bad("memoryd did not come up") + return 1 + + c = Mcp(mport) + init = c.call("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "0"}}) + if init.get("result", {}).get("serverInfo", {}).get("name") == "memoryd": + ok("initialize answers with the server name") + else: + bad("initialize did not name the server: %s" % json.dumps(init)[:120]) + + tools = c.call("tools/list").get("result", {}).get("tools", []) + names = sorted(t["name"] for t in tools) + want = ["memory_add", "memory_delete", "memory_get", "memory_list", + "memory_scopes", "memory_search", "memory_update"] + if names == want: + ok("seven tools, the expected ones") + else: + bad("tools are %s" % names) + + t, err = c.tool("memory_add", text="Der Frostschutz steht auf -25 Grad.", + scope="van/technik", tags="kühlmittel", source="konrad") + if not err and "embedded" in t and "m00001" in t: + ok("a memory is stored and embedded (768 → 32 dims in the stub)") + else: + bad("memory_add said: %s" % t) + + t, err = c.tool("memory_add", text="Der Frostschutz steht auf -25 Grad, G12+ blau.") + if not err: + ok("a second memory lands in the default scope") + else: + bad("second add failed: %s" % t) + + t, err = c.tool("memory_search", query="frostschutz grad", limit=2) + if not err and "score=" in t and "m00001" in t: + ok("search returns scored hits from the vector path") + top = t.splitlines()[0] + if "m00001" in t.split("m00002")[0]: + ok("the closer memory ranks first (%s)" % top.strip()) + else: + bad("ranking looks wrong: %s" % top.strip()) + else: + bad("search said: %s" % t[:200]) + + t, err = c.tool("memory_search", query="frostschutz", scope="van") + if not err and "m00001" in t: + ok("a scope selects itself and its children (van → van/technik)") + else: + bad("scope filter: %s" % t[:160]) + + t, err = c.tool("memory_list", limit=5) + if not err and t.count("m0000") == 2: + ok("memory_list shows both, newest first") + else: + bad("memory_list: %s" % t[:160]) + + t, err = c.tool("memory_get", id="m00001") + if not err and "-25 Grad" in t: + ok("memory_get returns the text") + else: + bad("memory_get: %s" % t[:160]) + + t, err = c.tool("memory_update", id="m00001", text="Der Frostschutz steht auf -30 Grad.") + if not err and "embedding: yes" in t: + ok("memory_update re-embeds the new text") + else: + bad("memory_update: %s" % t[:160]) + + path = os.path.join(env["MEMORYDIR"], "m00001.json") + raw = open(path).read() if os.path.exists(path) else "" + if '"embedding"' in raw and "-30 Grad" in raw: + ok("the file on disk carries the vector and the new text") + else: + bad("the stored file looks wrong: %s" % raw[:120]) + + t, err = c.tool("memory_scopes") + if not err and "van/technik" in t and "general" in t: + ok("memory_scopes counts both scopes") + else: + bad("memory_scopes: %s" % t[:160]) + + # Ohne Embedder: speichern geht weiter, die Suche sagt, was sie tut. + stub.shutdown() + t, err = c.tool("memory_add", text="Die Pumpe läuft seit März leise.", scope="van/technik") + if not err and "WITHOUT embedding" in t: + ok("a dead embedder is reported, not hidden") + else: + bad("storing without an embedder: %s" % t[:160]) + + t, err = c.tool("memory_search", query="pumpe") + if not err and "substring match" in t and "Pumpe" in t: + ok("search falls back to substrings and says so") + else: + bad("fallback search: %s" % t[:200]) + + t, err = c.tool("memory_delete", id="m00002") + if not err and "deleted" in t and not os.path.exists( + os.path.join(env["MEMORYDIR"], "m00002.json")): + ok("memory_delete removes the file") + else: + bad("memory_delete: %s" % t[:160]) + + t, err = c.tool("memory_get", id="m00002") + if err: + ok("a deleted memory is really gone") + else: + bad("memory_get still returns the deleted memory") + finally: + srv.terminate() + try: + srv.wait(timeout=5) + except subprocess.TimeoutExpired: + srv.kill() + stub.shutdown() + shutil.rmtree(work, ignore_errors=True) + + print() + if FAILED: + print("FAILURES: %d" % len(FAILED)) + return 1 + print("PASS") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..81ac5f7 --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# memoryd-Prüfungen. Braucht python3 (HTTP-Client), keinen laufenden Embedder: +# der Stub in run.py ist deterministisch. +set -eu +cd "$(dirname "$0")/.." +[ -x memoryd ] || make -s +exec python3 tests/run.py diff --git a/vendor/libmcp/mcp.h b/vendor/libmcp/mcp.h new file mode 100644 index 0000000..183ba20 --- /dev/null +++ b/vendor/libmcp/mcp.h @@ -0,0 +1,1150 @@ +#ifndef MCP_H +#define MCP_H + +/* + * libmcp - a minimal Model Context Protocol server in C99 + POSIX. + * + * Single file on purpose: copy mcp.h into a project, add one .c that does + * + * #define MCP_IMPLEMENTATION + * #include "mcp.h" + * + * and the whole server is there. No dependencies beyond libc. + * + * What it implements: newline-delimited JSON-RPC 2.0 on stdin/stdout, + * `initialize`, `tools/list`, `tools/call`, `ping`, and the rule that a + * message without an `id` is a notification and gets no answer. + * + * You supply a table of tools; each tool gets its arguments as a read-only + * JSON view and calls exactly one reply function. + * + * static void tool_echo(mcp_conn *c, const mcp_json *args, void *user) + * { + * const char *s = mcp_arg_string(args, "text"); + * mcp_reply_text(c, s ? s : ""); + * } + * + * static const mcp_tool tools[] = { + * { "echo", "Echo text back.", MCP_SCHEMA_ECHO, tool_echo }, + * }; + * + * int main(void) + * { + * mcp_server srv = { "echo-server", "1.0.0", tools, 1, NULL }; + * return mcp_serve_stdio(&srv); + * } + * + * A tool that does not reply gets an error reply from the library, so a + * forgotten branch cannot make a client hang. + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* ---------------------------------------------------------------- json view */ + +enum mcp_jtype { MCP_NULL, MCP_BOOL, MCP_NUM, MCP_STR, MCP_ARR, MCP_OBJ }; + +typedef struct mcp_json mcp_json; + +struct mcp_json { + enum mcp_jtype t; + int b; + double n; + char *s; + mcp_json **items; + char **keys; + size_t count; +}; + +/* ---------------------------------------------------------------- server */ + +typedef struct mcp_conn mcp_conn; + +typedef void (*mcp_handler)(mcp_conn *c, const mcp_json *args, void *user); + +typedef struct { + const char *name; + const char *description; + const char *schema; /* JSON object text for inputSchema */ + mcp_handler handler; +} mcp_tool; + +typedef struct { + const char *name; + const char *version; + const mcp_tool *tools; + size_t ntools; + void *user; +} mcp_server; + +/* Serve on stdin/stdout until EOF. Returns 0. */ +int mcp_serve_stdio(mcp_server *srv); + +/* Serve the same tools over HTTP (Streamable HTTP, JSON-RPC 2.0 on POST). + * host may be NULL for "0.0.0.0". Returns 0 if the socket could not be opened; + * otherwise it never returns — it accepts connections until the process ends. + * + * One process per connection via fork(): without that, every finished child + * stays a zombie and a long-running server grows a process table full of them. */ +int mcp_serve_http(mcp_server *srv, const char *host, int port); + +/* "--http 8781", "--http :8781" and "--http 0.0.0.0:8781" all mean the same. + * Returns -1 (and prints why) for anything that is not a usable port. */ +int mcp_parse_port(const char *s); + +/* ---------------------------------------------------------------- replies */ + +/* Reply with a single text content block (the usual tool answer). */ +void mcp_reply_text(mcp_conn *c, const char *text); + +/* Reply with text that happens to be JSON (pretty for the model, still text). */ +void mcp_reply_json(mcp_conn *c, const char *json); + +/* Reply with a raw result object, exactly as given. */ +void mcp_reply_raw(mcp_conn *c, const char *json); + +/* Reply with a tool error: {"content":[...],"isError":true}. */ +void mcp_reply_error(mcp_conn *c, const char *message); + +/* JSON-RPC level error (bad params, unknown method). */ +void mcp_reply_rpc_error(mcp_conn *c, int code, const char *message); + +/* ---------------------------------------------------------------- arguments */ + +const mcp_json *mcp_arg(const mcp_json *args, const char *key); +const char *mcp_arg_string(const mcp_json *args, const char *key); +int mcp_arg_int(const mcp_json *args, const char *key, int dflt); +double mcp_arg_num(const mcp_json *args, const char *key, double dflt); +int mcp_arg_bool(const mcp_json *args, const char *key, int dflt); + +const char *mcp_json_string(const mcp_json *v); +size_t mcp_array_len(const mcp_json *v); +const mcp_json *mcp_array_at(const mcp_json *v, size_t i); + +/* Growable string. Use it to build a reply, then mcp_reply_text/json it. */ +typedef struct { + char *p; + size_t len; + size_t cap; +} mcp_buf; + +void mcp_buf_init(mcp_buf *b); +void mcp_buf_add(mcp_buf *b, const char *s, size_t n); +void mcp_buf_puts(mcp_buf *b, const char *s); +void mcp_buf_printf(mcp_buf *b, const char *fmt, ...); +void mcp_buf_free(mcp_buf *b); + +/* Escape a string into a JSON string body (no surrounding quotes). */ +void mcp_json_escape(mcp_buf *b, const char *s); + +/* Parse a complete JSON document. Returns NULL on error. Free with + * mcp_json_free(). A backend that stores its own state as JSON needs this. */ +mcp_json *mcp_parse(const char *text); +void mcp_json_free(mcp_json *v); + +/* Handle one JSON-RPC line and return the reply as a malloc'd string, or NULL + * when the message was a notification. Free with free(). This is what a HTTP + * transport needs: same envelope, no stdin/stdout. */ +char *mcp_handle(mcp_server *srv, const char *line); + +#ifdef __cplusplus +} +#endif + + +/* =========================================================================== + * implementation + * =========================================================================== */ +#ifdef MCP_IMPLEMENTATION + +#ifndef MCP_MAX_BODY +#define MCP_MAX_BODY (8u * 1024u * 1024u) +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifndef MCP_MAX_TOOLS +#define MCP_MAX_TOOLS 128 +#endif + +struct mcp_conn { + FILE *out; + mcp_buf outbuf; /* when to_buf, replies accumulate here */ + int to_buf; + char *id_json; /* the request id, already serialized */ + int replied; +}; + +/* ------------------------------------------------------------------ buffer */ + +void mcp_buf_init(mcp_buf *b) +{ + b->p = NULL; + b->len = 0; + b->cap = 0; +} + +void mcp_buf_add(mcp_buf *b, const char *s, size_t n) +{ + if (b->len + n + 1 > b->cap) { + size_t want = b->cap ? b->cap : 256; + + while (want < b->len + n + 1) + want *= 2; + b->p = realloc(b->p, want); + if (b->p == NULL) { + fprintf(stderr, "libmcp: out of memory\n"); + exit(1); + } + b->cap = want; + } + memcpy(b->p + b->len, s, n); + b->len += n; + b->p[b->len] = '\0'; +} + +void mcp_buf_puts(mcp_buf *b, const char *s) +{ + mcp_buf_add(b, s, strlen(s)); +} + +void mcp_buf_printf(mcp_buf *b, const char *fmt, ...) +{ + char tmp[512]; + va_list ap; + int n; + + va_start(ap, fmt); + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); + va_end(ap); + if (n < 0) + return; + if ((size_t)n < sizeof(tmp)) { + mcp_buf_add(b, tmp, (size_t)n); + return; + } + { + char *big = malloc((size_t)n + 1); + + if (big == NULL) + return; + va_start(ap, fmt); + vsnprintf(big, (size_t)n + 1, fmt, ap); + va_end(ap); + mcp_buf_add(b, big, (size_t)n); + free(big); + } +} + +void mcp_buf_free(mcp_buf *b) +{ + free(b->p); + mcp_buf_init(b); +} + +void mcp_json_escape(mcp_buf *b, const char *s) +{ + if (s == NULL) + return; + for (; *s; s++) { + unsigned char c = (unsigned char)*s; + + switch (c) { + case '"': mcp_buf_puts(b, "\\\""); break; + case '\\': mcp_buf_puts(b, "\\\\"); break; + case '\n': mcp_buf_puts(b, "\\n"); break; + case '\r': mcp_buf_puts(b, "\\r"); break; + case '\t': mcp_buf_puts(b, "\\t"); break; + default: + if (c < 0x20) { + char tmp[8]; + + snprintf(tmp, sizeof(tmp), "\\u%04x", c); + mcp_buf_puts(b, tmp); + } else { + mcp_buf_add(b, (const char *)&c, 1); + } + } + } +} + +/* ------------------------------------------------------------------ parser */ + +static mcp_json *jnew(enum mcp_jtype t) +{ + mcp_json *v = calloc(1, sizeof(*v)); + + if (v == NULL) { + fprintf(stderr, "libmcp: out of memory\n"); + exit(1); + } + v->t = t; + return v; +} + +static void jfree(mcp_json *v) +{ + size_t i; + + if (v == NULL) + return; + if (v->t == MCP_STR) + free(v->s); + for (i = 0; i < v->count; i++) { + if (v->keys != NULL) + free(v->keys[i]); + jfree(v->items[i]); + } + free(v->items); + free(v->keys); + free(v); +} + +static const char *skip_ws(const char *p) +{ + while (*p && isspace((unsigned char)*p)) + p++; + return p; +} + +static const char *jparse(const char *p, mcp_json **out); + +static char *parse_string(const char **pp) +{ + const char *p = *pp; + mcp_buf b; + + if (*p != '"') + return NULL; + p++; + mcp_buf_init(&b); + while (*p && *p != '"') { + if (*p == '\\') { + p++; + switch (*p) { + case '"': mcp_buf_add(&b, "\"", 1); break; + case '\\': mcp_buf_add(&b, "\\", 1); break; + case '/': mcp_buf_add(&b, "/", 1); break; + case 'b': mcp_buf_add(&b, "\b", 1); break; + case 'f': mcp_buf_add(&b, "\f", 1); break; + case 'n': mcp_buf_add(&b, "\n", 1); break; + case 'r': mcp_buf_add(&b, "\r", 1); break; + case 't': mcp_buf_add(&b, "\t", 1); break; + case 'u': + if (p[1] && p[2] && p[3] && p[4]) { + char hex[5]; + unsigned long cp; + char utf8[4]; + size_t len = 0; + + memcpy(hex, p + 1, 4); + hex[4] = '\0'; + cp = strtoul(hex, NULL, 16); + if (cp < 0x80) { + utf8[len++] = (char)cp; + } else if (cp < 0x800) { + utf8[len++] = (char)(0xc0 | (cp >> 6)); + utf8[len++] = (char)(0x80 | (cp & 0x3f)); + } else { + utf8[len++] = (char)(0xe0 | (cp >> 12)); + utf8[len++] = (char)(0x80 | ((cp >> 6) & 0x3f)); + utf8[len++] = (char)(0x80 | (cp & 0x3f)); + } + mcp_buf_add(&b, utf8, len); + p += 4; + } + break; + default: mcp_buf_add(&b, p, 1); break; + } + p++; + continue; + } + mcp_buf_add(&b, p, 1); + p++; + } + if (*p == '"') + p++; + *pp = p; + if (b.p == NULL) + mcp_buf_add(&b, "", 0); + return b.p; +} + +static const char *jparse_array(const char *p, mcp_json **out) +{ + mcp_json *v = jnew(MCP_ARR); + + p = skip_ws(p + 1); + if (*p == ']') { + *out = v; + return p + 1; + } + for (;;) { + mcp_json *item = NULL; + + p = jparse(p, &item); + if (p == NULL) { + jfree(v); + return NULL; + } + v->items = realloc(v->items, (v->count + 1) * sizeof(*v->items)); + if (v->items == NULL) { + jfree(v); + return NULL; + } + v->items[v->count++] = item; + p = skip_ws(p); + if (*p == ',') { + p = skip_ws(p + 1); + continue; + } + if (*p == ']') { + *out = v; + return p + 1; + } + jfree(v); + return NULL; + } +} + +static const char *jparse_object(const char *p, mcp_json **out) +{ + mcp_json *v = jnew(MCP_OBJ); + + p = skip_ws(p + 1); + if (*p == '}') { + *out = v; + return p + 1; + } + for (;;) { + char *key = NULL; + mcp_json *val = NULL; + + p = skip_ws(p); + key = parse_string(&p); + if (key == NULL) { + jfree(v); + return NULL; + } + p = skip_ws(p); + if (*p != ':') { + free(key); + jfree(v); + return NULL; + } + p = jparse(skip_ws(p + 1), &val); + if (p == NULL) { + free(key); + jfree(v); + return NULL; + } + v->items = realloc(v->items, (v->count + 1) * sizeof(*v->items)); + v->keys = realloc(v->keys, (v->count + 1) * sizeof(*v->keys)); + if (v->items == NULL || v->keys == NULL) { + free(key); + jfree(val); + jfree(v); + return NULL; + } + v->keys[v->count] = key; + v->items[v->count] = val; + v->count++; + p = skip_ws(p); + if (*p == ',') { + p++; + continue; + } + if (*p == '}') { + *out = v; + return p + 1; + } + jfree(v); + return NULL; + } +} + +static const char *jparse(const char *p, mcp_json **out) +{ + p = skip_ws(p); + switch (*p) { + case '{': + return jparse_object(p, out); + case '[': + return jparse_array(p, out); + case '"': { + mcp_json *v = jnew(MCP_STR); + + v->s = parse_string(&p); + if (v->s == NULL) { + jfree(v); + return NULL; + } + *out = v; + return p; + } + case 't': + if (strncmp(p, "true", 4) == 0) { + mcp_json *v = jnew(MCP_BOOL); + + v->b = 1; + *out = v; + return p + 4; + } + return NULL; + case 'f': + if (strncmp(p, "false", 5) == 0) { + mcp_json *v = jnew(MCP_BOOL); + + v->b = 0; + *out = v; + return p + 5; + } + return NULL; + case 'n': + if (strncmp(p, "null", 4) == 0) { + *out = jnew(MCP_NULL); + return p + 4; + } + return NULL; + default: { + char *end = NULL; + double d = strtod(p, &end); + mcp_json *v; + + if (end == p) + return NULL; + v = jnew(MCP_NUM); + v->n = d; + *out = v; + return end; + } + } +} + +/* ------------------------------------------------------------------ reading */ + +const mcp_json *mcp_arg(const mcp_json *args, const char *key) +{ + size_t i; + + if (args == NULL || args->t != MCP_OBJ || key == NULL) + return NULL; + for (i = 0; i < args->count; i++) + if (strcmp(args->keys[i], key) == 0) + return args->items[i]; + return NULL; +} + +const char *mcp_json_string(const mcp_json *v) +{ + return (v != NULL && v->t == MCP_STR) ? v->s : NULL; +} + +const char *mcp_arg_string(const mcp_json *args, const char *key) +{ + return mcp_json_string(mcp_arg(args, key)); +} + +int mcp_arg_int(const mcp_json *args, const char *key, int dflt) +{ + const mcp_json *v = mcp_arg(args, key); + + return (v != NULL && v->t == MCP_NUM) ? (int)v->n : dflt; +} + +double mcp_arg_num(const mcp_json *args, const char *key, double dflt) +{ + const mcp_json *v = mcp_arg(args, key); + + return (v != NULL && v->t == MCP_NUM) ? v->n : dflt; +} + +int mcp_arg_bool(const mcp_json *args, const char *key, int dflt) +{ + const mcp_json *v = mcp_arg(args, key); + + return (v != NULL && v->t == MCP_BOOL) ? v->b : dflt; +} + +size_t mcp_array_len(const mcp_json *v) +{ + return (v != NULL && v->t == MCP_ARR) ? v->count : 0; +} + +const mcp_json *mcp_array_at(const mcp_json *v, size_t i) +{ + if (v == NULL || v->t != MCP_ARR || i >= v->count) + return NULL; + return v->items[i]; +} + +/* ------------------------------------------------------------------ writing */ + +static void send_line(mcp_conn *c, const char *body, size_t len) +{ + if (c->to_buf) { + mcp_buf_add(&c->outbuf, body, len); + return; + } + fwrite(body, 1, len, c->out); + fputc('\n', c->out); + fflush(c->out); +} + +static void emit_result(mcp_conn *c, const char *result_json) +{ + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); + mcp_buf_puts(&b, c->id_json ? c->id_json : "null"); + mcp_buf_puts(&b, ",\"result\":"); + mcp_buf_puts(&b, result_json); + mcp_buf_puts(&b, "}"); + send_line(c, b.p, b.len); + mcp_buf_free(&b); + c->replied = 1; +} + +void mcp_reply_rpc_error(mcp_conn *c, int code, const char *message) +{ + mcp_buf b; + + if (c->replied) + return; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); + mcp_buf_puts(&b, c->id_json ? c->id_json : "null"); + mcp_buf_printf(&b, ",\"error\":{\"code\":%d,\"message\":\"", code); + mcp_json_escape(&b, message); + mcp_buf_puts(&b, "\"}}"); + send_line(c, b.p, b.len); + mcp_buf_free(&b); + c->replied = 1; +} + +void mcp_reply_raw(mcp_conn *c, const char *json) +{ + if (c->replied) + return; + emit_result(c, json ? json : "{}"); +} + +static void emit_content(mcp_conn *c, const char *text, int is_error) +{ + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":\""); + mcp_json_escape(&b, text ? text : ""); + mcp_buf_puts(&b, "\"}]"); + if (is_error) + mcp_buf_puts(&b, ",\"isError\":true"); + mcp_buf_puts(&b, "}"); + emit_result(c, b.p); + mcp_buf_free(&b); +} + +void mcp_reply_text(mcp_conn *c, const char *text) +{ + if (c->replied) + return; + emit_content(c, text, 0); +} + +void mcp_reply_json(mcp_conn *c, const char *json) +{ + if (c->replied) + return; + emit_content(c, json, 0); +} + +void mcp_reply_error(mcp_conn *c, const char *message) +{ + if (c->replied) + return; + emit_content(c, message, 1); +} + +/* ------------------------------------------------------------------ parse api */ + +mcp_json *mcp_parse(const char *text) +{ + mcp_json *v = NULL; + + if (text == NULL) + return NULL; + if (jparse(text, &v) == NULL) { + jfree(v); + return NULL; + } + return v; +} + +void mcp_json_free(mcp_json *v) +{ + jfree(v); +} + +/* ------------------------------------------------------------------ server */ + +static void tools_list(mcp_conn *c, const mcp_server *srv) +{ + mcp_buf b; + size_t i; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"tools\":["); + for (i = 0; i < srv->ntools; i++) { + const mcp_tool *t = &srv->tools[i]; + + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"name\":\""); + mcp_json_escape(&b, t->name); + mcp_buf_puts(&b, "\",\"description\":\""); + mcp_json_escape(&b, t->description ? t->description : ""); + mcp_buf_puts(&b, "\",\"inputSchema\":"); + mcp_buf_puts(&b, (t->schema && *t->schema) ? t->schema + : "{\"type\":\"object\",\"properties\":{}}"); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "]}"); + emit_result(c, b.p); + mcp_buf_free(&b); +} + +static void tools_call(mcp_conn *c, const mcp_server *srv, const mcp_json *params) +{ + const char *name = mcp_arg_string(params, "name"); + const mcp_json *args = mcp_arg(params, "arguments"); + size_t i; + + if (name == NULL) { + mcp_reply_rpc_error(c, -32602, "missing tool name"); + return; + } + for (i = 0; i < srv->ntools; i++) { + if (strcmp(srv->tools[i].name, name) != 0) + continue; + c->replied = 0; + if (srv->tools[i].handler != NULL) + srv->tools[i].handler(c, args, srv->user); + if (!c->replied) { + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "tool '%s' produced no reply", name); + emit_content(c, b.p, 1); + mcp_buf_free(&b); + } + return; + } + { + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "unknown tool: %s", name); + mcp_reply_rpc_error(c, -32601, b.p); + mcp_buf_free(&b); + } +} + +static char *id_to_json(const mcp_json *id) +{ + mcp_buf b; + + if (id == NULL) + return NULL; + mcp_buf_init(&b); + if (id->t == MCP_STR) { + mcp_buf_puts(&b, "\""); + mcp_json_escape(&b, id->s); + mcp_buf_puts(&b, "\""); + } else if (id->t == MCP_NUM) { + mcp_buf_printf(&b, "%.0f", id->n); + } else if (id->t == MCP_BOOL) { + mcp_buf_puts(&b, id->b ? "true" : "false"); + } else { + mcp_buf_puts(&b, "null"); + } + return b.p; +} + +static void handle_line(mcp_server *srv, const char *line, mcp_conn *c) +{ + mcp_json *msg = NULL; + mcp_json *id; + const char *method; + + if (jparse(line, &msg) == NULL || msg == NULL || msg->t != MCP_OBJ) { + jfree(msg); + c->id_json = NULL; + c->replied = 0; + mcp_reply_rpc_error(c, -32700, "parse error"); + return; + } + id = NULL; + { + size_t i; + + for (i = 0; i < msg->count; i++) + if (strcmp(msg->keys[i], "id") == 0) + id = msg->items[i]; + } + method = mcp_arg_string(msg, "method"); + + c->replied = 0; + free(c->id_json); + c->id_json = id_to_json(id); + + /* no id -> notification -> no answer, whatever the method is */ + if (id == NULL) { + if (method != NULL && strcmp(method, "tools/call") == 0) { + const mcp_json *args = mcp_arg(mcp_arg(msg, "params"), "arguments"); + (void)args; + } + jfree(msg); + return; + } + + if (method == NULL) { + mcp_reply_rpc_error(c, -32600, "invalid request: no method"); + jfree(msg); + return; + } + if (strcmp(method, "initialize") == 0) { + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}"); + mcp_buf_puts(&b, ",\"serverInfo\":{\"name\":\""); + mcp_json_escape(&b, srv->name ? srv->name : "libmcp"); + mcp_buf_puts(&b, "\",\"version\":\""); + mcp_json_escape(&b, srv->version ? srv->version : "1.0.0"); + mcp_buf_puts(&b, "\"}}"); + emit_result(c, b.p); + mcp_buf_free(&b); + } else if (strcmp(method, "tools/list") == 0) { + tools_list(c, srv); + } else if (strcmp(method, "tools/call") == 0) { + tools_call(c, srv, mcp_arg(msg, "params")); + } else if (strcmp(method, "ping") == 0) { + emit_result(c, "{}"); + } else { + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "unknown method: %s", method); + mcp_reply_rpc_error(c, -32601, b.p); + mcp_buf_free(&b); + } + jfree(msg); +} + +/* Plain C99 line reader: no getline, no ssize_t, so this header compiles on + * every libc without a feature-test macro. */ +static int read_line(FILE *f, mcp_buf *b) +{ + int ch; + + b->len = 0; + if (b->p != NULL) + b->p[0] = '\0'; + while ((ch = fgetc(f)) != EOF && ch != '\n') { + char c = (char)ch; + + mcp_buf_add(b, &c, 1); + } + if (ch == EOF && b->len == 0) + return 0; + while (b->len > 0 && b->p[b->len - 1] == '\r') + b->p[--b->len] = '\0'; + return 1; +} + +char *mcp_handle(mcp_server *srv, const char *line) +{ + mcp_conn c; + char *out = NULL; + + if (srv == NULL || line == NULL) + return NULL; + memset(&c, 0, sizeof(c)); + c.out = stdout; + c.to_buf = 1; + mcp_buf_init(&c.outbuf); + handle_line(srv, line, &c); + if (c.outbuf.len > 0) { + out = malloc(c.outbuf.len + 1); + if (out != NULL) + memcpy(out, c.outbuf.p, c.outbuf.len + 1); + } + mcp_buf_free(&c.outbuf); + free(c.id_json); + return out; +} + +int mcp_serve_stdio(mcp_server *srv) +{ + mcp_conn c; + mcp_buf line; + + memset(&c, 0, sizeof(c)); + c.out = stdout; + mcp_buf_init(&line); + while (read_line(stdin, &line)) { + if (line.len == 0) + continue; + handle_line(srv, line.p, &c); + } + mcp_buf_free(&line); + free(c.id_json); + return 0; +} + +/* strcasestr is a GNU extension, not POSIX: do it here. */ +static char *mcp_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 mcp_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 mcp_http_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 = mcp_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 > MCP_MAX_BODY) { + mcp_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 > MCP_MAX_BODY) + break; + } + + if (!header_done) { + mcp_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 */ + mcp_http_reply(fd, 202, NULL, "", session); + free(body); + mcp_buf_free(&head); + close(fd); + return; + } + if (strncmp(head.p, "POST ", 5) != 0) { + mcp_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) { + mcp_http_reply(fd, 202, NULL, "", session); /* notification: nothing to say */ + } else { + mcp_http_reply(fd, 200, "application/json", reply, session); + free(reply); + } + mcp_buf_free(&head); + close(fd); +} + +int mcp_serve_http(mcp_server *srv, const char *host, 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; + if (inet_pton(AF_INET, host ? host : "0.0.0.0", &addr.sin_addr) != 1) + 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; + } + /* Ein Prozess je Verbindung. Dabei NICHT SIGCHLD auf SIG_IGN setzen: das + * lässt den Kernel alle Kinder selbst einsammeln, und dann scheitert jedes + * pclose() im Programm mit ECHILD — popen sieht einen Fehler, obwohl das + * Kommando lief. Genau so scheiterten in skilld alle git-Aufrufe still. + * Stattdessen doppelt forken: das Zwischenkind beendet sich sofort, der + * Enkel gehört init und wird von dort eingesammelt. */ + + fprintf(stderr, "%s: http mcp on %s:%d (session %s)\n", + srv->name ? srv->name : "mcp", host ? host : "0.0.0.0", port, session); + for (;;) { + int fd = accept(ls, NULL, NULL); + pid_t pid; + + if (fd < 0) + continue; + pid = fork(); + if (pid == 0) { + pid_t grand = fork(); + + if (grand == 0) { + close(ls); + mcp_http_serve_one(fd, srv, session); + _exit(0); + } + _exit(0); /* Zwischenkind: sofort weg, kein Zombie */ + } + if (pid > 0) { + int wstatus; + + close(fd); + while (waitpid(pid, &wstatus, 0) < 0 && errno == EINTR) + ; + } else { + mcp_http_serve_one(fd, srv, session); + } + } +} + +/* "--http 8781", "--http :8781" und "--http 0.0.0.0:8781" sind alle gemeint. + * atoi(":8781") is 0 — with the colon in front the server bound to a random + * free port that nobody could find. Skip past the last colon, then read. */ +int mcp_parse_port(const char *s) +{ + const char *p = strrchr(s, ':'); + int port = atoi(p ? p + 1 : s); + + if (port <= 0 || port > 65535) { + fprintf(stderr, "mcp: unusable port in '%s' (want 8781, :8781 or 0.0.0.0:8781)\n", s); + return -1; + } + return port; +} + + +#endif /* MCP_IMPLEMENTATION */ + +#endif /* MCP_H */