commit aedbed3827ac89c1c05b5c38fcdac6a639237657 Author: Hermes Agent Date: Sun Nov 8 18:01:40 2026 +0000 wikid: ein Wiki als eigener Dienst — benannte Wissensbasen mit Seiten Acht Werkzeuge: vier für Basen (wiki_create, wiki_list, wiki_drop, wiki_search), vier für Seiten (page_write, page_read, page_list, page_delete). Eine Seite ist eine Erinnerung mit Titel; der Unterschied ist der Zweck, nicht die Technik. Derselbe Titel aktualisiert die Seite, die vorherige Fassung bleibt in history (fünf Versionen), und wiki_list sagt, ob ein Verlauf existiert. Ohne Embedder wird weiter geschrieben und die Suche sagt, dass sie Buchstaben vergleicht. Ein eigener Dienst, weil Konrad es so wollte ("no different services" galt für die Basen innerhalb von memoryd; danach: doch ein eigener). Port 8796, Ablage /var/lib/wikid, gleiche Form wie tasksd und skilld: ein C99-Programm, stdio und HTTP, MCP. Nebenbei zwei Fallen behoben, die beim Ableiten aus memoryd entstanden: der Titel wurde bei einem Update in anderer Schreibweise überschrieben (aus Frostschutz wurde frostschutz — jetzt behält die Seite ihre Schreibweise), und ein Sortiervergleich zweier anonymer struct-Typen ist in C nicht zuweisbar. Tests: 26 Prüfungen, darunter Verlauf, globales Ranking, confirm-Pflicht und der Rückfall ohne Embedder. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..718e418 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +wikid +*.o diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..031960b --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +CC ?= cc +CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror +LIBDIR ?= vendor/libmcp +PREFIX ?= /usr/local + +all: wikid + +wikid: wikid.c $(LIBDIR)/mcp.h + $(CC) $(CFLAGS) -I$(LIBDIR) -o $@ wikid.c -lm + +test: wikid + ./tests/run.sh + +install: wikid + mkdir -p $(DESTDIR)$(PREFIX)/bin + cp wikid $(DESTDIR)$(PREFIX)/bin/ + +clean: + rm -f wikid + +.PHONY: all test install clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..b5f77a3 --- /dev/null +++ b/README.md @@ -0,0 +1,91 @@ +# wikid — ein Wiki für die Flotte + +Benannte Wissensbasen mit Seiten. Was ein Agent sich beiläufig merkt, gehört nach +`memoryd`; was ein Mensch aufgeschrieben hat, damit es nachgelesen wird, gehört hierher. +Technisch ist beides gleich — Titel, Text, Vektor, Suche nach Bedeutung —, aber der Zweck +entscheidet über die Form: hier gibt es **Basen** (ein Thema je Basis) und **Seiten** mit +Titel, und derselbe Titel aktualisiert die Seite, statt sie zu verdoppeln. + +Ein einzelnes C99-Programm, MCP über stdio und über HTTP, keine Datenbank. + +## Ablage + +``` +$WIKIDIR//kb.json {"name","slug","description","created"} +$WIKIDIR//e00001.json {"id","title","text","tags","source","created","updated", + "model","embedding","history":[{"text","updated"}]} +``` + +Standard für `$WIKIDIR` ist `~/.hermes/wiki`, auf n95 `/var/lib/wikid`. +Eine Datei je Seite: lesbar, kopierbar, sicherbar — und im Zweifel mit `grep` zu finden. + +**Verlauf mit git.** Ist `git` installiert, wird die Ablage beim ersten Schreiben ein +Repository, und jede Änderung wird festgeschrieben (`wiki_create olivia-technik`, +`page_write e00001`, `page_update e00001`, `page_delete e00001`, `wiki_drop `). +Dann ist „wie stand das vor drei Wochen da“ eine Frage an git, nicht an die Erinnerung: + +```sh +cd /var/lib/wikid && git log --oneline +git show HEAD~2:olivia-technik/e00001.json # die Fassung von vorher +git checkout HEAD~2 -- olivia-technik/ # zurücknehmen +``` + +Ist git nicht da, läuft alles weiter; `wiki_list` sagt dann ausdrücklich +`history: none - git is not installed`, damit niemand einen Verlauf annimmt, den es nicht +gibt. + +## Werkzeuge + +| Werkzeug | wofür | +|---|---| +| `wiki_create` | eine Basis je Sachgebiet (`olivia-technik`, `fleet-junction`); `"Olivia Technik"` wird zum Slug `olivia-technik` | +| `wiki_list` | welche Basen es gibt, wie viele Seiten, wofür sie da sind; nennt den Verlauf | +| `page_write` | eine Seite; **derselbe Titel aktualisiert sie** statt sie zu verdoppeln | +| `page_read` | eine Seite ganz, auf Wunsch mit ihren früheren Fassungen | +| `wiki_search` | nach Bedeutung; ohne `kb` über alle Basen, global sortiert | +| `page_list` | was eine Basis schon abdeckt | +| `page_delete` | eine Seite | +| `wiki_drop` | eine ganze Basis — braucht `confirm="yes"`, sonst sagt es nur, was verloren ginge | + +Zwei Entscheidungen, die den Unterschied zu einem Dateiordner ausmachen: + +- **Derselbe Titel = Aktualisierung, mit Verlauf.** Der alte Text wandert in `history` + (fünf Fassungen), und die Antwort sagt `updated … earlier version kept in history`. + Ein Wiki, das still überschreibt, ist keins. Wird der Titel nur anders geschrieben, + behält die Seite ihre bisherige Schreibweise — sonst macht ein flüchtig klein getipptes + Update aus „Frostschutz“ ein „frostschutz“. +- **Die Suche sortiert global** über alle Basen, wenn keine genannt ist — sonst gewinnt + die beste Seite je Basis statt der besten Seite. + +## Bauen und prüfen + +```sh +make && make test # 26 Prüfungen gegen den laufenden Dienst +sudo make install # /usr/local/bin/wikid +``` + +`make test` startet den Dienst auf einem freien Port mit einem **deterministischen +Embedder-Stub** (Buchstabenzählung statt Modell) und prüft über HTTP und stdio: Slug aus +dem Namen, Aktualisierung statt Dublette, lesbarer Verlauf, Suche über alle Basen und +innerhalb einer, Löschen, `confirm`-Pflicht, den Rückfall ohne Embedder — und, wenn git +installiert ist, dass jede Änderung ein Commit ist und eine alte Fassung aus git +zurückkommt. + +## Embedder + +OpenAI-kompatibel: `EMBED_URL` (Standard `http://127.0.0.1:8091/v1/embeddings`), +`EMBED_MODEL` (`nomic-embed-text`, 768 Dimensionen). Ohne Embedder läuft der Dienst +weiter und sagt es (`WITHOUT embedding`, Suche dann `substring match`) — ein Wiki, das +Bedeutung behauptet, wo es Buchstaben vergleicht, wäre schlimmer als eines, das es zugibt. + +## Betrieb + +```sh +sudo cp packaging/wikid.service /etc/systemd/system/ +sudo systemctl daemon-reload && sudo systemctl enable --now wikid +curl -s http://127.0.0.1:8796/mcp -X POST -H 'Content-Type: application/json' \ + -H 'Accept: application/json, text/event-stream' \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' +``` + +Über junction erscheinen die Werkzeuge als `wikid__page_write`, `wikid__wiki_search` usw. diff --git a/packaging/wikid.service b/packaging/wikid.service new file mode 100644 index 0000000..4d95b18 --- /dev/null +++ b/packaging/wikid.service @@ -0,0 +1,23 @@ +[Unit] +Description=wikid — benannte Wissensbasen mit Seiten, Suche nach Bedeutung (MCP über HTTP) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=lotherk +Group=lotherk +Environment=WIKIDIR=/var/lib/wikid +# 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/wikid --http 127.0.0.1:8796 +Restart=always +RestartSec=3 +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths=/var/lib/wikid +NoNewPrivileges=yes + +[Install] +WantedBy=multi-user.target diff --git a/tests/run.py b/tests/run.py new file mode 100644 index 0000000..d42ac1b --- /dev/null +++ b/tests/run.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""wikid — 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 wikid 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), "wikid") +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, _tool_name, **args): + # Der Parameter heißt nicht `name`, weil ein Werkzeug selbst ein Argument `name` + # haben darf (kb_create) — sonst kollidieren Signatur und Aufruf. + r = self.call("tools/call", {"name": _tool_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="wikid-test-") + eport = 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["WIKIDIR"] = work + env["EMBED_URL"] = "http://127.0.0.1:%d/v1/embeddings" % eport + + port = free_port() + srv = subprocess.Popen([BIN, "--http", "127.0.0.1:%d" % port], + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env) + try: + if not wait_port(port): + bad("the service did not come up: %s" % srv.stderr.read().decode()[:300]) + return + c = Mcp(port) + r = c.call("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "0"}}) + if (r.get("result") or {}).get("serverInfo", {}).get("name") == "wikid": + ok("initialize answers with the server name") + else: + bad("initialize: %s" % str(r)[:160]) + + tools = c.call("tools/list").get("result", {}).get("tools", []) + names = sorted(t["name"] for t in tools) + want = ["page_delete", "page_list", "page_read", "page_write", + "wiki_create", "wiki_drop", "wiki_list", "wiki_search"] + if names == want: + ok("eight tools: four for wikis, four for pages") + else: + bad("tools are %s" % names) + + # ---- Wiken anlegen und ansprechen ---- + t, err = c.tool("wiki_create", name="Olivia Technik", + description="was am Fahrzeug gemessen und entschieden wurde") + if not err and "created" in t and "olivia-technik" in t: + ok("a wiki gets a readable slug (Olivia Technik → olivia-technik)") + else: + bad("wiki_create: %s" % t[:160]) + + t, err = c.tool("wiki_create", name="Olivia Technik") + if not err and "already exists" in t: + ok("creating the same wiki twice says so instead of failing") + else: + bad("second wiki_create: %s" % t[:160]) + + t, err = c.tool("page_write", kb="Olivia Technik", title="Frostschutz", + text="G12+ blau, Mischung 50:50, geprüft bei -25 Grad.", + tags="kühlmittel") + if not err and "created" in t: + ok("a page is created in the wiki") + else: + bad("page_write: %s" % t[:160]) + + t, err = c.tool("page_write", kb="olivia-technik", title="frostschutz", + text="G12+ blau, Mischung 60:40, geprüft bei -32 Grad.") + if not err and "updated" in t and "e00001" in t: + ok("the same title (even another case) updates the page, no duplicate") + else: + bad("second write: %s" % t[:160]) + + t, err = c.tool("page_read", kb="Olivia Technik", title="Frostschutz", history=True) + if not err and "-32 Grad" in t and "-25 Grad" in t and "earlier version" in t: + ok("the earlier version survives in the page history") + else: + bad("page_read with history: %s" % t[:220]) + + t, err = c.tool("page_read", kb="Olivia Technik", title="Frostschutz") + if not err and "-25 Grad" not in t: + ok("without history the page shows only the current version") + else: + bad("page_read without history: %s" % t[:160]) + + t, err = c.tool("page_write", kb="Olivia Technik", title="Ölwechsel", + text="OM 364 A: 12 Liter 15W-40, Filter alle 10 000 km.") + if not err: + ok("a second page lands in the same wiki") + else: + bad("second page: %s" % t[:160]) + + # ---- Suchen: Bedeutung statt Buchstaben ---- + t, err = c.tool("wiki_search", query="wie viel öl braucht der motor", limit=2) + if not err and "Ölwechsel" in t and "score=" in t: + ok("search finds the page by meaning") + else: + bad("wiki_search: %s" % t[:220]) + + t, err = c.tool("wiki_search", query="öl", kb="olivia-technik") + if not err and "Ölwechsel" in t: + ok("restricting to one wiki returns the same page") + else: + bad("wiki_search with kb: %s" % t[:220]) + + t, err = c.tool("page_list", kb="Olivia Technik") + if not err and "Frostschutz" in t and "Ölwechsel" in t and "2 entries" in t: + ok("page_list names both pages") + else: + bad("page_list: %s" % t[:220]) + + t, err = c.tool("wiki_list") + if not err and "olivia-technik" in t and "2 entries" in t: + ok("wiki_list shows the wiki with its page count") + else: + bad("wiki_list: %s" % t[:220]) + + t, err = c.tool("wiki_create", name="Fleet Junction") + t, err = c.tool("page_write", kb="Fleet Junction", title="Ports", + text="Der Router hört auf 8090, Metriken auf 9180.") + t, err = c.tool("wiki_search", query="welcher port gehört zu den metriken", limit=3) + if not err and (t.index("Ports") < t.index("Frostschutz") if "Frostschutz" in t else True): + ok("a search without kb covers every wiki and ranks the better page first") + else: + bad("cross-wiki search: %s" % t[:240]) + + # ---- Verlauf: git, wenn vorhanden ---- + if shutil.which("git"): + commits = subprocess.run(["git", "-C", work, "log", "--oneline"], + capture_output=True, text=True).stdout.strip().splitlines() + if len(commits) == 6: + ok("every change is a commit of its own (6 changes, 6 commits)") + else: + bad("expected 6 commits, got %d: %s" % (len(commits), commits)) + + tracked = subprocess.run(["git", "-C", work, "ls-files"], + capture_output=True, text=True).stdout.split() + if any(p.endswith("e00001.json") for p in tracked): + ok("the pages themselves are under version control") + else: + bad("nothing tracked: %s" % tracked) + + # Revert: die alte Fassung muss aus git zurückholbar sein. + old = subprocess.run(["git", "-C", work, "show", + "HEAD~2:olivia-technik/e00001.json"], + capture_output=True, text=True) + if old.returncode == 0 and "50:50" in old.stdout: + ok("an earlier version can be recovered from git (revert works)") + else: + bad("git show of the earlier version failed: %s" % old.stderr[:160]) + + t, err = c.tool("wiki_list") + if "git, every change committed" in t: + ok("wiki_list states that the contents are versioned") + else: + bad("wiki_list does not mention git: %s" % t[:160]) + else: + ok("git is not installed here - the versioning test is skipped, not faked") + + # ---- Löschen ---- + t, err = c.tool("wiki_drop", kb="olivia-technik") + if not err and "not deleting" in t and "confirm" in t: + ok("dropping a wiki needs an explicit yes") + else: + bad("wiki_drop without confirm: %s" % t[:160]) + + t, err = c.tool("page_delete", kb="olivia-technik", title="Frostschutz") + if not err and "deleted" in t: + ok("a single page can be deleted") + else: + bad("page_delete: %s" % t[:160]) + + t, err = c.tool("page_read", kb="olivia-technik", title="Frostschutz") + if err or "no page" in t: + ok("the deleted page is gone") + else: + bad("the page is still there: %s" % t[:120]) + + t, err = c.tool("wiki_drop", kb="olivia-technik", confirm="yes") + if not err and "dropped" in t: + ok("dropping with confirm removes the wiki") + else: + bad("wiki_drop with confirm: %s" % t[:160]) + + t, err = c.tool("wiki_list") + if "fleet-junction" in t and "olivia-technik" not in t: + ok("only the other wiki is left") + else: + bad("wiki_list after drop: %s" % t[:160]) + + # ---- Ohne Embedder: schreiben geht, die Suche sagt, was sie tut ---- + stub.shutdown() + stub.server_close() + t, err = c.tool("page_write", kb="Fleet Junction", title="Ohne Vektor", + text="Diese Seite entstand ohne Embedder.") + if not err and "WITHOUT embedding" in t: + ok("a dead embedder is reported, not hidden") + else: + bad("write without embedder: %s" % t[:200]) + + t, err = c.tool("wiki_search", query="Embedder") + if not err and "substring match" in t: + ok("search falls back to substrings and says so") + else: + bad("fallback search: %s" % t[:200]) + + # ---- stdio: derselbe Dienst, anderer Transport ---- + p = subprocess.run([BIN], input='{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n', + capture_output=True, text=True, env=env, timeout=30) + if '"wiki_create"' in p.stdout: + ok("stdio transport serves the same tools") + else: + bad("stdio: %s" % (p.stdout[:120] + p.stderr[:120])) + finally: + srv.terminate() + try: + srv.wait(timeout=10) + except subprocess.TimeoutExpired: + srv.kill() + stub.shutdown() + stub.server_close() + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + main() + print() + if FAILED: + print("FAILURES: %d" % FAILED) + sys.exit(1) + print("PASS") diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..f76f0e2 --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Baut den Dienst, falls nötig, und prüft ihn über HTTP und stdio. +set -e +cd "$(dirname "$0")/.." +[ -x ./wikid ] || make +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 */ diff --git a/wikid.c b/wikid.c new file mode 100644 index 0000000..6f712ce --- /dev/null +++ b/wikid.c @@ -0,0 +1,1486 @@ +/* strdup/POSIX: das Makro muss vor dem ersten Header stehen. */ +#define _POSIX_C_SOURCE 200809L + +/* + * wikid - ein Wiki für die Flotte: benannte Wissensbasen mit Seiten. + * + * Zwei Transporte aus einem Programm: + * + * wikid stdio, JSON-RPC je Zeile + * wikid --http 8796 Streamable HTTP, damit jeder Host dasselbe Wiki liest + * + * Was ein Agent sich beiläufig merkt, gehört nach memoryd; was ein Mensch aufgeschrieben + * hat, damit es nachgelesen wird, gehört hierher. Technisch ist beides gleich — Titel, + * Text, Vektor —, aber der Zweck entscheidet über die Form: hier gibt es Basen (ein + * Thema je Basis) und Seiten mit Titel, und derselbe Titel aktualisiert die Seite, statt + * sie zu verdoppeln. Die vorherige Fassung bleibt in der Historie. + * + * Ablage unter $WIKIDIR: + * + * /kb.json {"name","slug","description","created"} + * /e00001.json {"id","title","text","tags","source","created","updated", + * "model","embedding","history":[{"text","updated"}]} + * + * Und weil ein Wiki ohne Verlauf kein Wiki ist: ist git installiert, wird das Verzeichnis + * beim ersten Schreiben ein Repository, und jede Änderung wird festgeschrieben. Dann ist + * "wie stand das vor drei Wochen da" eine Frage an git, nicht an die Erinnerung. + */ +#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 *wiki_root(void) +{ + const char *env = getenv("WIKIDIR"); + 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/wiki", 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 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); +} + +/* ------------------------------------------------------------------ git */ +/* + * Ist git installiert, wird die Ablage beim ersten Schreiben ein Repository und jede + * Änderung festgeschrieben — dann ist "wie stand das vor drei Wochen da" eine Frage an + * git statt an die Erinnerung. Ist git nicht da, läuft alles weiter; der Dienst sagt es + * beim Start und in wiki_list, damit niemand Verlauf annimmt, den es nicht gibt. + * + * Zwei Regeln, die den Aufruf billig und harmlos machen: + * - festgeschrieben wird nur, wenn sich wirklich etwas geändert hat (git commit sagt + * sonst "nothing to commit" und das ist kein Fehler); + * - der Text der Meldung kommt ausschließlich aus eigenen Kennungen (e00001, slug), + * nie aus Modell- oder Menschentext. Damit gibt es nichts zu quoten und nichts zu + * injizieren. + */ +static int g_git = -1; /* -1 ungeprüft, 0 kein git, 1 git vorhanden */ + +static int git_available(void) +{ + if (g_git >= 0) + return g_git; + g_git = (system("git --version >/dev/null 2>&1") == 0) ? 1 : 0; + return g_git; +} + +static void git_ensure_repo(void) +{ + static int done; + + if (done || !git_available()) + return; + done = 1; + { + char *root = wiki_root(); + mcp_buf cmd; + + mcp_buf_init(&cmd); + /* rev-parse entscheidet, ob schon ein Repository (auch ein übergeordnetes). */ + mcp_buf_printf(&cmd, "git -C '%s' rev-parse --git-dir >/dev/null 2>&1 || " + "git -C '%s' init -q", root, root); + if (system(cmd.p) != 0) { + fprintf(stderr, "wikid: git init in %s failed\n", root); + } else { + FILE *ign = NULL; + char *path = NULL; + + { + mcp_buf pb; + + mcp_buf_init(&pb); + mcp_buf_printf(&pb, "%s/.gitignore", root); + path = pb.p; + } + ign = fopen(path != NULL ? path : "/dev/null", "w"); + if (ign != NULL) { + fprintf(ign, "*.tmp.*\n.tmp/\n"); + fclose(ign); + } + free(path); + } + mcp_buf_free(&cmd); + free(root); + } +} + +/* Schreibt eine Änderung fest. Verb und Kennung stammen von uns, nicht vom Aufrufer. */ +static void git_commit(const char *verb, const char *what) +{ + char *root; + mcp_buf cmd; + + if (!git_available()) + return; + git_ensure_repo(); + root = wiki_root(); + mcp_buf_init(&cmd); + /* Die Kennung ist geprüft (valid_id) beziehungsweise ein Slug aus [a-z0-9-]; der + * Verb ist ein Literal aus unserem Code. Kein Anführungszeichen weit und breit. */ + mcp_buf_printf(&cmd, "git -C '%s' add -A >/dev/null 2>&1 && " + "git -C '%s' -c user.name=wikid -c user.email=wikid@localhost " + "commit -q -m \"%s %s\" >/dev/null 2>&1", root, root, verb, what); + if (system(cmd.p) != 0) + fprintf(stderr, "wikid: git commit failed (%s %s)\n", verb, what); + mcp_buf_free(&cmd); + free(root); +} + +/* ------------------------------------------------------------------ helper */ + + + +static const char *js(const mcp_json *v, const char *key) +{ + const char *s = mcp_arg_string(v, key); + + return s != NULL ? s : ""; +} + +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, "\""); +} + +/* Teilstringsuche, wenn kein Vektor da ist (kein Embedder oder alte Seite 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; +} + +/* ------------------------------------------------------------------ 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 = wiki_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)); +} + +/* ========================================================================== + * Wissensbasis: benannte Sammlungen, sonst wie Erinnerungen + * + * Eine Wissensbasis ist ein Name mit einem Verzeichnis darunter, und darin liegen + * Seiten wie Erinnerungen: Titel, Text, Vektor. Der Unterschied ist der Zweck — + * Erinnerungen sind das, was ein Agent beiläufig behält; eine Wissensbasis ist das, + * was ein Mensch aufgeschrieben hat, damit es nachgelesen wird. + * + * $MEMORYDIR/kb//kb.json {"name","slug","description","created"} + * $MEMORYDIR/kb//e00001.json {"id","title","text","tags","source", + * "created","updated","model","embedding", + * "history":[{"text","updated"}]} + * + * Schreiben mit demselben Titel überschreibt die Seite nicht stillschweigend: der alte + * Text wandert in `history` (fünf Fassungen), und die Antwort sagt, dass es eine + * Aktualisierung war. Ein Wiki ohne jede Spur der vorherigen Fassung ist keins. + * ========================================================================== */ + +#define MAX_KB 512 +#define MAX_HISTORY 5 + +struct entry { + char *id; + char *title; + char *text; + char *tags; + char *source; + char *model; + long created; + long updated; + double *vec; + int dim; + /* Ältere Fassungen, nur beim Lesen/Schreiben gebraucht. */ + int nhist; + long hist_at[MAX_HISTORY]; + char *hist_text[MAX_HISTORY]; +}; + +static void free_entry(struct entry *e) +{ + int i; + + if (e == NULL) + return; + free(e->id); + free(e->title); + free(e->text); + free(e->tags); + free(e->source); + free(e->model); + free(e->vec); + for (i = 0; i < e->nhist; i++) + free(e->hist_text[i]); + memset(e, 0, sizeof(*e)); +} + +/* Ein Treffer über mehrere Basen: Basis, Seite, Bewertung. Benannt, weil ein + * anonymer struct-Typ sich nicht zuweisen lässt (und Sortieren ist Zuweisen). */ +struct kbhit { + char slug[MAX_KB]; + struct entry e; + double score; +}; + +/* Name → Verzeichnisname: Kleinbuchstaben, alles Fremde zu "-", keine Doppelpunkte. */ +static void slugify(const char *name, char *out, size_t outlen) +{ + size_t i = 0; + int last_dash = 0; + + for (const char *p = name; *p != '\0' && i + 1 < outlen; p++) { + unsigned char ch = (unsigned char)*p; + + if (isalnum(ch)) { + out[i++] = (char)tolower(ch); + last_dash = 0; + } else if (!last_dash) { + out[i++] = '-'; + last_dash = 1; + } + } + while (i > 0 && out[i - 1] == '-') + i--; + out[i] = '\0'; +} + +/* Die Wurzel IST die Ablage: $WIKIDIR//, kein Zwischenverzeichnis. */ +static char *kb_root(void) +{ + return wiki_root(); +} + +static char *kb_dir(const char *slug) +{ + char *root = kb_root(); + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s/%s", root, slug); + free(root); + return b.p; +} + +static char *kb_file(const char *slug, const char *leaf) +{ + char *dir = kb_dir(slug); + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s/%s", dir, leaf); + free(dir); + return b.p; +} + +/* Existiert die Basis? Name und Beschreibung kommen aus kb.json. */ +static int kb_meta(const char *slug, char *name, size_t namelen, char *desc, size_t desclen) +{ + char *path = kb_file(slug, "kb.json"); + char *raw = read_file(path); + mcp_json *v; + + free(path); + if (raw == NULL) + return -1; + v = mcp_parse(raw); + free(raw); + if (v == NULL) + return -1; + snprintf(name, namelen, "%s", js(v, "name")); + if (desc != NULL) + snprintf(desc, desclen, "%s", js(v, "description")); + mcp_json_free(v); + return 0; +} + +static int kb_save_meta(const char *slug, const char *name, const char *desc) +{ + char *path = kb_file(slug, "kb.json"); + mcp_buf b; + int rc; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\n "); + put_str(&b, "name", name); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "slug", slug); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "description", desc != NULL ? desc : ""); + mcp_buf_printf(&b, ",\n \"created\":%ld\n}\n", (long)time(NULL)); + rc = write_file_atomic(path, b.p != NULL ? b.p : "{}"); + mcp_buf_free(&b); + free(path); + return rc; +} + +/* Alle Basen: Verzeichnisse unter kb/ mit kb.json. */ +static int kb_list_all(char slugs[][MAX_KB], int max, int *count) +{ + char *root = kb_root(); + DIR *d; + struct dirent *de; + + *count = 0; + d = opendir(root); + if (d == NULL) { + free(root); + return -1; + } + while ((de = readdir(d)) != NULL && *count < max) { + char *path; + FILE *f; + + if (de->d_name[0] == '.') + continue; + path = kb_file(de->d_name, "kb.json"); + f = fopen(path, "r"); + free(path); + if (f == NULL) + continue; /* kein fertiges Verzeichnis */ + fclose(f); + snprintf(slugs[*count], MAX_KB, "%s", de->d_name); + (*count)++; + } + closedir(d); + free(root); + /* Verzeichnisreihenfolge ist nicht stabil; sortieren, damit die Ausgabe es ist. */ + for (int i = 1; i < *count; i++) + for (int j = i; j > 0 && strcmp(slugs[j - 1], slugs[j]) > 0; j--) { + char tmp[MAX_KB]; + + snprintf(tmp, sizeof(tmp), "%s", slugs[j]); + snprintf(slugs[j], MAX_KB, "%s", slugs[j - 1]); + snprintf(slugs[j - 1], MAX_KB, "%s", tmp); + } + return 0; +} + +static int kb_entry_ids(const char *slug, char ***out, size_t *out_n) +{ + char *dir = kb_dir(slug); + DIR *d; + struct dirent *de; + char **ids = NULL; + size_t n = 0, cap = 0; + + *out = NULL; + *out_n = 0; + d = opendir(dir); + free(dir); + if (d == NULL) + return -1; + while ((de = readdir(d)) != NULL) { + size_t len = strlen(de->d_name); + char *id; + + if (len < 6 || strncmp(de->d_name, "e", 1) != 0 || + strcmp(de->d_name + len - 5, ".json") != 0) + continue; + id = strndup(de->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); + *out = ids; + *out_n = n; + return 0; +} + +static char *kb_claim_entry_id(const char *slug) +{ + char *dir = kb_dir(slug); + int n; + + mkdir_p(dir); + for (n = 1; n < 100000; n++) { + mcp_buf path; + int fd; + + mcp_buf_init(&path); + mcp_buf_printf(&path, "%s/e%05d.json", dir, 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, "e%05d", n); + free(dir); + return out; + } + if (errno != EEXIST) { + free(dir); + return NULL; + } + } + free(dir); + return NULL; +} + +static int entry_load(const char *slug, const char *id, struct entry *out) +{ + char *leaf, *path, *raw; + mcp_json *v; + const mcp_json *emb, *hist; + + memset(out, 0, sizeof(*out)); + if (!valid_id(id)) + return -1; + leaf = NULL; + { + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s.json", id); + leaf = b.p; + } + path = kb_file(slug, leaf); + free(leaf); + 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->title = strdup(js(v, "title")); + 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); + out->updated = (long)mcp_arg_num(v, "updated", out->created); + 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; + } + } + } + hist = mcp_arg(v, "history"); + if (hist != NULL) { + size_t nh = mcp_array_len(hist); + + for (size_t i = 0; i < nh && out->nhist < MAX_HISTORY; i++) { + const mcp_json *h = mcp_array_at(hist, i); + + if (h == NULL) + continue; + out->hist_text[out->nhist] = strdup(js(h, "text")); + out->hist_at[out->nhist] = (long)mcp_arg_num(h, "updated", 0); + if (out->hist_text[out->nhist] != NULL) + out->nhist++; + } + } + mcp_json_free(v); + if (out->id == NULL || out->title == NULL || out->text == NULL || + out->tags == NULL || out->source == NULL || out->model == NULL) { + free_entry(out); + return -1; + } + return 0; +} + +static int entry_save(const char *slug, const struct entry *e) +{ + char *leaf, *path; + mcp_buf b; + int rc, i; + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\n "); + put_str(&b, "id", e->id); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "title", e->title); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "text", e->text); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "tags", e->tags); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "source", e->source); + mcp_buf_puts(&b, ",\n "); + put_str(&b, "model", e->model); + mcp_buf_printf(&b, ",\n \"created\":%ld,\n \"updated\":%ld", e->created, e->updated); + mcp_buf_puts(&b, ",\n \"embedding\":["); + for (i = 0; i < e->dim; i++) + mcp_buf_printf(&b, "%s%.7f", i ? "," : "", e->vec[i]); + mcp_buf_puts(&b, "],\n \"history\":["); + for (i = 0; i < e->nhist; i++) { + mcp_buf_puts(&b, i ? ",{" : "{"); + put_str(&b, "text", e->hist_text[i]); + mcp_buf_printf(&b, ",\"updated\":%ld}", e->hist_at[i]); + } + mcp_buf_puts(&b, "]\n}\n"); + + { + mcp_buf leaf_buf; + + mcp_buf_init(&leaf_buf); + mcp_buf_printf(&leaf_buf, "%s.json", e->id); + leaf = leaf_buf.p; + } + path = kb_file(slug, leaf != NULL ? leaf : "e.json"); + free(leaf); + rc = write_file_atomic(path, b.p != NULL ? b.p : "{}"); + free(path); + mcp_buf_free(&b); + return rc; +} + +/* Seite mit diesem Titel (ohne Rücksicht auf Groß/klein) oder NULL. */ +static char *find_by_title(const char *slug, const char *title) +{ + char **ids = NULL; + size_t n = 0, i; + char *found = NULL; + + if (kb_entry_ids(slug, &ids, &n) != 0) + return NULL; + for (i = 0; i < n && found == NULL; i++) { + struct entry e; + + if (entry_load(slug, ids[i], &e) != 0) + continue; + if (strcasecmp(e.title, title) == 0) + found = strdup(ids[i]); + free_entry(&e); + } + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); + return found; +} + +static void fmt_entry_ref(mcp_buf *b, const char *slug, const struct entry *e, double score) +{ + mcp_buf_printf(b, "%s/%s [%s]", slug, e->id, e->title); + if (score >= 0.0) + mcp_buf_printf(b, " score=%.3f", score); + if (e->tags != NULL && *e->tags != '\0') + mcp_buf_printf(b, " tags=%s", e->tags); + mcp_buf_puts(b, "\n "); + if (strlen(e->text) > 400) + mcp_buf_add(b, e->text, 400); + else + mcp_buf_puts(b, e->text); + if (strlen(e->text) > 400) + mcp_buf_puts(b, " …"); + mcp_buf_puts(b, "\n"); +} + +static void t_kb_create(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *name = mcp_arg_string(args, "name"); + const char *desc = mcp_arg_string(args, "description"); + char slug[MAX_KB], existing[MAX_KB]; + + (void)user; + if (name == NULL || *name == '\0') { + mcp_reply_error(c, "kb_create needs a name"); + return; + } + slugify(name, slug, sizeof(slug)); + if (slug[0] == '\0') { + mcp_reply_error(c, "that name has no usable characters for a directory"); + return; + } + if (kb_meta(slug, existing, sizeof(existing), NULL, 0) == 0) { + say(c, "knowledge base \"%s\" already exists (%s) - write into it with kb_write", + existing, slug); + return; + } + { + char *dir = kb_dir(slug); + + mkdir_p(dir); + free(dir); + } + if (kb_save_meta(slug, name, desc) != 0) { + mcp_reply_error(c, "could not create the knowledge base directory"); + return; + } + git_commit("wiki_create", slug); + say(c, "created knowledge base \"%s\" (%s)%s%s", name, slug, + (desc != NULL && *desc) ? ": " : "", (desc != NULL && *desc) ? desc : ""); +} + +static void t_kb_list(mcp_conn *c, const mcp_json *args, void *user) +{ + char slugs[64][MAX_KB]; + int n = 0, i; + mcp_buf b; + + (void)args; + (void)user; + if (kb_list_all(slugs, 64, &n) != 0 || n == 0) { + say(c, "no knowledge bases yet - create one with kb_create"); + return; + } + { + char *root = wiki_root(); + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%d knowledge base(s) in %s (history: %s)\n", n, root, + git_available() ? "git, every change committed" + : "none - git is not installed"); + free(root); + } + for (i = 0; i < n; i++) { + char name[256] = "", desc[256] = ""; + char **ids = NULL; + size_t ne = 0; + + (void)kb_meta(slugs[i], name, sizeof(name), desc, sizeof(desc)); + (void)kb_entry_ids(slugs[i], &ids, &ne); + for (size_t k = 0; k < ne; k++) + free(ids[k]); + free(ids); + mcp_buf_printf(&b, " %-24s %-20s %4zu entries", slugs[i], name, ne); + if (desc[0] != '\0') + mcp_buf_printf(&b, " — %s", desc); + mcp_buf_puts(&b, "\n"); + } + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); +} + +static void t_kb_write(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *kb = mcp_arg_string(args, "kb"); + const char *title = mcp_arg_string(args, "title"); + const char *text = mcp_arg_string(args, "text"); + const char *tags = mcp_arg_string(args, "tags"); + const char *source = mcp_arg_string(args, "source"); + char slug[MAX_KB], name[256]; + char *own_id = NULL; + struct entry old, e; + int had_old = 0; + double *vec = NULL; + int dim = 0, embedded, i; + + (void)user; + if (kb == NULL || *kb == '\0' || title == NULL || *title == '\0' || + text == NULL || *text == '\0') { + mcp_reply_error(c, "kb_write needs kb, title and text"); + return; + } + slugify(kb, slug, sizeof(slug)); + if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { + say(c, "no knowledge base \"%s\" - create it first with kb_create", kb); + return; + } + if (strlen(text) > MAX_TEXT) { + mcp_reply_error(c, "text too long (limit 16384 bytes) - a page, not a transcript"); + return; + } + embedded = (embed_fetch(text, &vec, &dim) == 0); + + /* Eine Seite mit diesem Titel gibt es schon? Dann ist das eine Aktualisierung. + * Die alte Fassung wird EINMAL gelesen und danach in die Historie übernommen. */ + memset(&old, 0, sizeof(old)); + { + char *found = find_by_title(slug, title); + + if (found != NULL) { + if (entry_load(slug, found, &old) == 0) + had_old = 1; + own_id = found; + } else { + own_id = kb_claim_entry_id(slug); + } + } + if (own_id == NULL) { + free(vec); + mcp_reply_error(c, "could not allocate a page id"); + return; + } + + memset(&e, 0, sizeof(e)); + e.id = own_id; + /* Schreibt jemand denselben Titel in anderer Schreibweise, bleibt die Seite unter + * ihrem bisherigen Namen stehen — sonst macht ein flüchtig klein getippter Update + * aus "Frostschutz" ein "frostschutz". Ein echter anderer Titel benennt sie um. */ + e.title = (had_old && old.title != NULL && strcasecmp(old.title, title) == 0) + ? old.title : (char *)title; + e.text = (char *)text; + e.tags = (char *)(tags != NULL ? tags : ""); + e.source = (char *)(source != NULL ? source : ""); + e.model = (char *)(embedded ? embed_model() : "none"); + e.created = had_old && old.created ? old.created : (long)time(NULL); + e.updated = (long)time(NULL); + e.vec = vec; + e.dim = dim; + + /* Historie: die bisherigen Fassungen übernehmen, die vorherige anhängen, die + * älteste fallen lassen, wenn fünf voll sind. */ + if (had_old) { + for (i = 0; i < old.nhist && e.nhist < MAX_HISTORY; i++) { + e.hist_text[e.nhist] = strdup(old.hist_text[i] != NULL ? old.hist_text[i] : ""); + e.hist_at[e.nhist] = old.hist_at[i]; + if (e.hist_text[e.nhist] != NULL) + e.nhist++; + } + if (old.text != NULL && strcmp(old.text, text) != 0) { + if (e.nhist == MAX_HISTORY) { + free(e.hist_text[0]); + for (i = 1; i < MAX_HISTORY; i++) { + e.hist_text[i - 1] = e.hist_text[i]; + e.hist_at[i - 1] = e.hist_at[i]; + } + e.hist_text[MAX_HISTORY - 1] = NULL; + e.nhist = MAX_HISTORY - 1; + } + e.hist_text[e.nhist] = strdup(old.text); + e.hist_at[e.nhist] = old.updated; + if (e.hist_text[e.nhist] != NULL) + e.nhist++; + } + } + + if (entry_save(slug, &e) == 0) { + git_commit(had_old ? "page_update" : "page_write", own_id); + say(c, "%s %s/%s \"%s\"%s%s", had_old ? "updated" : "created", slug, own_id, title, + embedded ? " (embedded)" : " (WITHOUT embedding: the embedder did not answer, " + "search will fall back to substrings for this page)", + (had_old && e.nhist > 0) ? " - earlier version kept in history" : ""); + } else { + say(c, "could not write %s/%s", slug, own_id); + } + + for (i = 0; i < e.nhist; i++) + free(e.hist_text[i]); + if (had_old) + free_entry(&old); + free(vec); + free(own_id); +} + +static void t_kb_entries(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *kb = mcp_arg_string(args, "kb"); + int limit = mcp_arg_int(args, "limit", 50); + char slug[MAX_KB], name[256]; + char **ids = NULL; + size_t n = 0, i, shown = 0; + mcp_buf b; + + (void)user; + if (kb == NULL || *kb == '\0') { + mcp_reply_error(c, "kb_entries needs kb"); + return; + } + slugify(kb, slug, sizeof(slug)); + if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { + say(c, "no knowledge base \"%s\"", kb); + return; + } + if (limit <= 0 || limit > 500) + limit = 50; + mcp_buf_init(&b); + if (kb_entry_ids(slug, &ids, &n) != 0 || n == 0) { + mcp_buf_printf(&b, "\"%s\" has no entries yet\n", name); + mcp_reply_text(c, b.p); + mcp_buf_free(&b); + return; + } + mcp_buf_printf(&b, "%zu entries in \"%s\" (newest first):\n", n, name); + for (i = n; i > 0 && shown < (size_t)limit; i--) { + struct entry e; + + if (entry_load(slug, ids[i - 1], &e) != 0) + continue; + mcp_buf_printf(&b, " %s %s", e.id, e.title); + if (e.tags != NULL && *e.tags != '\0') + mcp_buf_printf(&b, " tags=%s", e.tags); + mcp_buf_printf(&b, " (%s, updated %ld)\n", e.dim > 0 ? "embedded" : "no vector", + e.updated); + shown++; + free_entry(&e); + } + if (shown < n) + mcp_buf_printf(&b, "(%zu of %zu)\n", shown, n); + mcp_reply_text(c, b.p); + mcp_buf_free(&b); + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); +} + +static void t_kb_read(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *kb = mcp_arg_string(args, "kb"); + const char *title = mcp_arg_string(args, "title"); + const char *id = mcp_arg_string(args, "id"); + int history = mcp_arg_bool(args, "history", 0); + char slug[MAX_KB], name[256]; + struct entry e; + mcp_buf b; + char *found = NULL; + + (void)user; + if (kb == NULL || *kb == '\0') { + mcp_reply_error(c, "kb_read needs kb and title (or id)"); + return; + } + if (id == NULL || *id == '\0') { + if (title == NULL || *title == '\0') { + mcp_reply_error(c, "kb_read needs kb and title (or id)"); + return; + } + } + slugify(kb, slug, sizeof(slug)); + if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { + say(c, "no knowledge base \"%s\"", kb); + return; + } + found = (id != NULL && *id != '\0') ? strdup(id) : find_by_title(slug, title); + if (found == NULL || entry_load(slug, found, &e) != 0) { + say(c, "no page \"%s\" in \"%s\"", title != NULL ? title : id, name); + free(found); + return; + } + mcp_buf_init(&b); + mcp_buf_printf(&b, "# %s (%s/%s)\n", e.title, slug, e.id); + if (e.tags != NULL && *e.tags != '\0') + mcp_buf_printf(&b, "tags: %s\n", e.tags); + mcp_buf_printf(&b, "source: %s created: %ld updated: %ld vector: %s\n\n", + e.source ? e.source : "-", e.created, e.updated, + e.dim > 0 ? "yes" : "no"); + mcp_buf_puts(&b, e.text != NULL ? e.text : ""); + mcp_buf_puts(&b, "\n"); + if (history && e.nhist > 0) { + mcp_buf_printf(&b, "\n--- %d earlier version(s) ---\n", e.nhist); + for (int i = e.nhist - 1; i >= 0; i--) + mcp_buf_printf(&b, "[%ld]\n%s\n", e.hist_at[i], + e.hist_text[i] != NULL ? e.hist_text[i] : ""); + } + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); + free_entry(&e); + free(found); +} + +static void t_kb_search(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *query = mcp_arg_string(args, "query"); + const char *kb = mcp_arg_string(args, "kb"); + int limit = mcp_arg_int(args, "limit", 5); + char slugs[64][MAX_KB]; + int nslugs = 0, si; + double *qvec = NULL; + int qdim = 0, semantic; + mcp_buf b; + int shown = 0; + + (void)user; + if (query == NULL || *query == '\0') { + mcp_reply_error(c, "kb_search needs a query"); + return; + } + if (limit <= 0 || limit > 50) + limit = 5; + semantic = (embed_fetch(query, &qvec, &qdim) == 0); + + if (kb != NULL && *kb != '\0') { + char slug[MAX_KB]; + + slugify(kb, slug, sizeof(slug)); + snprintf(slugs[0], MAX_KB, "%s", slug); + nslugs = 1; + } else if (kb_list_all(slugs, 64, &nslugs) != 0) { + nslugs = 0; + } + if (nslugs == 0) { + say(c, "no knowledge bases yet - create one with kb_create"); + free(qvec); + return; + } + + /* Alle Treffer sammeln und global sortieren: eine Suche über mehrere Basen soll + * die beste Seite zeigen, nicht die beste Seite je Basis. */ + { + struct kbhit *hits = NULL; + size_t nhits = 0, cap = 0; + + for (si = 0; si < nslugs; si++) { + char **ids = NULL; + size_t n = 0, i; + + if (kb_entry_ids(slugs[si], &ids, &n) != 0) + continue; + for (i = 0; i < n; i++) { + struct entry e; + double score = -1.0; + int take = 0; + + if (entry_load(slugs[si], ids[i], &e) != 0) + continue; + if (semantic && e.dim == qdim) { + score = cosine(qvec, e.vec, qdim); + take = 1; + } else if (!semantic && text_has(e.text, query)) { + score = -1.0; + take = 1; + } + if (!take) { + free_entry(&e); + continue; + } + if (nhits == cap) { + size_t ncap = cap ? cap * 2 : 32; + void *grown = realloc(hits, ncap * sizeof(struct kbhit)); + + if (grown == NULL) { + free_entry(&e); + continue; + } + hits = grown; + cap = ncap; + } + snprintf(hits[nhits].slug, MAX_KB, "%.*s", MAX_KB - 1, slugs[si]); + hits[nhits].e = e; + hits[nhits].score = score; + nhits++; + } + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); + } + /* Sortieren: bester Score zuerst (bei Substringsuche die Einfügereihenfolge). */ + for (size_t i = 1; i < nhits; i++) + for (size_t j = i; j > 0 && hits[j].score > hits[j - 1].score; j--) { + struct kbhit tmp = hits[j]; + + hits[j] = hits[j - 1]; + hits[j - 1] = tmp; + } + + mcp_buf_init(&b); + if (nhits == 0) { + mcp_buf_printf(&b, "nothing found for \"%s\"%s%s\n", query, + semantic ? "" : " (substring match - the embedder did not answer)", + ""); + } else { + size_t show = (size_t)limit < nhits ? (size_t)limit : nhits; + + mcp_buf_printf(&b, "%zu hit(s) for \"%s\"%s:\n", show, query, + semantic ? "" : " (substring match)"); + for (size_t i = 0; i < show; i++) { + fmt_entry_ref(&b, hits[i].slug, &hits[i].e, semantic ? hits[i].score : -1.0); + shown++; + } + } + mcp_reply_text(c, b.p != NULL ? b.p : ""); + mcp_buf_free(&b); + for (size_t i = 0; i < nhits; i++) + free_entry(&hits[i].e); + free(hits); + } + (void)shown; + free(qvec); +} + +static void t_kb_delete(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *kb = mcp_arg_string(args, "kb"); + const char *title = mcp_arg_string(args, "title"); + const char *id = mcp_arg_string(args, "id"); + char slug[MAX_KB], name[256]; + char *target = NULL, *path, *leaf; + + (void)user; + if (kb == NULL || *kb == '\0') { + mcp_reply_error(c, "kb_delete needs kb and title (or id)"); + return; + } + slugify(kb, slug, sizeof(slug)); + if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { + say(c, "no knowledge base \"%s\"", kb); + return; + } + target = (id != NULL && *id != '\0') ? strdup(id) : find_by_title(slug, title); + if (target == NULL) { + say(c, "no page \"%s\" in \"%s\"", title != NULL ? title : "", name); + return; + } + { + mcp_buf lb; + + mcp_buf_init(&lb); + mcp_buf_printf(&lb, "%s.json", target); + leaf = lb.p; + } + path = kb_file(slug, leaf != NULL ? leaf : "e.json"); + free(leaf); + if (unlink(path) != 0) { + free(path); + free(target); + mcp_reply_error(c, "could not remove the page file"); + return; + } + free(path); + git_commit("page_delete", target); + say(c, "deleted %s/%s", slug, target); + free(target); +} + +static void t_kb_drop(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *kb = mcp_arg_string(args, "kb"); + const char *confirm = mcp_arg_string(args, "confirm"); + char slug[MAX_KB], name[256]; + char **ids = NULL; + size_t n = 0, i; + char *dir; + mcp_buf cmd; + + (void)user; + if (kb == NULL || *kb == '\0') { + mcp_reply_error(c, "kb_drop needs kb and confirm=\"yes\""); + return; + } + slugify(kb, slug, sizeof(slug)); + if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { + say(c, "no knowledge base \"%s\"", kb); + return; + } + /* Löschen einer ganzen Basis ist nicht rückgängig zu machen — deshalb ein + * ausdrückliches Wort. Ein Tippfehler soll nicht das ganze Wiki entfernen. */ + if (confirm == NULL || strcmp(confirm, "yes") != 0) { + say(c, "not deleting \"%s\": pass confirm=\"yes\". It holds %s.", name, + (kb_entry_ids(slug, &ids, &n) == 0) ? "pages" : "unknown pages"); + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); + return; + } + if (kb_entry_ids(slug, &ids, &n) == 0) { + for (i = 0; i < n; i++) + free(ids[i]); + free(ids); + } + dir = kb_dir(slug); + mcp_buf_init(&cmd); + mcp_buf_printf(&cmd, "rm -rf '%s'", dir != NULL ? dir : ""); + if (system(cmd.p) != 0) { + mcp_buf_free(&cmd); + free(dir); + mcp_reply_error(c, "could not remove the knowledge base directory"); + return; + } + mcp_buf_free(&cmd); + free(dir); + git_commit("wiki_drop", slug); + say(c, "dropped knowledge base \"%s\" (%zu pages removed)", name, n); +} + +/* ------------------------------------------------------------------ table */ + +static const mcp_tool TOOLS[] = { + { "wiki_create", + "Create a named knowledge base - one wiki per subject area (\"olivia-technik\", " + "\"fleet-junction\"), not one per project. Pages inside are written with page_write " + "and found again with wiki_search, by meaning rather than by keyword.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\",\"description\":\"human name, e.g. olivia-technik\"}," + "\"description\":{\"type\":\"string\",\"description\":\"what belongs in here\"}}," + "\"required\":[\"name\"]}", + t_kb_create }, + { "wiki_list", + "Which wikis exist, how many pages each holds and what they are for. Call it before " + "writing so a page lands in the right wiki.", + "{\"type\":\"object\",\"properties\":{}}", + t_kb_list }, + { "page_write", + "Write a page: title plus body. The SAME title in the same wiki updates the page " + "instead of duplicating it, and the previous text stays in the page history - so a " + "correction never loses what was there before. Write what a human would want to read " + "later: procedures, measurements, decisions with their reasoning. Not transcripts.", + "{\"type\":\"object\",\"properties\":{" + "\"kb\":{\"type\":\"string\",\"description\":\"which wiki\"}," + "\"title\":{\"type\":\"string\",\"description\":\"page title; the same title updates it\"}," + "\"text\":{\"type\":\"string\",\"description\":\"the page body\"}," + "\"tags\":{\"type\":\"string\",\"description\":\"comma separated\"}," + "\"source\":{\"type\":\"string\",\"description\":\"who or what this came from\"}}," + "\"required\":[\"kb\",\"title\",\"text\"]}", + t_kb_write }, + { "page_read", + "Read one page in full by title (or id), optionally with its earlier versions - that " + "is how you answer \"what did we decide back then\".", + "{\"type\":\"object\",\"properties\":{" + "\"kb\":{\"type\":\"string\"}," + "\"title\":{\"type\":\"string\"}," + "\"id\":{\"type\":\"string\",\"description\":\"instead of title\"}," + "\"history\":{\"type\":\"boolean\",\"description\":\"include earlier versions\"}}," + "\"required\":[\"kb\"]}", + t_kb_read }, + { "wiki_search", + "Search the wikis by meaning. Without kb it searches all of them and ranks globally, " + "so the best page wins rather than the best page per wiki. This is how you answer " + "\"what does our own documentation say about X\" before asking the human again.", + "{\"type\":\"object\",\"properties\":{" + "\"query\":{\"type\":\"string\"}," + "\"kb\":{\"type\":\"string\",\"description\":\"restrict to one wiki\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"default 5\"}}," + "\"required\":[\"query\"]}", + t_kb_search }, + { "page_list", + "List the pages of one wiki - titles, tags, whether a vector exists, when it last " + "changed. Use it to see what the wiki already covers before writing something new.", + "{\"type\":\"object\",\"properties\":{" + "\"kb\":{\"type\":\"string\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"default 50\"}}," + "\"required\":[\"kb\"]}", + t_kb_entries }, + { "page_delete", + "Delete one page (by title or id). Use it for pages that are wrong or obsolete - two " + "contradicting pages are worse than none. The deletion is committed too, so it can be " + "recovered with git.", + "{\"type\":\"object\",\"properties\":{" + "\"kb\":{\"type\":\"string\"}," + "\"title\":{\"type\":\"string\"}," + "\"id\":{\"type\":\"string\"}}," + "\"required\":[\"kb\"]}", + t_kb_delete }, + { "wiki_drop", + "Delete a whole wiki and every page in it. Needs confirm=\"yes\"; without it the tool " + "only says what would be lost. Undone from git if the wiki directory is a repository.", + "{\"type\":\"object\",\"properties\":{" + "\"kb\":{\"type\":\"string\"}," + "\"confirm\":{\"type\":\"string\",\"description\":\"the word yes, deliberately\"}}," + "\"required\":[\"kb\"]}", + t_kb_drop }, +}; + +int main(int argc, char **argv) +{ + mcp_server srv; + + srv.name = "wikid"; + 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); +}