git: jede Skill-Änderung wird festgeschrieben; HTTP-Modus

skill_create, skill_update, skill_clone und skill_delete committen ihre Änderung
selbst (skilld: create/update/… <name>). Dazu vier Werkzeuge: skill_history,
skill_diff, skill_sync (pull --rebase, push:true für die Gegenrichtung).

Ist die Bibliothek kein Repository, behauptet das Werkzeug keinen Verlauf,
sondern sagt es; beim Start steht im Log, in welchem Modus skilld läuft.

Dazu --http PORT über den gemeinsamen Transport aus libmcp.

tests/git.py legt ein echtes Repo mit bare-Remote an und prüft fünf Fälle,
darunter eine Änderung von Hand, die der nächste Schreibvorgang mitschreibt.
This commit is contained in:
Hermes committed 2026-11-06 19:03:15 +00:00
1 parent ad002ecfa5
commit c1c2ca0ef2
8 files changed
+839 -8

No files matched your search

+3 -2
View File
@@ -5,11 +5,12 @@ PREFIX ?= /usr/local
all: skilld
skilld: skilld.c $(LIBDIR)/mcp.h
$(CC) $(CFLAGS) -I$(LIBDIR) -o $@ skilld.c
skilld: skilld.c skilld_git.c skilld_git.h $(LIBDIR)/mcp.h
$(CC) $(CFLAGS) -I$(LIBDIR) -o $@ skilld.c skilld_git.c
test: skilld
./tests/run.sh
./tests/git.py
install: skilld
mkdir -p $(DESTDIR)$(PREFIX)/bin
+37
View File
@@ -13,6 +13,43 @@ make test
The binary speaks MCP over stdio, so it is registered as an MCP server, not
started by hand.
## Git is the substrate
Every write through skilld is committed: `skill_create`, `skill_update`,
`skill_clone` and `skill_delete` end with a commit under the skill's own message
(`skilld: update <name>`). A skill written by one agent and corrected by another
keeps both, and `git log` answers who changed what and when.
```sh
git -C "$SKILLLIB" init
git -C "$SKILLLIB" remote add origin <somewhere>
```
Four tools come with it:
| tool | what it does |
|---|---|
| `skill_history` | commits for one skill or the whole library |
| `skill_diff` | what was changed outside skilld and is not committed yet |
| `skill_sync` | `pull --rebase` from the remote; `push: true` sends instead |
| (automatic) | a write whose working tree is dirty commits the change with it |
Is the library *not* a repository, nothing breaks: the tools say so instead of
pretending, and skilld prints at start which mode it is in. Version control that
silently does nothing is worse than none.
## HTTP
```sh
skilld # MCP over stdin/stdout
skilld --http 8790 # same tools over Streamable HTTP
skilld --http :8790 # ... on every address
```
The HTTP server lives in libmcp (`mcp_serve_http`), so tasksd and skilld share
one implementation instead of two copies.
## Dependency: libmcp
`vendor/libmcp/mcp.h` is a copy of the header from the `libmcp` repository, so
+164 -2
View File
@@ -12,7 +12,8 @@
* <name>/<anything> references, scripts, templates
*/
#define MCP_IMPLEMENTATION
#include "../libmcp/mcp.h"
#include "mcp.h"
#include "skilld_git.h"
#include <ctype.h>
#include <dirent.h>
@@ -25,6 +26,34 @@
#include <sys/types.h>
#include <unistd.h>
/* ------------------------------------------------------------------ git */
/* Jede Änderung an einer Fähigkeit wird festgeschrieben. Ohne Historie gibt es
* keine Antwort auf "wer hat das geändert"; ohne Abgleich überschreibt ein Agent
* die Arbeit des anderen. Ist das Verzeichnis kein Repository, bleibt alles wie
* vorher — dann steht es wenigstens im Log, statt still zu passieren. */
static void autocommit(const char *dir, const char *fmt, ...)
{
char msg[256];
char err[256];
char *hash = NULL;
va_list ap;
int rc;
if (!skilld_git_present(dir))
return;
va_start(ap, fmt);
vsnprintf(msg, sizeof msg, fmt, ap);
va_end(ap);
rc = skilld_git_commit(dir, ".", msg, err, sizeof err, &hash);
if (rc == 0)
fprintf(stderr, "skilld: committed %s (%s)\n", msg, hash ? hash : "?");
else if (rc < 0)
fprintf(stderr, "skilld: commit failed: %s\n", err);
free(hash);
}
/* ------------------------------------------------------------------ paths */
static char *skilllib_path(void)
@@ -530,6 +559,7 @@ static void t_create(mcp_conn *c, const mcp_json *args, void *user)
free(dir);
return;
}
autocommit(dir, "skilld: create %s", name);
mcp_buf_init(&msg);
mcp_buf_printf(&msg, "created '%s' at %s", name, dir);
mcp_reply_text(c, msg.p);
@@ -646,6 +676,12 @@ static void t_update(mcp_conn *c, const mcp_json *args, void *user)
free(rest);
skill_free(&s);
if (rc == 0) {
char *d = skill_dir(name);
autocommit(d, "skilld: update %s", name);
free(d);
}
mcp_buf_init(&msg);
if (rc != 0)
mcp_buf_printf(&msg, "cannot write '%s'", name);
@@ -800,6 +836,94 @@ static void t_assign(mcp_conn *c, const mcp_json *args, void *user)
free(dir);
}
/* ------------------------------------------------------------------ git tools */
static void t_history(mcp_conn *c, const mcp_json *args, void *user)
{
const char *name = mcp_arg_string(args, "name");
int limit = mcp_arg_int(args, "limit", 20);
char *lib = skilllib_path();
char *dir = NULL;
char *log;
(void)user;
if (name && *name && valid_name(name)) {
dir = skill_dir(name);
} else {
dir = strdup(lib);
}
if (!skilld_git_present(dir)) {
mcp_reply_error(c, "the skill library is not a git repository "
"(git init in SKILLLIB, then commit once)");
free(lib);
free(dir);
return;
}
log = skilld_git_log(dir, ".", limit);
mcp_reply_text(c, (log && *log) ? log : "no commits yet");
free(log);
free(dir);
free(lib);
}
static void t_diff(mcp_conn *c, const mcp_json *args, void *user)
{
const char *name = mcp_arg_string(args, "name");
char *lib = skilllib_path();
char *dir;
(void)user;
dir = (name && *name && valid_name(name)) ? skill_dir(name) : strdup(lib);
if (!skilld_git_present(dir)) {
mcp_reply_error(c, "the skill library is not a git repository");
free(lib);
free(dir);
return;
}
char *d = skilld_git_diff(dir, ".");
mcp_reply_text(c, (d && *d) ? d : "nothing uncommitted");
free(d);
free(dir);
free(lib);
}
static void t_sync(mcp_conn *c, const mcp_json *args, void *user)
{
int push = mcp_arg_bool(args, "push", 0);
char err[512];
char *lib = skilllib_path();
char *out;
mcp_buf msg;
char *before, *after;
(void)user;
if (!skilld_git_present(lib)) {
mcp_reply_error(c, "the skill library is not a git repository");
free(lib);
return;
}
before = skilld_git_head(lib);
out = skilld_git_sync(lib, push, err, sizeof err);
after = skilld_git_head(lib);
mcp_buf_init(&msg);
if (out == NULL) {
mcp_buf_printf(&msg, "git %s failed: %s", push ? "push" : "pull", err);
mcp_reply_error(c, msg.p);
} else {
mcp_buf_printf(&msg, "%s: %s -> %s\n%s",
push ? "pushed" : "pulled",
before ? before : "?", after ? after : "?",
*out ? out : "(no output)");
mcp_reply_text(c, msg.p);
}
mcp_buf_free(&msg);
free(out);
free(before);
free(after);
free(lib);
}
/* ------------------------------------------------------------------ table */
static const mcp_tool TOOLS[] = {
@@ -867,6 +991,28 @@ static const mcp_tool TOOLS[] = {
"\"profile\":{\"type\":\"string\",\"description\":\"Profile name on this host\"}},"
"\"required\":[\"name\",\"profile\"]}",
t_assign },
{ "skill_history",
"Show how a skill changed over time: commits with hash, date, author and "
"message. Use before editing something you did not write, and after a "
"correction to see whether the error came back before.",
"{\"type\":\"object\",\"properties\":{"
"\"name\":{\"type\":\"string\",\"description\":\"Skill; omit for the whole library\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"Max commits, default 20\"}}}",
t_history },
{ "skill_diff",
"What is changed in the working tree but not yet committed. Every write "
"through skilld commits itself, so anything here was changed outside skilld "
"or by hand.",
"{\"type\":\"object\",\"properties\":{"
"\"name\":{\"type\":\"string\",\"description\":\"Skill; omit for the whole library\"}}}",
t_diff },
{ "skill_sync",
"Pull the library from its remote (fast-forward via rebase) so this host sees "
"what the others wrote. With push=true, send local commits back instead. Use "
"at the start of a session on a machine that has been offline.",
"{\"type\":\"object\",\"properties\":{"
"\"push\":{\"type\":\"boolean\",\"description\":\"true = push instead of pull\"}}}",
t_sync },
{ "skill_delete",
"Remove a skill from the library. This deletes the directory and does not "
"ask twice.",
@@ -876,7 +1022,7 @@ static const mcp_tool TOOLS[] = {
t_delete },
};
int main(void)
int main(int argc, char **argv)
{
mcp_server srv;
@@ -885,5 +1031,21 @@ int main(void)
srv.tools = TOOLS;
srv.ntools = sizeof(TOOLS) / sizeof(TOOLS[0]);
srv.user = NULL;
{
char *lib = skilllib_path();
fprintf(stderr, "skilld: library %s (%s)\n", lib,
skilld_git_present(lib) ? "git" : "no git — changes are not versioned");
free(lib);
}
if (argc >= 3 && strcmp(argv[1], "--http") == 0) {
int port = mcp_parse_port(argv[2]);
if (port < 0)
return 2;
return mcp_serve_http(&srv, NULL, port);
}
return mcp_serve_stdio(&srv);
}
+232
View File
@@ -0,0 +1,232 @@
/* git.c — Git als Unterbau für die Skill-Bibliothek.
*
* Warum Git und nicht einfach Dateien: eine Fähigkeit wird von mehreren Agenten
* auf mehreren Rechnern geändert. Ohne Historie gibt es keine Antwort auf "wer hat
* das geändert und warum", und ohne Abgleich überschreibt der eine die Arbeit des
* anderen. Also: jede Änderung wird festgeschrieben, die Bibliothek lässt sich
* ziehen und schieben, und der Verlauf ist abfragbar.
*
* Kein libgit2: git wird über popen aufgerufen, wie tgagent curl aufruft. Eine
* Abhängigkeit weniger, und das Programm, das die Arbeit macht, ist dasselbe, das
* der Mensch benutzt.
*/
/* popen braucht POSIX, bevor irgendein Header kommt. */
#define _POSIX_C_SOURCE 200809L
#include "skilld_git.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Ein Argument für die Shell unschädlich machen. */
static void sh_quote(mcp_buf *b, const char *s)
{
mcp_buf_puts(b, "'");
for (const char *p = s; *p; p++) {
if (*p == '\'')
mcp_buf_puts(b, "'\\''");
else
mcp_buf_add(b, p, 1);
}
mcp_buf_puts(b, "'");
}
/* Kommando ausführen, Ausgabe einsammeln. NULL, wenn popen scheitert. */
static char *run_capture(const char *cmd, int *status_out)
{
FILE *f = popen(cmd, "r");
mcp_buf out;
char tmp[4096];
size_t n;
int st = -1;
if (status_out)
*status_out = -1;
if (!f)
return NULL;
mcp_buf_init(&out);
while ((n = fread(tmp, 1, sizeof tmp, f)) > 0)
mcp_buf_add(&out, tmp, n);
st = pclose(f);
if (status_out)
*status_out = st;
if (out.p == NULL)
return strdup("");
return out.p;
}
int skilld_git_present(const char *dir)
{
mcp_buf cmd;
char *out;
int st;
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " rev-parse --git-dir 2>/dev/null");
out = run_capture(cmd.p, &st);
mcp_buf_free(&cmd);
int ok = (st == 0 && out && *out != '\0');
free(out);
return ok;
}
char *skilld_git_head(const char *dir)
{
mcp_buf cmd;
char *out;
int st;
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " rev-parse --short HEAD 2>/dev/null");
out = run_capture(cmd.p, &st);
mcp_buf_free(&cmd);
if (st != 0 || !out) {
free(out);
return NULL;
}
char *nl = strchr(out, '\n');
if (nl)
*nl = '\0';
return out;
}
/* Eine Änderung festschreiben. 0 = festgeschrieben, 1 = nichts zu tun,
* -1 = Fehler (die Meldung steht in err). */
int skilld_git_commit(const char *dir, const char *path, const char *message,
char *err, size_t errlen, char **hash_out)
{
mcp_buf cmd;
char *out;
int st;
if (hash_out)
*hash_out = NULL;
/* Erst prüfen, ob es überhaupt etwas zu schreiben gibt: ein leerer Commit
* ist ein Fehler, und ein Fehler nach jeder Änderung macht die Werkzeuge
* unbrauchbar. */
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " status --porcelain -- ");
sh_quote(&cmd, path);
out = run_capture(cmd.p, &st);
mcp_buf_free(&cmd);
if (out == NULL) {
snprintf(err, errlen, "git status failed");
return -1;
}
if (*out == '\0') {
free(out);
return 1;
}
free(out);
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " add -A -- ");
sh_quote(&cmd, path);
mcp_buf_puts(&cmd, " && git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " -c user.name=");
sh_quote(&cmd, "skilld");
mcp_buf_puts(&cmd, " -c user.email=");
sh_quote(&cmd, "skilld@local");
mcp_buf_puts(&cmd, " commit -q -m ");
sh_quote(&cmd, message);
mcp_buf_puts(&cmd, " 2>&1");
out = run_capture(cmd.p, &st);
mcp_buf_free(&cmd);
if (st != 0) {
snprintf(err, errlen, "%s", out ? out : "commit failed");
char *nl = strchr(err, '\n');
if (nl)
*nl = '\0';
free(out);
return -1;
}
free(out);
if (hash_out)
*hash_out = skilld_git_head(dir);
return 0;
}
char *skilld_git_log(const char *dir, const char *path, int limit)
{
mcp_buf cmd;
char *out;
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " log -n ");
mcp_buf_printf(&cmd, "%d", limit <= 0 ? 20 : limit);
mcp_buf_puts(&cmd, " --format='%h %ad %an %s' --date=short");
if (path && *path) {
mcp_buf_puts(&cmd, " -- ");
sh_quote(&cmd, path);
}
mcp_buf_puts(&cmd, " 2>&1");
out = run_capture(cmd.p, NULL);
mcp_buf_free(&cmd);
return out;
}
char *skilld_git_diff(const char *dir, const char *path)
{
mcp_buf cmd;
char *out;
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " status --short");
if (path && *path) {
mcp_buf_puts(&cmd, " -- ");
sh_quote(&cmd, path);
}
mcp_buf_puts(&cmd, " 2>&1; git -C ");
sh_quote(&cmd, dir);
mcp_buf_puts(&cmd, " diff --stat");
if (path && *path) {
mcp_buf_puts(&cmd, " -- ");
sh_quote(&cmd, path);
}
mcp_buf_puts(&cmd, " 2>&1");
out = run_capture(cmd.p, NULL);
mcp_buf_free(&cmd);
return out;
}
char *skilld_git_sync(const char *dir, int push, char *err, size_t errlen)
{
mcp_buf cmd;
char *out;
int st;
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "git -C ");
sh_quote(&cmd, dir);
if (push)
mcp_buf_puts(&cmd, " push 2>&1");
else
mcp_buf_puts(&cmd, " pull --rebase 2>&1");
out = run_capture(cmd.p, &st);
mcp_buf_free(&cmd);
if (st != 0) {
snprintf(err, errlen, "%s", out ? out : "git failed");
free(out);
return NULL;
}
return out ? out : strdup("");
}
+29
View File
@@ -0,0 +1,29 @@
/* skilld_git.h — Git als Unterbau für Skill-Updates. */
#ifndef SKILLD_GIT_H
#define SKILLD_GIT_H
#include "mcp.h"
#include <stddef.h>
/* Ist das Verzeichnis ein Git-Repository? 1 = ja. */
int skilld_git_present(const char *dir);
/* Kurzer HEAD-Hash oder NULL. */
char *skilld_git_head(const char *dir);
/* Änderungen unterhalb von path festschreiben.
* 0 = festgeschrieben (hash_out gesetzt), 1 = nichts zu tun, -1 = Fehler. */
int skilld_git_commit(const char *dir, const char *path, const char *message,
char *err, size_t errlen, char **hash_out);
/* Verlauf (malloc) — ganze Bibliothek oder ein Pfad. */
char *skilld_git_log(const char *dir, const char *path, int limit);
/* Unfestgeschriebene Änderungen (Status und Kurzstatistik, malloc). */
char *skilld_git_diff(const char *dir, const char *path);
/* pull --rebase bzw. push. NULL bei Fehler, sonst die Ausgabe. */
char *skilld_git_sync(const char *dir, int push, char *err, size_t errlen);
#endif /* SKILLD_GIT_H */
Executable
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""skilld muss Git benutzen: jede Änderung festgeschrieben, Verlauf abfragbar.
Der Test legt ein leeres Repository an, hängt ein bare-Repo als "remote" daneben
und prüft über MCP:
1. Anlegen einer Fähigkeit erzeugt einen Commit
2. Ändern erzeugt einen zweiten Commit, der Verlauf nennt beide
3. skill_diff zeigt, was von Hand geändert wurde, und der nächste skilld-Schreib-
vorgang schreibt es mit fest
4. skill_sync --push bringt die Commits ins Remote
5. ohne Repository sagt skilld ehrlich, dass nichts versioniert wird
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
BIN = os.path.join(HERE, "..", "skilld")
failures = []
def call(payload, n=1):
p = subprocess.run([BIN], input=json.dumps(payload) + "\n",
capture_output=True, text=True, env=os.environ.copy(), timeout=60)
lines = [l for l in p.stdout.splitlines() if l.strip()]
if len(lines) < n:
raise RuntimeError(f"keine Antwort: rc={p.returncode} err={p.stderr[-300:]}")
return [json.loads(l) for l in lines[:n]]
def tool(name, args, lib):
env = os.environ.copy()
env["SKILLLIB"] = lib
p = subprocess.run([BIN], input=json.dumps({
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": name, "arguments": args}}) + "\n",
capture_output=True, text=True, env=env, timeout=120)
line = [l for l in p.stdout.splitlines() if l.strip()]
if not line:
raise RuntimeError(f"keine Antwort auf {name}: {p.stderr[-300:]}")
d = json.loads(line[0])
if "error" in d:
return {"error": d["error"]}
content = d["result"].get("content", [])
return {"text": "".join(c.get("text", "") for c in content),
"isError": bool(d["result"].get("isError"))}
def git(lib, *args):
return subprocess.run(["git", "-C", lib] + list(args), capture_output=True, text=True)
def main():
work = tempfile.mkdtemp(prefix="skilld-git-")
lib = os.path.join(work, "skilllib")
remote = os.path.join(work, "remote.git")
os.makedirs(lib)
git(lib, "init", "-q")
git(lib, "config", "user.name", "test")
git(lib, "config", "user.email", "test@local")
git(lib, "branch", "-M", "main")
git(lib, "commit", "-q", "--allow-empty", "-m", "empty")
subprocess.run(["git", "init", "-q", "--bare", remote], check=True)
git(lib, "remote", "add", "origin", remote)
git(lib, "push", "-q", "-u", "origin", "HEAD:main")
try:
# 1. Anlegen -> Commit
r = tool("skill_create", {"name": "git-probe", "description": "Use when testing git",
"body": "# Zweck\nPrüfen.\n"}, lib)
if r.get("isError"):
failures.append(f"skill_create: {r}")
n = git(lib, "rev-list", "--count", "HEAD").stdout.strip()
if n != "2":
failures.append(f"nach dem Anlegen stehen {n} Commits statt 2")
# 2. Ändern -> zweiter Commit
r = tool("skill_update", {"name": "git-probe", "append": "\n## Neu\nMehr.\n"}, lib)
if r.get("isError"):
failures.append(f"skill_update: {r}")
n = git(lib, "rev-list", "--count", "HEAD").stdout.strip()
if n != "3":
failures.append(f"nach dem Ändern stehen {n} Commits statt 3")
r = tool("skill_history", {"name": "git-probe"}, lib)
text = r.get("text", "")
if "create git-probe" not in text or "update git-probe" not in text:
failures.append(f"Verlauf nennt die Änderungen nicht: {text[:200]}")
# 3. Änderung von Hand -> skill_diff sieht sie, der nächste Schreibvorgang nimmt sie mit
with open(os.path.join(lib, "git-probe", "SKILL.md"), "a") as f:
f.write("\n## Von Hand\n")
r = tool("skill_diff", {"name": "git-probe"}, lib)
if "SKILL.md" not in r.get("text", ""):
failures.append(f"skill_diff zeigt die Änderung nicht: {r}")
tool("skill_update", {"name": "git-probe", "append": "\n## Nochwas\n"}, lib)
st = git(lib, "status", "--porcelain").stdout.strip()
if st:
failures.append(f"nach dem Schreiben bleibt etwas offen: {st}")
# 4. Abgleich mit dem Remote
r = tool("skill_sync", {"push": True}, lib)
if r.get("isError"):
failures.append(f"skill_sync push: {r}")
log_remote = subprocess.run(["git", "-C", remote, "log", "--oneline", "main"],
capture_output=True, text=True).stdout
if "update git-probe" not in log_remote:
failures.append(f"das Remote kennt die Änderung nicht: {log_remote[:200]}")
# 5. ohne Repository ehrlich bleiben
plain = os.path.join(work, "plainlib")
os.makedirs(plain)
r = tool("skill_history", {}, plain)
if not r.get("isError"):
failures.append(f"ohne Repository wurde trotzdem ein Verlauf behauptet: {r.get('text','')[:120]}")
finally:
shutil.rmtree(work, ignore_errors=True)
if failures:
print("FAIL")
for f in failures:
print(" -", f)
sys.exit(1)
print("PASS: 5 Prüfungen — Commit beim Anlegen, Commit beim Ändern, Verlauf, "
"Handänderung erkannt und mitgeschrieben, Push ins Remote, ehrlich ohne Repo")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -79,7 +79,7 @@ check("initialize names skilld",
tools = by_id.get(2, {}).get("result", {}).get("tools", [])
names = {t["name"] for t in tools}
check("eight tools advertised", len(tools) == 8, sorted(names))
check("eleven tools advertised", len(tools) == 11, sorted(names))
check("search description carries the trigger",
any("skill_search" == t["name"] and len(t["description"]) > 200 for t in tools))
+239 -3
View File
@@ -1,3 +1,6 @@
#ifndef MCP_H
#define MCP_H
/*
* libmcp - a minimal Model Context Protocol server in C99 + POSIX.
*
@@ -34,8 +37,6 @@
* A tool that does not reply gets an error reply from the library, so a
* forgotten branch cannot make a client hang.
*/
#ifndef MCP_H
#define MCP_H
#include <stddef.h>
@@ -83,6 +84,18 @@ typedef struct {
/* 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). */
@@ -142,18 +155,29 @@ char *mcp_handle(mcp_server *srv, const char *line);
}
#endif
#endif /* MCP_H */
/* ===========================================================================
* implementation
* =========================================================================== */
#ifdef MCP_IMPLEMENTATION
#ifndef MCP_MAX_BODY
#define MCP_MAX_BODY (8u * 1024u * 1024u)
#endif
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#ifndef MCP_MAX_TOOLS
#define MCP_MAX_TOOLS 128
@@ -895,4 +919,216 @@ int mcp_serve_stdio(mcp_server *srv)
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;
}
/* fork per connection: without this every finished child stays a zombie */
signal(SIGCHLD, SIG_IGN);
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) {
close(ls);
mcp_http_serve_one(fd, srv, session);
_exit(0);
}
if (pid > 0)
close(fd);
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 */