commit e7b3801cad4a58537489dc33e574903636155f55 Author: Konrad Date: Fri Nov 6 17:59:15 2026 +0000 skilld: initial import diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..623b377 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.o +skilld diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2e489ee --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +CC ?= cc +CFLAGS ?= -std=c99 -O2 -Wall -Wextra +LIBDIR ?= ../libmcp +PREFIX ?= /usr/local + +all: skilld + +skilld: skilld.c $(LIBDIR)/mcp.h + $(CC) $(CFLAGS) -I$(LIBDIR) -o $@ skilld.c + +test: skilld + ./tests/run.sh + +install: skilld + mkdir -p $(DESTDIR)$(PREFIX)/bin + cp skilld $(DESTDIR)$(PREFIX)/bin/ + +clean: + rm -f skilld + +.PHONY: all test install clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..4036291 --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# skilld + +MCP server for the skill library, written in C99/POSIX. + +Eight tools over the standard MCP surface: list, search, read, write and +inspect `SKILL.md` files under `$SKILLS_DIR`. Built on `libmcp` (header-only). + +```sh +make +make test +``` + +The binary speaks MCP over stdio, so it is registered as an MCP server, not +started by hand. diff --git a/skilld.c b/skilld.c new file mode 100644 index 0000000..1918c34 --- /dev/null +++ b/skilld.c @@ -0,0 +1,889 @@ +/* strtok_r, strdup, strndup are POSIX; ask for them before any header. */ +#define _POSIX_C_SOURCE 200809L + +/* + * skilld - the fleet's skill library, served over MCP. + * + * Built on libmcp (../libmcp/mcp.h): this file owns storage and the tool + * handlers, the library owns the protocol. + * + * Storage: $SKILLLIB (default ~/.hermes/skilllib) + * /SKILL.md YAML frontmatter + markdown body + * / references, scripts, templates + */ +#define MCP_IMPLEMENTATION +#include "../libmcp/mcp.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* ------------------------------------------------------------------ paths */ + +static char *skilllib_path(void) +{ + const char *env = getenv("SKILLLIB"); + 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/skilllib", home); + return b.p; +} + +static int is_dir(const char *path) +{ + struct stat st; + + return stat(path, &st) == 0 && S_ISDIR(st.st_mode); +} + +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(const char *path, const char *data) +{ + FILE *f = fopen(path, "wb"); + size_t len = strlen(data); + + if (f == NULL) + return -1; + if (len > 0 && fwrite(data, 1, len, f) != len) { + fclose(f); + return -1; + } + return fclose(f); +} + +static int mkdir_p(const char *path) +{ + char tmp[PATH_MAX]; + size_t i, len; + + if (strlen(path) >= sizeof(tmp)) + return -1; + strcpy(tmp, path); + len = strlen(tmp); + for (i = 1; i < len; i++) { + if (tmp[i] != '/') + continue; + tmp[i] = '\0'; + if (!is_dir(tmp) && mkdir(tmp, 0755) != 0 && errno != EEXIST) + return -1; + tmp[i] = '/'; + } + if (!is_dir(tmp) && mkdir(tmp, 0755) != 0 && errno != EEXIST) + return -1; + return 0; +} + +static int valid_name(const char *name) +{ + const char *p; + + if (name == NULL || *name == '\0' || strlen(name) > 100) + return 0; + if (strstr(name, "..") != NULL) + return 0; + for (p = name; *p; p++) + if (!isalnum((unsigned char)*p) && *p != '-' && *p != '_' && *p != '.') + return 0; + return 1; +} + +static char *skill_dir(const char *name) +{ + char *base = skilllib_path(); + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s/%s", base, name); + free(base); + return b.p; +} + +static char *skill_file(const char *name) +{ + char *dir = skill_dir(name); + mcp_buf b; + + mcp_buf_init(&b); + mcp_buf_printf(&b, "%s/SKILL.md", dir); + free(dir); + return b.p; +} + +/* ------------------------------------------------------------------ skills */ + +struct skill { + char *name; + char *desc; + char *tags; + char *body; +}; + +static void skill_free(struct skill *s) +{ + free(s->name); + free(s->desc); + free(s->tags); + free(s->body); +} + +static void parse_frontmatter(struct skill *s, const char *text) +{ + const char *p = text; + const char *end; + const char *line; + + s->desc = strdup(""); + s->tags = strdup(""); + if (strncmp(p, "---", 3) != 0) + return; + p += 3; + while (*p == '\n') + p++; + end = strstr(p, "\n---"); + if (end == NULL) + return; + line = p; + while (line < end) { + const char *eol = memchr(line, '\n', (size_t)(end - line)); + size_t n = eol ? (size_t)(eol - line) : (size_t)(end - line); + const char *colon = memchr(line, ':', n); + + if (colon != NULL) { + size_t klen = (size_t)(colon - line); + const char *v = colon + 1; + const char *vstart; + size_t vlen; + + while (klen > 0 && isspace((unsigned char)line[klen - 1])) + klen--; + while (*v == ' ') + v++; + vstart = v; + vlen = (size_t)((line + n) - v); + if (vlen >= 2 && (v[0] == '"' || v[0] == '\'') && v[vlen - 1] == v[0]) { + vstart++; + vlen -= 2; + } + if (klen == 11 && strncmp(line, "description", 11) == 0) { + free(s->desc); + s->desc = strndup(vstart, vlen); + } else if (klen == 4 && strncmp(line, "tags", 4) == 0) { + free(s->tags); + s->tags = strndup(vstart, vlen); + } + } + line += n; + if (line < end) + line++; + } +} + +static int load_skill(const char *name, struct skill *out) +{ + char *path; + const char *body; + + memset(out, 0, sizeof(*out)); + if (!valid_name(name)) + return -1; + path = skill_file(name); + body = read_file(path); + free(path); + if (body == NULL) + return -1; + out->body = (char *)body; + out->name = strdup(name); + parse_frontmatter(out, out->body); + return 0; +} + +static int cmp_skill(const void *a, const void *b) +{ + return strcmp(((const struct skill *)a)->name, ((const struct skill *)b)->name); +} + +static size_t list_skills(struct skill **outp) +{ + char *base = skilllib_path(); + DIR *d = opendir(base); + struct dirent *e; + struct skill *arr = NULL; + size_t n = 0; + + *outp = NULL; + if (d == NULL) { + free(base); + return 0; + } + while ((e = readdir(d)) != NULL) { + struct skill s; + + if (e->d_name[0] == '.' || !valid_name(e->d_name)) + continue; + if (load_skill(e->d_name, &s) != 0) + continue; + arr = realloc(arr, (n + 1) * sizeof(*arr)); + if (arr == NULL) { + skill_free(&s); + break; + } + arr[n++] = s; + } + closedir(d); + free(base); + if (n > 1) + qsort(arr, n, sizeof(*arr), cmp_skill); + *outp = arr; + return n; +} + +static void free_skills(struct skill *arr, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) + skill_free(&arr[i]); + free(arr); +} + +static int icontains(const char *hay, const char *needle) +{ + size_t nl = strlen(needle); + const char *p; + + if (nl == 0 || hay == NULL) + return 0; + 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 1; + } + return 0; +} + +static int score_skill(const struct skill *s, char **words, size_t nwords) +{ + int score = 0; + size_t i; + + for (i = 0; i < nwords; i++) { + if (icontains(s->name, words[i])) + score += 10; + if (icontains(s->desc, words[i])) + score += 5; + if (icontains(s->tags, words[i])) + score += 4; + if (icontains(s->body, words[i])) + score += 1; + } + return score; +} + +/* ------------------------------------------------------------------ tools */ + +static void put_skill(mcp_buf *b, const struct skill *s, int score, int with_body) +{ + mcp_buf_puts(b, "{\"name\":\""); + mcp_json_escape(b, s->name); + mcp_buf_puts(b, "\",\"description\":\""); + mcp_json_escape(b, s->desc); + mcp_buf_puts(b, "\""); + if (s->tags != NULL && *s->tags != '\0') { + mcp_buf_puts(b, ",\"tags\":\""); + mcp_json_escape(b, s->tags); + mcp_buf_puts(b, "\""); + } + if (with_body) { + mcp_buf_puts(b, ",\"content\":\""); + mcp_json_escape(b, s->body); + mcp_buf_puts(b, "\""); + } + if (score >= 0) + mcp_buf_printf(b, ",\"score\":%d", score); + mcp_buf_puts(b, "}"); +} + +static void t_search(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *query = mcp_arg_string(args, "query"); + int limit = mcp_arg_int(args, "limit", 10); + struct skill *arr; + size_t n, i; + char *words[32]; + size_t nwords = 0; + char *copy; + char *tok; + char *save = NULL; + mcp_buf out, ids; + size_t *ranked; + int *scores; + size_t nr = 0; + + (void)user; + if (query == NULL) + query = ""; + if (limit <= 0 || limit > 50) + limit = 10; + + copy = strdup(query); + for (tok = strtok_r(copy, " \t,.;:-/", &save); + tok != NULL && nwords < 32; + tok = strtok_r(NULL, " \t,.;:-/", &save)) { + if (strlen(tok) >= 2) + words[nwords++] = tok; + } + + n = list_skills(&arr); + ranked = calloc(n + 1, sizeof(*ranked)); + scores = calloc(n + 1, sizeof(*scores)); + for (i = 0; i < n; i++) { + int sc = nwords == 0 ? 1 : score_skill(&arr[i], words, nwords); + + if (sc > 0) { + ranked[nr] = i; + scores[nr] = sc; + nr++; + } + } + /* insertion sort, best first */ + for (i = 1; i < nr; i++) { + size_t j = i; + + while (j > 0 && scores[j - 1] < scores[j]) { + size_t ti = ranked[j - 1]; + int ts = scores[j - 1]; + + ranked[j - 1] = ranked[j]; + scores[j - 1] = scores[j]; + ranked[j] = ti; + scores[j] = ts; + j--; + } + } + + mcp_buf_init(&ids); + mcp_buf_puts(&ids, "{\"query\":\""); + mcp_json_escape(&ids, query); + mcp_buf_printf(&ids, "\",\"total\":%lu,\"results\":[", (unsigned long)n); + { + int emitted = 0; + + for (i = 0; i < nr && emitted < limit; i++) { + if (emitted > 0) + mcp_buf_puts(&ids, ","); + put_skill(&ids, &arr[ranked[i]], scores[i], 0); + emitted++; + } + } + mcp_buf_puts(&ids, "]}"); + mcp_reply_json(c, ids.p); + mcp_buf_free(&ids); + out = ids; + free(ranked); + free(scores); + free(copy); + free_skills(arr, n); + (void)out; +} + +static void t_load(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *name = mcp_arg_string(args, "name"); + struct skill s; + + (void)user; + if (!valid_name(name)) { + mcp_reply_error(c, "invalid skill name"); + return; + } + if (load_skill(name, &s) != 0) { + mcp_buf e; + + mcp_buf_init(&e); + mcp_buf_printf(&e, "no such skill: %s", name); + mcp_reply_error(c, e.p); + mcp_buf_free(&e); + return; + } + mcp_reply_text(c, s.body); + skill_free(&s); +} + +static void t_list(mcp_conn *c, const mcp_json *args, void *user) +{ + struct skill *arr; + size_t n, i; + mcp_buf out; + + (void)args; + (void)user; + n = list_skills(&arr); + mcp_buf_init(&out); + mcp_buf_printf(&out, "{\"total\":%lu,\"skills\":[", (unsigned long)n); + for (i = 0; i < n; i++) { + if (i > 0) + mcp_buf_puts(&out, ","); + put_skill(&out, &arr[i], -1, 0); + } + mcp_buf_puts(&out, "]}"); + mcp_reply_json(c, out.p); + mcp_buf_free(&out); + free_skills(arr, n); +} + +static void t_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"); + const char *body = mcp_arg_string(args, "body"); + const char *tags = mcp_arg_string(args, "tags"); + char *dir, *path, *base; + mcp_buf md, msg; + int rc; + + (void)user; + if (!valid_name(name)) { + mcp_reply_error(c, "name must be [A-Za-z0-9._-], at most 100 chars"); + return; + } + dir = skill_dir(name); + if (is_dir(dir)) { + mcp_buf_init(&msg); + mcp_buf_printf(&msg, "skill '%s' already exists (use skill_update)", name); + mcp_reply_error(c, msg.p); + mcp_buf_free(&msg); + free(dir); + return; + } + base = skilllib_path(); + mkdir_p(base); + free(base); + if (mkdir_p(dir) != 0) { + mcp_reply_error(c, "cannot create the skill directory"); + free(dir); + return; + } + mcp_buf_init(&md); + mcp_buf_puts(&md, "---\nname: "); + mcp_buf_puts(&md, name); + mcp_buf_puts(&md, "\ndescription: "); + mcp_buf_puts(&md, (desc && *desc) ? desc : "TODO: what this skill is for"); + if (tags && *tags) { + mcp_buf_puts(&md, "\ntags: "); + mcp_buf_puts(&md, tags); + } + mcp_buf_puts(&md, "\n---\n\n"); + if (body && *body) { + mcp_buf_puts(&md, body); + } else { + mcp_buf_puts(&md, "# "); + mcp_buf_puts(&md, name); + } + if (md.len > 0 && md.p[md.len - 1] != '\n') + mcp_buf_puts(&md, "\n"); + + path = skill_file(name); + rc = write_file(path, md.p); + free(path); + mcp_buf_free(&md); + if (rc != 0) { + mcp_reply_error(c, "cannot write SKILL.md"); + free(dir); + return; + } + mcp_buf_init(&msg); + mcp_buf_printf(&msg, "created '%s' at %s", name, dir); + mcp_reply_text(c, msg.p); + mcp_buf_free(&msg); + free(dir); +} + +/* Split an existing SKILL.md into frontmatter and body. */ +static void split_skill(const char *text, char **fm, char **body) +{ + const char *end = NULL; + + *fm = NULL; + *body = NULL; + if (strncmp(text, "---", 3) == 0) { + end = strstr(text + 3, "\n---"); + if (end != NULL) { + size_t n = (size_t)((end + 4) - text); + + *fm = strndup(text, n); + *body = strdup(end + 4); + return; + } + } + *fm = strdup(""); + *body = strdup(text); +} + +static void t_update(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"); + const char *body = mcp_arg_string(args, "body"); + const char *append = mcp_arg_string(args, "append"); + struct skill s; + char *fm = NULL, *rest = NULL, *path; + mcp_buf md, msg; + int rc; + + (void)user; + if (!valid_name(name) || load_skill(name, &s) != 0) { + mcp_reply_error(c, "no such skill"); + return; + } + if (desc == NULL && body == NULL && append == NULL) { + mcp_reply_error(c, "nothing to update: give description, body or append"); + skill_free(&s); + return; + } + split_skill(s.body, &fm, &rest); + + mcp_buf_init(&md); + if (desc != NULL) { + /* rewrite the description line, keep every other frontmatter line */ + const char *line = fm; + + mcp_buf_puts(&md, "---\n"); + if (strncmp(fm, "---", 3) == 0) { + const char *stop = strstr(fm + 3, "\n---"); + + line = fm + 3; + while (*line == '\n') + line++; + while (stop != NULL && line < stop) { + const char *eol = memchr(line, '\n', (size_t)(stop - line)); + size_t n = eol ? (size_t)(eol - line) : (size_t)(stop - line); + + if (n >= 12 && strncmp(line, "description:", 12) == 0) { + mcp_buf_puts(&md, "description: "); + mcp_buf_puts(&md, desc); + mcp_buf_puts(&md, "\n"); + } else { + mcp_buf_add(&md, line, n); + mcp_buf_puts(&md, "\n"); + } + line += n; + if (line < stop && *line == '\n') + line++; + } + } else { + mcp_buf_puts(&md, "name: "); + mcp_buf_puts(&md, name); + mcp_buf_puts(&md, "\ndescription: "); + mcp_buf_puts(&md, desc); + mcp_buf_puts(&md, "\n"); + } + mcp_buf_puts(&md, "---\n"); + } else { + mcp_buf_puts(&md, fm); + if (md.len > 0 && md.p[md.len - 1] != '\n') + mcp_buf_puts(&md, "\n"); + } + if (body != NULL) { + mcp_buf_puts(&md, "\n"); + mcp_buf_puts(&md, body); + if (md.len > 0 && md.p[md.len - 1] != '\n') + mcp_buf_puts(&md, "\n"); + } else { + mcp_buf_puts(&md, rest); + if (md.len > 0 && md.p[md.len - 1] != '\n') + mcp_buf_puts(&md, "\n"); + } + if (append != NULL) { + mcp_buf_puts(&md, append); + if (md.len > 0 && md.p[md.len - 1] != '\n') + mcp_buf_puts(&md, "\n"); + } + + path = skill_file(name); + rc = write_file(path, md.p); + free(path); + mcp_buf_free(&md); + free(fm); + free(rest); + skill_free(&s); + + mcp_buf_init(&msg); + if (rc != 0) + mcp_buf_printf(&msg, "cannot write '%s'", name); + else + mcp_buf_printf(&msg, "updated '%s'", name); + if (rc != 0) + mcp_reply_error(c, msg.p); + else + mcp_reply_text(c, msg.p); + mcp_buf_free(&msg); +} + +static void t_clone(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *from = mcp_arg_string(args, "name"); + const char *to = mcp_arg_string(args, "new_name"); + struct skill s; + char *dir, *path; + mcp_buf md, msg; + int rc; + + (void)user; + if (!valid_name(from) || !valid_name(to)) { + mcp_reply_error(c, "invalid name"); + return; + } + if (load_skill(from, &s) != 0) { + mcp_reply_error(c, "no such skill"); + return; + } + dir = skill_dir(to); + if (is_dir(dir)) { + mcp_reply_error(c, "'new_name' already exists"); + free(dir); + skill_free(&s); + return; + } + { + char *base = skilllib_path(); + + mkdir_p(base); + free(base); + } + if (mkdir_p(dir) != 0) { + mcp_reply_error(c, "cannot create the clone directory"); + free(dir); + skill_free(&s); + return; + } + /* copy the whole skill, so references travel with it */ + mcp_buf_init(&md); + mcp_buf_printf(&md, "cp -a '%s/.' '%s/'", skill_dir(from), dir); + rc = system(md.p); + mcp_buf_free(&md); + + path = skill_file(to); + mcp_buf_init(&msg); + if (rc != 0 || !is_dir(dir)) { + mcp_buf_printf(&msg, "clone failed: %s", to); + mcp_reply_error(c, msg.p); + } else { + mcp_buf_printf(&msg, "cloned '%s' to '%s'", from, to); + mcp_reply_text(c, msg.p); + } + mcp_buf_free(&msg); + free(path); + free(dir); + skill_free(&s); +} + +static void t_delete(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *name = mcp_arg_string(args, "name"); + char *dir; + mcp_buf cmd, msg; + int rc; + + (void)user; + if (!valid_name(name)) { + mcp_reply_error(c, "invalid name"); + return; + } + dir = skill_dir(name); + if (!is_dir(dir)) { + mcp_reply_error(c, "no such skill"); + free(dir); + return; + } + mcp_buf_init(&cmd); + mcp_buf_printf(&cmd, "rm -rf '%s'", dir); + rc = system(cmd.p); + mcp_buf_free(&cmd); + mcp_buf_init(&msg); + if (rc != 0) { + mcp_buf_printf(&msg, "could not delete '%s'", name); + mcp_reply_error(c, msg.p); + } else { + mcp_buf_printf(&msg, "deleted '%s'", name); + mcp_reply_text(c, msg.p); + } + mcp_buf_free(&msg); + free(dir); +} + +static void t_assign(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *name = mcp_arg_string(args, "name"); + const char *profile = mcp_arg_string(args, "profile"); + char *dir, *dst; + mcp_buf cmd, msg; + const char *home; + int rc; + + (void)user; + if (!valid_name(name) || profile == NULL || *profile == '\0' || + strchr(profile, '/') != NULL || strstr(profile, "..") != NULL) { + mcp_reply_error(c, "bad skill name or profile"); + return; + } + dir = skill_dir(name); + if (!is_dir(dir)) { + mcp_reply_error(c, "no such skill"); + free(dir); + return; + } + home = getenv("HOME"); + if (home == NULL) + home = "."; + { + mcp_buf d; + + mcp_buf_init(&d); + mcp_buf_printf(&d, "%s/.hermes/profiles/%s/skills", home, profile); + mkdir_p(d.p); + mcp_buf_printf(&d, "/%s", name); + dst = d.p; + } + mcp_buf_init(&cmd); + mcp_buf_printf(&cmd, "rm -rf '%s' && cp -a '%s' '%s'", dst, dir, dst); + rc = system(cmd.p); + mcp_buf_free(&cmd); + mcp_buf_init(&msg); + if (rc != 0) { + mcp_buf_printf(&msg, "assignment failed for '%s'", name); + mcp_reply_error(c, msg.p); + } else { + mcp_buf_printf(&msg, "assigned '%s' to profile '%s' at %s", name, profile, dst); + mcp_reply_text(c, msg.p); + } + mcp_buf_free(&msg); + free(dst); + free(dir); +} + +/* ------------------------------------------------------------------ table */ + +static const mcp_tool TOOLS[] = { + { "skill_search", + "Find the right skill for a task before you start working. Call this " + "whenever a request touches something you have not done in this session: it " + "returns the skills that already encode how this fleet solves it, each with a " + "description and a relevance score. Search by describing the JOB in your own " + "words ('run a kanban worker', 'netbsd kernel patch', 'master audio to -14 " + "LUFS'); do not search by skill name, and do not skip it because you think " + "you already know the answer.", + "{\"type\":\"object\",\"properties\":{" + "\"query\":{\"type\":\"string\",\"description\":\"What you are trying to do, in plain words\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"Max results, default 10\"}}," + "\"required\":[\"query\"]}", + t_search }, + { "skill_load", + "Read one skill in full: its instructions, pitfalls and commands. Always load " + "before acting on a skill you found with skill_search - the description is only " + "the trigger, the body is the procedure.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\",\"description\":\"Exact name from skill_search\"}}," + "\"required\":[\"name\"]}", + t_load }, + { "skill_create", + "Write a NEW skill so the next agent does not rediscover what you just learned. " + "Use when you solved something non-obvious, hit a pitfall, or found a procedure " + "worth repeating. Write rules with the reason behind them, not a log of what " + "happened.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\",\"description\":\"kebab-case, stable, e.g. netbsd-kernel-build\"}," + "\"description\":{\"type\":\"string\",\"description\":\"One line starting with 'Use when ...' - this is the trigger other agents match on\"}," + "\"body\":{\"type\":\"string\",\"description\":\"Markdown: what to do, why, pitfalls, commands\"}," + "\"tags\":{\"type\":\"string\",\"description\":\"Comma separated\"}}," + "\"required\":[\"name\",\"description\"]}", + t_create }, + { "skill_update", + "Correct or extend an existing skill after reality proved it wrong or " + "incomplete. Give description to replace the trigger line, body to replace " + "everything after the frontmatter, or append to add a section at the end.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\"}," + "\"description\":{\"type\":\"string\"}," + "\"body\":{\"type\":\"string\"}," + "\"append\":{\"type\":\"string\"}}," + "\"required\":[\"name\"]}", + t_update }, + { "skill_clone", + "Duplicate a skill under a new name when a variant needs its own life instead " + "of editing the shared one. References and scripts come along.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\"},\"new_name\":{\"type\":\"string\"}}," + "\"required\":[\"name\",\"new_name\"]}", + t_clone }, + { "skill_list", + "Inventory of every skill in the library: name, description, tags. Use for a " + "survey, not for finding one skill - that is skill_search.", + "{\"type\":\"object\",\"properties\":{}}", + t_list }, + { "skill_assign", + "Hand a skill to a profile on this host by copying it into that profile's " + "skills directory, so that profile's agent loads it at start.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\"}," + "\"profile\":{\"type\":\"string\",\"description\":\"Profile name on this host\"}}," + "\"required\":[\"name\",\"profile\"]}", + t_assign }, + { "skill_delete", + "Remove a skill from the library. This deletes the directory and does not " + "ask twice.", + "{\"type\":\"object\",\"properties\":{" + "\"name\":{\"type\":\"string\"}}," + "\"required\":[\"name\"]}", + t_delete }, +}; + +int main(void) +{ + mcp_server srv; + + srv.name = "skilld"; + srv.version = "2.0.0"; + srv.tools = TOOLS; + srv.ntools = sizeof(TOOLS) / sizeof(TOOLS[0]); + srv.user = NULL; + return mcp_serve_stdio(&srv); +} diff --git a/tests/run.py b/tests/run.py new file mode 100644 index 0000000..2c342e4 --- /dev/null +++ b/tests/run.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Prove skilld's MCP surface: handshake, every tool, and the notification rule.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile + +BIN = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "skilld") +LIB = tempfile.mkdtemp(prefix="skilllib-test-") +HOME = tempfile.mkdtemp(prefix="skilld-home-") +fails = [] + + +def run(lines): + env = dict(os.environ) + env["SKILLLIB"] = LIB + env["HOME"] = HOME + proc = subprocess.run([BIN], input="\n".join(json.dumps(x) for x in lines) + "\n", + capture_output=True, text=True, env=env, timeout=60) + out = [l for l in proc.stdout.splitlines() if l.strip()] + return [json.loads(l) for l in out] + + +def check(name, cond, detail=""): + if cond: + print("PASS %s" % name) + else: + print("FAIL %s %s" % (name, detail)) + fails.append(name) + + +msgs = [ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2024-11-05", "capabilities": {}}}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "skill_create", "arguments": { + "name": "netbsd-kernel-build", + "description": "Use when building a NetBSD kernel after editing sys files.", + "body": "# NetBSD kernel build\n\nRun build.sh tools then kernel=GENERIC.", + "tags": "netbsd,kernel,build"}}}, + {"jsonrpc": "2.0", "id": 4, "method": "tools/call", + "params": {"name": "skill_create", "arguments": { + "name": "audio-mastering", + "description": "Use when mastering audio to streaming loudness targets.", + "body": "# Mastering\n\nTarget -14 LUFS integrated, true peak -1 dBTP.", + "tags": "audio,mastering,lufs"}}}, + {"jsonrpc": "2.0", "id": 5, "method": "tools/call", + "params": {"name": "skill_search", "arguments": {"query": "build a netbsd kernel"}}}, + {"jsonrpc": "2.0", "id": 6, "method": "tools/call", + "params": {"name": "skill_load", "arguments": {"name": "audio-mastering"}}}, + {"jsonrpc": "2.0", "id": 7, "method": "tools/call", + "params": {"name": "skill_update", "arguments": { + "name": "audio-mastering", "append": "Check with ffmpeg ebur128 before delivery."}}}, + {"jsonrpc": "2.0", "id": 8, "method": "tools/call", + "params": {"name": "skill_assign", "arguments": { + "name": "audio-mastering", "profile": "coder"}}}, + {"jsonrpc": "2.0", "id": 9, "method": "tools/call", + "params": {"name": "skill_clone", "arguments": { + "name": "audio-mastering", "new_name": "audio-mastering-dnb"}}}, + {"jsonrpc": "2.0", "id": 10, "method": "tools/call", + "params": {"name": "skill_list", "arguments": {}}}, + {"jsonrpc": "2.0", "id": 11, "method": "tools/call", + "params": {"name": "skill_delete", "arguments": {"name": "audio-mastering-dnb"}}}, + {"jsonrpc": "2.0", "id": 12, "method": "tools/call", + "params": {"name": "nope", "arguments": {}}}, +] + +res = run(msgs) +by_id = {r.get("id"): r for r in res} + +check("one answer per request, none for the notification", len(res) == 12, + "got %d answers for 12 requests + 1 notification" % len(res)) +check("initialize names skilld", + by_id.get(1, {}).get("result", {}).get("serverInfo", {}).get("name") == "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("search description carries the trigger", + any("skill_search" == t["name"] and len(t["description"]) > 200 for t in tools)) + +def text_of(r): + try: + return r["result"]["content"][0]["text"] + except Exception: + return "" + +check("create writes the skill", "created" in text_of(by_id.get(3, {}))) +check("create refuses nothing silently", os.path.isdir(os.path.join(LIB, "netbsd-kernel-build"))) + +hits = json.loads(text_of(by_id.get(5, {}))) +check("search ranks the kernel skill first", + hits["results"] and hits["results"][0]["name"] == "netbsd-kernel-build", + json.dumps(hits.get("results", [])[:2])) +check("search excludes the unrelated skill", all(r["name"] != "audio-mastering" for r in hits["results"])) + +loaded = text_of(by_id.get(6, {})) +check("load returns the body", "-14 LUFS" in loaded, loaded[:80]) + +upd = text_of(by_id.get(7, {})) +check("update appends", "updated" in upd) + +asg = text_of(by_id.get(8, {})) +check("assign copies into the profile", + os.path.isfile(os.path.join(HOME, ".hermes/profiles/coder/skills/audio-mastering/SKILL.md")), + asg) + +# the variant is proven by the inventory, because the delete below removes it +# before the checks run - the skill_list answer was taken while it existed +lst_names = [] +_lst = json.loads(text_of(by_id.get(10, {}))) +lst_names = [x["name"] for x in _lst.get("skills", [])] +check("clone makes the variant", "audio-mastering-dnb" in lst_names, lst_names) + +check("list counts three skills", _lst.get("total") == 3, _lst.get("total")) + +check("delete removes it", not os.path.exists(os.path.join(LIB, "audio-mastering-dnb"))) +check("unknown tool is an error", by_id.get(12, {}).get("error", {}).get("code") == -32601) + +shutil.rmtree(LIB, ignore_errors=True) +shutil.rmtree(HOME, ignore_errors=True) +print() +print("FAILURES: %d" % len(fails)) +sys.exit(1 if fails else 0) diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..7877689 --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,3 @@ +#!/bin/sh +# MCP surface test for skilld: no network, no model, temporary skill library. +exec python3 "$(dirname "$0")/run.py"