/* The MCP client: servers as rows, their sealed secrets, their tools in the registry, and * pic mcp (mcp.h). The protocol is mcp_wire.c's. */ #include #include #include #include #include #include #include "cred.h" #include "mcp.h" #include "mcp_wire.h" #include "noise.h" #include "platform.h" #include "toolreg.h" #include "userdb.h" #define MCP_NAME_CAP 65 #define MCP_URL_CAP 1024 #define MCP_VALUE_CAP 8192 #define MCP_TIMEOUT 60 #define MCP_OUTPUT_MAX 20480 /* Pi's: model-facing text beyond this is cut in the middle */ #define MCP_AAD "mcp-server:" /* ---- JSON through a private in-memory database --------------------------------------------- */ static sqlite3 *mcp_jdb_conn; static pid_t mcp_jdb_pid; /* This process's :memory: connection, for the JSON functions (one is never used across fork). */ static sqlite3 *mcp_jdb(void) { if (mcp_jdb_conn && mcp_jdb_pid == getpid()) { return mcp_jdb_conn; } mcp_jdb_conn = NULL; if (sqlite3_open(":memory:", &mcp_jdb_conn) != SQLITE_OK) { sqlite3_close(mcp_jdb_conn); mcp_jdb_conn = NULL; } mcp_jdb_pid = getpid(); return mcp_jdb_conn; } /* The first column of SQL's first row as text (malloc'd), over up to three text arguments, on * DB (NULL: the private one), or NULL. */ static char *mcp_jtext3(sqlite3 *db, const char *sql, const char *a, const char *b, const char *c) { sqlite3_stmt *q = NULL; const char *args[3] = {a, b, c}; char *out = NULL; if (!db && !(db = mcp_jdb())) { return NULL; } if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) == SQLITE_OK) { for (int i = 0; i < 3 && i < sqlite3_bind_parameter_count(q); i++) { sqlite3_bind_text(q, i + 1, args[i], -1, SQLITE_STATIC); } if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) { out = strdup((const char *)sqlite3_column_text(q, 0)); } } sqlite3_finalize(q); return out; } static char *mcp_jtext(const char *sql, const char *a, const char *b) { return mcp_jtext3(NULL, sql, a, b, NULL); } static long long mcp_jint(const char *sql, const char *a, const char *b, long long dflt) { char *v = mcp_jtext(sql, a, b); long long n = v ? strtoll(v, NULL, 10) : dflt; free(v); return n; } static long long mcp_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); } /* ---- checks ------------------------------------------------------------------------------------ */ /* A name is 1-64 of letters, digits, '_' and '-' (Pi's rule). */ static int mcp_name_check(const char *name, char *err, size_t errcap) { size_t n = strlen(name); if (n == 0 || n >= MCP_NAME_CAP || strspn(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") != n) { (void)snprintf(err, errcap, "an MCP server's name is 1-64 letters, digits, '_' and '-': %.80s", name); return -1; } return 0; } /* https://..., or http:// to this machine only; no spaces, no user:password@. */ static int mcp_url_check(const char *url, char *err, size_t errcap) { int tls = strncmp(url, "https://", 8) == 0; const char *host = url + (tls ? 8 : 7), *end; size_t h; if (!tls && strncmp(url, "http://", 7) != 0) { (void)snprintf(err, errcap, "an MCP server's URL starts with https:// (or http:// to this machine)"); return -1; } if (strlen(url) >= MCP_URL_CAP) { (void)snprintf(err, errcap, "the URL is longer than %d bytes", MCP_URL_CAP - 1); return -1; } for (const char *p = url; *p; p++) { if ((unsigned char)*p <= ' ' || *p == 0x7f) { (void)snprintf(err, errcap, "the URL has a space or a control character in it"); return -1; } } end = host + strcspn(host, "/?#"); if (memchr(host, '@', (size_t)(end - host))) { (void)snprintf(err, errcap, "the URL names a user: give a token with -H \"Authorization: Bearer ...\" instead"); return -1; } if (end == host || host[0] == ':') { (void)snprintf(err, errcap, "the URL has no host"); return -1; } h = host[0] == '[' ? strcspn(host, "]") + 1 : strcspn(host, ":/?#"); if (!tls && !((h == 9 && strncmp(host, "127.0.0.1", 9) == 0) || (h == 9 && strncmp(host, "localhost", 9) == 0) || (h == 5 && strncmp(host, "[::1]", 5) == 0))) { (void)snprintf(err, errcap, "plain http:// only to this machine (127.0.0.1, localhost); use https://"); return -1; } return 0; } /* Where a secret may be sent: the URL's scheme, host and port, or "stdio:PROGRAM". */ static void mcp_origin(const char *url, const char *program, char *out, size_t cap) { if (url) { const char *host = strstr(url, "://"); size_t n = host ? (size_t)(host + 3 - url) + strcspn(host + 3, "/?#") : strlen(url); (void)snprintf(out, cap, "%.*s", (int)n, url); for (char *p = out; *p; p++) { *p = (char)tolower((unsigned char)*p); } } else { (void)snprintf(out, cap, "stdio:%s", program ? program : ""); } } /* A header given as "Name: value" (Claude Code) or "Name=value" (Pi), as NAME and VALUE. */ static int mcp_header_split(const char *h, char *name, size_t ncap, const char **value, char *err, size_t errcap) { const char *colon = strchr(h, ':'), *eq = strchr(h, '='), *cut = colon && (!eq || colon < eq) ? colon : eq; size_t n = cut ? (size_t)(cut - h) : 0; if (!cut || n == 0 || n >= ncap || strspn(h, "!#$%&'*+.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-") != n) { (void)snprintf(err, errcap, "a header is \"Name: value\" or Name=value"); return -1; } memcpy(name, h, n); name[n] = '\0'; *value = cut + 1; while (**value == ' ') { (*value)++; } if (strlen(*value) >= MCP_VALUE_CAP) { (void)snprintf(err, errcap, "the value of the header %s is too long", name); return -1; } for (const char *p = *value; *p; p++) { if (((unsigned char)*p < 0x20 && *p != '\t') || *p == 0x7f) { (void)snprintf(err, errcap, "the value of the header %s has a control character in it", name); return -1; } } return 0; } static int mcp_env_check(const char *e, char *err, size_t errcap) { const char *eq = strchr(e, '='); size_t n = eq ? (size_t)(eq - e) : 0; if (!eq || n == 0 || isdigit((unsigned char)e[0]) || strspn(e, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != n || strlen(e) >= MCP_VALUE_CAP) { (void)snprintf(err, errcap, "an environment value is NAME=VALUE"); return -1; } return 0; } /* ---- a server as pic mcp add describes it -------------------------------------------------- */ typedef struct { char name[MCP_NAME_CAP]; char *url, *cwd, *description, *exposure; char **argv; /* stdio: the program, then its arguments */ size_t argc; char **headers; /* "Name: value" */ size_t nheaders; char **env; /* "NAME=value" */ size_t nenv; int timeout; } mcp_spec; static void mcp_list_free(char **l, size_t n, int secret) { for (size_t i = 0; i < n; i++) { if (secret && l[i]) { pic_cred_wipe(l[i], strlen(l[i])); } free(l[i]); } free(l); } static void mcp_spec_free(mcp_spec *s) { free(s->url); free(s->cwd); free(s->description); free(s->exposure); mcp_list_free(s->argv, s->argc, 0); mcp_list_free(s->headers, s->nheaders, 1); mcp_list_free(s->env, s->nenv, 1); memset(s, 0, sizeof *s); } static int mcp_push(char ***l, size_t *n, const char *v) { char **grown = realloc(*l, (*n + 1) * sizeof **l); if (!grown) { return -1; } *l = grown; if (!(grown[*n] = strdup(v))) { return -1; } (*n)++; return 0; } static int mcp_set(char **slot, const char *v) { free(*slot); return (*slot = strdup(v)) ? 0 : -1; } /* Adds a header given either way, normalised to "Name: value". */ static int mcp_spec_header(mcp_spec *s, const char *h, char *err, size_t errcap) { char name[128], *line; const char *value; int rc; if (mcp_header_split(h, name, sizeof name, &value, err, errcap) != 0) { return -1; } if (!(line = malloc(strlen(name) + strlen(value) + 3))) { return -1; } (void)snprintf(line, strlen(name) + strlen(value) + 3, "%s: %s", name, value); rc = mcp_push(&s->headers, &s->nheaders, line); pic_cred_wipe(line, strlen(line)); free(line); return rc; } static const char *const mcp_exposures[] = {"direct", "deferred", "codemode", "codemode-deferred", "hidden"}; /* The checks every way of adding a server shares. */ static int mcp_spec_check(mcp_spec *s, char *err, size_t errcap) { if (mcp_name_check(s->name, err, errcap) != 0) { return -1; } if (!s->url == !s->argc) { (void)snprintf(err, errcap, "give %s either a URL (an HTTP server) or a command after -- (a stdio server)", s->name); return -1; } if (s->url && mcp_url_check(s->url, err, errcap) != 0) { return -1; } if (s->url && (s->nenv || s->cwd)) { (void)snprintf(err, errcap, "--env and --cwd are for a stdio server; %s is an HTTP server", s->name); return -1; } if (s->argc && s->nheaders) { (void)snprintf(err, errcap, "headers are for an HTTP server; %s is a stdio server (give secrets with --env)", s->name); return -1; } if (s->exposure) { int known = 0; for (size_t i = 0; i < sizeof mcp_exposures / sizeof mcp_exposures[0]; i++) { known |= strcmp(s->exposure, mcp_exposures[i]) == 0; } if (!known) { (void)snprintf(err, errcap, "--exposure is direct, deferred, codemode or hidden"); return -1; } } if (s->timeout <= 0) { s->timeout = MCP_TIMEOUT; } return 0; } static const char mcp_no_oauth[] = "pic does not sign in to MCP servers itself yet: give a token with -H \"Authorization: Bearer ...\""; /* pic mcp add's arguments, in Pi's shape (NAME --url URL, NAME -- COMMAND ARGS...) or Claude * Code's ([--transport http|stdio] NAME URL|COMMAND [ARGS...], -H "Name: value", -e K=V). */ static int mcp_spec_parse(int argc, char **argv, mcp_spec *s, char *err, size_t errcap) { const char *transport = NULL, *name = NULL; memset(s, 0, sizeof *s); for (int i = 0; i < argc; i++) { const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL, *eq = strchr(a, '='); char opt[48]; size_t on = a[0] == '-' && a[1] == '-' && eq ? (size_t)(eq - a) : strlen(a); if (s->argc) { /* the rest is the command's own */ if (mcp_push(&s->argv, &s->argc, a) != 0) { goto oom; } continue; } if (strcmp(a, "--") == 0) { for (i++; i < argc; i++) { if (mcp_push(&s->argv, &s->argc, argv[i]) != 0) { goto oom; } } if (!s->argc) { (void)snprintf(err, errcap, "no command after --"); return -1; } break; } if (a[0] != '-' || a[1] == '\0') { if (!name) { name = a; } else if (strncmp(a, "http://", 7) == 0 || strncmp(a, "https://", 8) == 0) { if (s->url) { (void)snprintf(err, errcap, "two URLs given"); return -1; } if (mcp_set(&s->url, a) != 0) { goto oom; } } else if (mcp_push(&s->argv, &s->argc, a) != 0) { goto oom; } continue; } (void)snprintf(opt, sizeof opt, "%.*s", (int)(on < sizeof opt ? on : sizeof opt - 1), a); if (a[1] == '-' && eq) { v = eq + 1; /* --name=value */ } else if (strcmp(opt, "-l") == 0 || strcmp(opt, "--local") == 0) { (void)snprintf(err, errcap, "pic keeps MCP servers in ~/.pic/pic.sqlite, not in a project's file: " "add it without -l"); return -1; } else { i++; /* every other option takes a value */ } if (!v) { (void)snprintf(err, errcap, "%s needs a value", opt); return -1; } if (strcmp(opt, "--url") == 0) { if (mcp_set(&s->url, v) != 0) { goto oom; } } else if (strcmp(opt, "--transport") == 0 || strcmp(opt, "-t") == 0) { transport = v; } else if (strcmp(opt, "--header") == 0 || strcmp(opt, "-H") == 0) { if (mcp_spec_header(s, v, err, errcap) != 0) { return -1; } } else if (strcmp(opt, "--env") == 0 || strcmp(opt, "-e") == 0) { if (mcp_env_check(v, err, errcap) != 0) { return -1; } if (mcp_push(&s->env, &s->nenv, v) != 0) { goto oom; } } else if (strcmp(opt, "--bearer-token-env-var") == 0) { char h[256]; if (strspn(v, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(v) || !*v || strlen(v) > 200) { (void)snprintf(err, errcap, "--bearer-token-env-var names an environment variable"); return -1; } (void)snprintf(h, sizeof h, "Authorization: Bearer ${%s}", v); if (mcp_spec_header(s, h, err, errcap) != 0) { return -1; } } else if (strcmp(opt, "--cwd") == 0) { if (mcp_set(&s->cwd, v) != 0) { goto oom; } } else if (strcmp(opt, "--description") == 0) { if (mcp_set(&s->description, v) != 0) { goto oom; } } else if (strcmp(opt, "--exposure") == 0) { if (mcp_set(&s->exposure, v) != 0) { goto oom; } } else if (strcmp(opt, "--timeout") == 0) { char *end; long t = strtol(v, &end, 10); if (*end || t <= 0 || t > 3600) { (void)snprintf(err, errcap, "--timeout is seconds, 1-3600"); return -1; } s->timeout = (int)t; } else if (strcmp(opt, "--scope") == 0 || strcmp(opt, "-s") == 0) { if (strcmp(v, "project") == 0) { (void)snprintf(err, errcap, "pic does not write a project's .mcp.json; it reads a trusted project's. " "Add the server without -s project to keep it for yourself"); return -1; } if (strcmp(v, "user") != 0 && strcmp(v, "local") != 0) { (void)snprintf(err, errcap, "--scope is user or local (pic keeps both in ~/.pic/pic.sqlite)"); return -1; } } else if (strncmp(opt, "--oauth", 7) == 0 || strcmp(opt, "--client-id") == 0 || strcmp(opt, "--client-secret") == 0 || strcmp(opt, "--callback-port") == 0) { (void)snprintf(err, errcap, "%s", mcp_no_oauth); return -1; } else { (void)snprintf(err, errcap, "pic mcp add does not know %s (pic help mcp)", opt); return -1; } } if (!name) { (void)snprintf(err, errcap, "pic mcp add NAME URL, or NAME -- COMMAND [ARGS...] (pic help mcp)"); return -1; } if (strlen(name) >= sizeof s->name) { return mcp_name_check(name, err, errcap); } (void)snprintf(s->name, sizeof s->name, "%s", name); if (transport) { if (strcmp(transport, "sse") == 0) { (void)snprintf(err, errcap, "pic does not speak the old HTTP+SSE transport; most servers also offer streamable " "HTTP, often at /mcp instead of /sse"); return -1; } if (strcmp(transport, "http") != 0 && strcmp(transport, "streamable-http") != 0 && strcmp(transport, "stdio") != 0) { (void)snprintf(err, errcap, "--transport is http or stdio"); return -1; } if ((strcmp(transport, "stdio") == 0) != (s->argc > 0)) { (void)snprintf(err, errcap, "--transport %s does not fit what was given (a URL is http, a command stdio)", transport); return -1; } } return mcp_spec_check(s, err, errcap); oom: (void)snprintf(err, errcap, "out of memory"); return -1; } /* One server of an mcpServers entry: {type, url, headers, command, args, env, cwd, description, * exposure, timeout}. */ static int mcp_spec_json(const char *name, const char *entry, mcp_spec *s, char *err, size_t errcap) { sqlite3 *db = mcp_jdb(); sqlite3_stmt *q = NULL; char *type = mcp_jtext("SELECT json_extract(?1, '$.type') WHERE json_type(?1, '$.type') = 'text'", entry, NULL); char *url = mcp_jtext("SELECT json_extract(?1, '$.url') WHERE json_type(?1, '$.url') = 'text'", entry, NULL); char *cmd = mcp_jtext("SELECT json_extract(?1, '$.command') WHERE json_type(?1, '$.command') = 'text'", entry, NULL); int rc = -1; memset(s, 0, sizeof *s); if (strlen(name) >= sizeof s->name) { rc = mcp_name_check(name, err, errcap); goto done; } (void)snprintf(s->name, sizeof s->name, "%s", name); if (type && strcmp(type, "sse") == 0) { (void)snprintf(err, errcap, "%s: pic does not speak the old HTTP+SSE transport", name); goto done; } if (mcp_jint("SELECT json_type(?1, '$.oauth') IS NOT NULL OR json_type(?1, '$.auth') IS NOT NULL", entry, NULL, 0)) { (void)snprintf(err, errcap, "%s: %s", name, mcp_no_oauth); goto done; } if ((url && mcp_set(&s->url, url) != 0) || (cmd && mcp_push(&s->argv, &s->argc, cmd) != 0)) { goto oom; } if (!db || sqlite3_prepare_v2(db, "SELECT 'a', value, NULL FROM json_each(?1, '$.args') WHERE json_type(?1, '$.args') = 'array'" " UNION ALL SELECT 'h', key, value FROM json_each(?1, '$.headers')" " WHERE json_type(?1, '$.headers') = 'object'" " UNION ALL SELECT 'e', key, value FROM json_each(?1, '$.env')" " WHERE json_type(?1, '$.env') = 'object'", -1, &q, NULL) != SQLITE_OK) { goto oom; } sqlite3_bind_text(q, 1, entry, -1, SQLITE_STATIC); while (sqlite3_step(q) == SQLITE_ROW) { const char *kind = (const char *)sqlite3_column_text(q, 0), *k = (const char *)sqlite3_column_text(q, 1), *v = (const char *)sqlite3_column_text(q, 2); char *line; if (!k) { continue; } if (kind[0] == 'a') { if (mcp_push(&s->argv, &s->argc, k) != 0) { goto oom; } continue; } if (!v || !(line = malloc(strlen(k) + strlen(v) + 3))) { goto oom; } (void)snprintf(line, strlen(k) + strlen(v) + 3, kind[0] == 'h' ? "%s: %s" : "%s=%s", k, v); rc = kind[0] == 'h' ? mcp_spec_header(s, line, err, errcap) : (mcp_env_check(line, err, errcap) == 0 ? mcp_push(&s->env, &s->nenv, line) : -1); pic_cred_wipe(line, strlen(line)); free(line); if (rc != 0) { goto done; } } { char *d = mcp_jtext("SELECT json_extract(?1, '$.description') WHERE json_type(?1, '$.description') = 'text'", entry, NULL); char *x = mcp_jtext("SELECT json_extract(?1, '$.exposure') WHERE json_type(?1, '$.exposure') = 'text'", entry, NULL); char *c = mcp_jtext("SELECT json_extract(?1, '$.cwd') WHERE json_type(?1, '$.cwd') = 'text'", entry, NULL); s->description = d; s->exposure = x; s->cwd = c; s->timeout = (int)mcp_jint("SELECT json_extract(?1, '$.timeout') WHERE json_type(?1, '$.timeout') = 'integer'", entry, NULL, 0); } if (type && strcmp(type, "http") != 0 && strcmp(type, "streamable-http") != 0 && strcmp(type, "stdio") != 0) { (void)snprintf(err, errcap, "%s: type is http or stdio", name); rc = -1; goto done; } rc = mcp_spec_check(s, err, errcap); goto done; oom: (void)snprintf(err, errcap, "out of memory"); rc = -1; done: sqlite3_finalize(q); free(type); free(url); free(cmd); return rc; } /* ---- rows ------------------------------------------------------------------------------------- */ typedef struct { char *name, *transport, *url, *command, *cwd, *header_names, *env_names, *description, *exposure, *era, *tools, *error; unsigned char *sealed; int sealed_n, timeout, enabled; long long added_ms, listed_ms; } mcp_row; static void mcp_row_free(mcp_row *r) { free(r->name); free(r->transport); free(r->url); free(r->command); free(r->cwd); free(r->header_names); free(r->env_names); free(r->description); free(r->exposure); free(r->era); free(r->tools); free(r->error); free(r->sealed); memset(r, 0, sizeof *r); } static char *mcp_col_dup(sqlite3_stmt *q, int i) { return sqlite3_column_type(q, i) == SQLITE_NULL ? NULL : strdup((const char *)sqlite3_column_text(q, i)); } /* Every server (or NAME's), by name, into *OUT. 0, or -1 when the database cannot be read. */ static int mcp_rows_load(const char *name, mcp_row **out, size_t *n) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; mcp_row *rows = NULL; *out = NULL; *n = 0; if (!db || sqlite3_prepare_v2(db, "SELECT name, transport, url, command, cwd, header_names, env_names, description, exposure," " era, tools, error, sealed, timeout, enabled, added_ms, coalesce(listed_ms, 0)" " FROM picu_mcp_server WHERE ?1 IS NULL OR name = ?1 ORDER BY name", -1, &q, NULL) != SQLITE_OK) { sqlite3_finalize(q); return -1; } sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC); while (sqlite3_step(q) == SQLITE_ROW) { mcp_row *grown = realloc(rows, (*n + 1) * sizeof *rows), *r; if (!grown) { break; } rows = grown; r = &rows[*n]; memset(r, 0, sizeof *r); r->name = mcp_col_dup(q, 0); r->transport = mcp_col_dup(q, 1); r->url = mcp_col_dup(q, 2); r->command = mcp_col_dup(q, 3); r->cwd = mcp_col_dup(q, 4); r->header_names = mcp_col_dup(q, 5); r->env_names = mcp_col_dup(q, 6); r->description = mcp_col_dup(q, 7); r->exposure = mcp_col_dup(q, 8); r->era = mcp_col_dup(q, 9); r->tools = mcp_col_dup(q, 10); r->error = mcp_col_dup(q, 11); if (sqlite3_column_type(q, 12) == SQLITE_BLOB && (r->sealed_n = sqlite3_column_bytes(q, 12)) > 0 && (r->sealed = malloc((size_t)r->sealed_n))) { memcpy(r->sealed, sqlite3_column_blob(q, 12), (size_t)r->sealed_n); } r->timeout = sqlite3_column_int(q, 13); r->enabled = sqlite3_column_int(q, 14); r->added_ms = sqlite3_column_int64(q, 15); r->listed_ms = sqlite3_column_int64(q, 16); (*n)++; } sqlite3_finalize(q); *out = rows; return 0; } static void mcp_rows_free(mcp_row *rows, size_t n) { for (size_t i = 0; i < n; i++) { mcp_row_free(&rows[i]); } free(rows); } /* A JSON array of the names in LIST ("Name: value" or "NAME=value": the part before SEP). */ static char *mcp_names_json(char **list, size_t n, const char *sep) { sqlite3_str *t = sqlite3_str_new(NULL); char *out, *res; sqlite3_str_appendall(t, "["); for (size_t i = 0; i < n; i++) { sqlite3_str_appendf(t, "%s\"%.*s\"", i ? "," : "", (int)strcspn(list[i], sep), list[i]); } sqlite3_str_appendall(t, "]"); res = sqlite3_str_finish(t); out = res ? strdup(res) : NULL; sqlite3_free(res); return out; } /* The secrets of S as the sealed JSON {"origin", "headers": [[name, value]], "env": [[name, * value]]}, malloc'd; NULL when it has none (or out of memory: *oom). */ static char *mcp_secrets_json(const mcp_spec *s, int *oom) { char origin[MCP_URL_CAP + 16], *out = NULL, *res; sqlite3_str *t; *oom = 0; if (!s->nheaders && !s->nenv) { return NULL; } mcp_origin(s->url, s->argc ? s->argv[0] : NULL, origin, sizeof origin); t = sqlite3_str_new(NULL); sqlite3_str_appendf(t, "{\"origin\":\"%w\",\"headers\":[", origin); for (size_t i = 0; i < s->nheaders; i++) { const char *v = s->headers[i] + strcspn(s->headers[i], ":") + 2; sqlite3_str_appendf(t, "%s[\"%.*s\",", i ? "," : "", (int)strcspn(s->headers[i], ":"), s->headers[i]); /* a JSON string by SQLite's quote rules: %w doubles quotes, so escape by hand */ sqlite3_str_appendall(t, "\""); for (const char *p = v; *p; p++) { if (*p == '"' || *p == '\\') { sqlite3_str_appendchar(t, 1, '\\'); } if (*p == '\t') { sqlite3_str_appendall(t, "\\t"); } else { sqlite3_str_appendchar(t, 1, *p); } } sqlite3_str_appendall(t, "\"]"); } sqlite3_str_appendall(t, "],\"env\":["); for (size_t i = 0; i < s->nenv; i++) { const char *v = strchr(s->env[i], '=') + 1; sqlite3_str_appendf(t, "%s[\"%.*s\",\"", i ? "," : "", (int)strcspn(s->env[i], "="), s->env[i]); for (const char *p = v; *p; p++) { if (*p == '"' || *p == '\\') { sqlite3_str_appendchar(t, 1, '\\'); } if ((unsigned char)*p < 0x20) { sqlite3_str_appendf(t, "\\u%04x", (unsigned char)*p); } else { sqlite3_str_appendchar(t, 1, *p); } } sqlite3_str_appendall(t, "\"]"); } sqlite3_str_appendall(t, "]}"); if (sqlite3_str_errcode(t) != SQLITE_OK) { *oom = 1; } { int n = sqlite3_str_length(t); res = sqlite3_str_finish(t); if (res && !*oom) { out = strdup(res); } if (res) { pic_cred_wipe(res, (size_t)n); } sqlite3_free(res); } *oom = *oom || !out; return out; } /* Saves S (replacing a server of the same name), sealing its secrets. 0, or -1 with err. */ static int mcp_spec_save(const mcp_spec *s, char *err, size_t errcap) { sqlite3 *db = pic_userdb(err, errcap); sqlite3_stmt *q = NULL; char aad[sizeof MCP_AAD + MCP_NAME_CAP], *secret, *hn = NULL, *en = NULL, *argv_json = NULL; unsigned char *box = NULL; size_t sn = 0; int oom, rc = -1; if (!db) { return -1; } if (sqlite3_prepare_v2(db, "SELECT name FROM picu_mcp_server WHERE replace(name, '-', '_') = replace(?1, '-', '_')" " AND name <> ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, s->name, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { (void)snprintf(err, errcap, "%s is too like the server %s (names that differ only in '-' and '_' are one)", s->name, (const char *)sqlite3_column_text(q, 0)); sqlite3_finalize(q); return -1; } } sqlite3_finalize(q); q = NULL; secret = mcp_secrets_json(s, &oom); if (oom) { (void)snprintf(err, errcap, "out of memory"); return -1; } (void)snprintf(aad, sizeof aad, MCP_AAD "%s", s->name); if (secret) { sn = strlen(secret); if (pic_cred_prepare(err, errcap) != 0 || !(box = malloc(sn + PIC_CRED_OVERHEAD)) || pic_cred_box(aad, secret, sn, box, err, errcap) != 0) { if (!err[0]) { (void)snprintf(err, errcap, "out of memory"); } goto done; } } hn = mcp_names_json(s->headers, s->nheaders, ":"); en = mcp_names_json(s->env, s->nenv, "="); argv_json = s->argc ? mcp_names_json(s->argv, s->argc, "") : NULL; if (s->argc && argv_json) { /* mcp_names_json cuts at the separator; arguments are whole: build it properly */ sqlite3_str *t = sqlite3_str_new(NULL); char *res; free(argv_json); sqlite3_str_appendall(t, "["); for (size_t i = 0; i < s->argc; i++) { char *quoted = mcp_jtext("SELECT json_quote(?1)", s->argv[i], NULL); sqlite3_str_appendf(t, "%s%s", i ? "," : "", quoted ? quoted : "\"\""); free(quoted); } sqlite3_str_appendall(t, "]"); res = sqlite3_str_finish(t); argv_json = res ? strdup(res) : NULL; sqlite3_free(res); } if (!hn || !en || (s->argc && !argv_json)) { (void)snprintf(err, errcap, "out of memory"); goto done; } if (sqlite3_prepare_v2(db, "INSERT OR REPLACE INTO picu_mcp_server(name, transport, url, command, cwd, header_names," " env_names, sealed, description, exposure, timeout, enabled, added_ms)" " VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 1, ?12)", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, s->name, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, s->url ? "http" : "stdio", -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, s->url, -1, SQLITE_STATIC); sqlite3_bind_text(q, 4, argv_json, -1, SQLITE_STATIC); sqlite3_bind_text(q, 5, s->cwd, -1, SQLITE_STATIC); sqlite3_bind_text(q, 6, hn, -1, SQLITE_STATIC); sqlite3_bind_text(q, 7, en, -1, SQLITE_STATIC); if (box) { sqlite3_bind_blob(q, 8, box, (int)(sn + PIC_CRED_OVERHEAD), SQLITE_STATIC); } sqlite3_bind_text(q, 9, s->description, -1, SQLITE_STATIC); sqlite3_bind_text(q, 10, s->exposure, -1, SQLITE_STATIC); sqlite3_bind_int(q, 11, s->timeout); sqlite3_bind_int64(q, 12, mcp_now_ms()); rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1; } if (rc != 0) { (void)snprintf(err, errcap, "cannot save the server in ~/.pic/pic.sqlite: %s", sqlite3_errmsg(db)); } done: sqlite3_finalize(q); if (secret) { pic_cred_wipe(secret, sn); free(secret); } free(box); free(hn); free(en); free(argv_json); return rc; } /* Records a listing: ERA, TOOLS and INSTRUCTIONS when it worked (TOOLS not NULL), else ERROR. */ static void mcp_row_note(const char *name, const char *era, const char *tools, const char *error) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; if (db && sqlite3_prepare_v2(db, tools ? "UPDATE picu_mcp_server SET era = ?2, tools = json(?3), listed_ms = ?4, error = NULL" " WHERE name = ?1" : "UPDATE picu_mcp_server SET error = ?5 WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC); if (tools) { sqlite3_bind_text(q, 2, era, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, tools, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 4, mcp_now_ms()); } else { sqlite3_bind_text(q, 5, error, -1, SQLITE_STATIC); } (void)sqlite3_step(q); } sqlite3_finalize(q); } static int mcp_row_remove(const char *name) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; int rc = -1; if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_mcp_server WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC); rc = sqlite3_step(q) == SQLITE_DONE ? sqlite3_changes(db) > 0 : -1; } sqlite3_finalize(q); return rc; } /* ---- a live connection's target, with its secrets opened --------------------------------------- */ typedef struct { pic_mcp_target t; char **headers, **env, **argv; size_t nheaders, nenv, argc; char *cwd; } mcp_live; static void mcp_live_free(mcp_live *l) { mcp_list_free(l->headers, l->nheaders, 1); mcp_list_free(l->env, l->nenv, 1); mcp_list_free(l->argv, l->argc, 0); free(l->cwd); memset(l, 0, sizeof *l); } /* VALUE with each ${NAME} replaced by the variable's value (malloc'd), or NULL with err. */ static char *mcp_expand(const char *server, const char *what, const char *value, char *err, size_t errcap) { sqlite3_str *t = sqlite3_str_new(NULL); char *res, *out; int n; for (const char *p = value; *p;) { const char *open = strstr(p, "${"), *close = open ? strchr(open + 2, '}') : NULL; char var[256]; const char *v; if (!open || !close || (size_t)(close - open - 2) >= sizeof var) { sqlite3_str_appendall(t, p); break; } sqlite3_str_append(t, p, (int)(open - p)); (void)snprintf(var, sizeof var, "%.*s", (int)(close - open - 2), open + 2); if (!(v = getenv(var))) { (void)snprintf(err, errcap, "%s's %s names ${%s}, which is not set", server, what, var); n = sqlite3_str_length(t); res = sqlite3_str_finish(t); if (res) { pic_cred_wipe(res, (size_t)n); } sqlite3_free(res); return NULL; } sqlite3_str_appendall(t, v); p = close + 1; } n = sqlite3_str_length(t); res = sqlite3_str_finish(t); out = res ? strdup(res) : NULL; if (res) { pic_cred_wipe(res, (size_t)n); } sqlite3_free(res); if (!out) { (void)snprintf(err, errcap, "out of memory"); } return out; } /* R's target: its URL or command, and its sealed headers and environment opened (QUIET: never * asking for a passphrase) and bound to its origin. 0, or -1 with err. */ static int mcp_live_open(const mcp_row *r, const char *workspace, int quiet, mcp_live *l, char *err, size_t errcap) { char aad[sizeof MCP_AAD + MCP_NAME_CAP], origin[MCP_URL_CAP + 16], *plain = NULL, *sealed_origin = NULL; sqlite3 *db = mcp_jdb(); sqlite3_stmt *q = NULL; int rc = -1; memset(l, 0, sizeof *l); l->t.name = r->name; l->t.url = r->url; l->t.era = r->era; l->t.timeout = r->timeout > 0 ? r->timeout : MCP_TIMEOUT; if (!db) { (void)snprintf(err, errcap, "out of memory"); return -1; } if (r->command) { if (sqlite3_prepare_v2(db, "SELECT value FROM json_each(?1) WHERE type = 'text'", -1, &q, NULL) != SQLITE_OK) { goto oom; } sqlite3_bind_text(q, 1, r->command, -1, SQLITE_STATIC); while (sqlite3_step(q) == SQLITE_ROW) { if (mcp_push(&l->argv, &l->argc, (const char *)sqlite3_column_text(q, 0)) != 0) { goto oom; } } sqlite3_finalize(q); q = NULL; if (!l->argc || mcp_push(&l->argv, &l->argc, "") != 0) { (void)snprintf(err, errcap, "%s has no command", r->name); goto fail; } free(l->argv[--l->argc]); /* the NULL that ends the list */ l->argv[l->argc] = NULL; l->t.argv = (const char *const *)l->argv; /* a relative cwd is the workspace's; none is the workspace (or, outside a request, here) */ if (r->cwd && (r->cwd[0] == '/' || r->cwd[0] == '~' || !workspace)) { l->cwd = strdup(r->cwd); } else if (workspace && (l->cwd = malloc(strlen(workspace) + (r->cwd ? strlen(r->cwd) : 0) + 2))) { (void)snprintf(l->cwd, strlen(workspace) + (r->cwd ? strlen(r->cwd) : 0) + 2, "%s%s%s", workspace, r->cwd ? "/" : "", r->cwd ? r->cwd : ""); } if ((r->cwd || workspace) && !l->cwd) { goto oom; } l->t.cwd = l->cwd; } mcp_origin(r->url, l->argc ? l->argv[0] : NULL, origin, sizeof origin); if (!r->sealed) { if (mcp_jint("SELECT json_array_length(?1) + json_array_length(?2)", r->header_names ? r->header_names : "[]", r->env_names ? r->env_names : "[]", 0) > 0) { (void)snprintf(err, errcap, "%s's sealed headers and environment are gone (pic auth reset); add it again", r->name); goto fail; } rc = 0; goto done; } { int q_rc = quiet ? pic_cred_quiet(err, errcap) : pic_cred_unlock(err, errcap); if (q_rc == 1) { (void)snprintf(err, errcap, "the credential store is locked, so %s's sealed headers cannot be opened: unlock it " "first (pic auth status)", r->name); goto fail; } if (q_rc != 0) { goto fail; } } if (!(plain = calloc(1, (size_t)r->sealed_n))) { goto oom; } (void)snprintf(aad, sizeof aad, MCP_AAD "%s", r->name); if (pic_cred_unbox(aad, r->sealed, (size_t)r->sealed_n, plain, err, errcap) != 0) { goto fail; } sealed_origin = mcp_jtext("SELECT json_extract(?1, '$.origin')", plain, NULL); if (!sealed_origin || strcmp(sealed_origin, origin) != 0) { (void)snprintf(err, errcap, "%s's sealed headers belong to %.200s, not %.200s: add the server again", r->name, sealed_origin ? sealed_origin : "another address", origin); goto fail; } if (sqlite3_prepare_v2(db, "SELECT 'h', json_extract(value, '$[0]'), json_extract(value, '$[1]') FROM json_each(?1, '$.headers')" " UNION ALL SELECT 'e', json_extract(value, '$[0]'), json_extract(value, '$[1]')" " FROM json_each(?1, '$.env')", -1, &q, NULL) != SQLITE_OK) { goto oom; } sqlite3_bind_text(q, 1, plain, -1, SQLITE_STATIC); while (sqlite3_step(q) == SQLITE_ROW) { const char *kind = (const char *)sqlite3_column_text(q, 0), *k = (const char *)sqlite3_column_text(q, 1), *v = (const char *)sqlite3_column_text(q, 2); char what[200], *value, *line; int pushed; if (!k || !v) { continue; } (void)snprintf(what, sizeof what, "%s %s", kind[0] == 'h' ? "header" : "variable", k); if (!(value = mcp_expand(r->name, what, v, err, errcap))) { goto fail; } if (!(line = malloc(strlen(k) + strlen(value) + 3))) { pic_cred_wipe(value, strlen(value)); free(value); goto oom; } (void)snprintf(line, strlen(k) + strlen(value) + 3, kind[0] == 'h' ? "%s: %s" : "%s=%s", k, value); pushed = kind[0] == 'h' ? mcp_push(&l->headers, &l->nheaders, line) : mcp_push(&l->env, &l->nenv, line); pic_cred_wipe(value, strlen(value)); pic_cred_wipe(line, strlen(line)); free(value); free(line); if (pushed != 0) { goto oom; } } sqlite3_finalize(q); q = NULL; if (l->nenv && mcp_push(&l->env, &l->nenv, "") == 0) { free(l->env[--l->nenv]); l->env[l->nenv] = NULL; } l->t.headers = (const char *const *)l->headers; l->t.nheaders = l->nheaders; l->t.env = (const char *const *)l->env; rc = 0; goto done; oom: (void)snprintf(err, errcap, "out of memory"); fail: mcp_live_free(l); rc = -1; done: sqlite3_finalize(q); if (plain) { pic_cred_wipe(plain, (size_t)r->sealed_n); free(plain); } free(sealed_origin); return rc; } /* Rewrites ERR so no opened header or environment value of L survives in it. */ static void mcp_live_scrub(const mcp_live *l, char *err) { for (size_t i = 0; i < l->nheaders; i++) { const char *v = l->headers[i] + strcspn(l->headers[i], ":"); v += *v ? 2 : 0; if (strlen(v) >= 8) { pic_cred_scrub(err, v); } } for (size_t i = 0; i < l->nenv; i++) { const char *v = strchr(l->env[i], '='); if (v && strlen(v + 1) >= 8) { pic_cred_scrub(err, v + 1); } } } /* Connects to R and lists its tools, recording them (or why not) in its row. The number of * tools, or -1 with err. */ static int mcp_row_refresh(const mcp_row *r, char *era, size_t eracap, char *err, size_t errcap) { mcp_live l; pic_mcp_conn *c; char *tools; int n = -1; era[0] = '\0'; if (mcp_live_open(r, NULL, 0, &l, err, errcap) != 0) { mcp_row_note(r->name, NULL, NULL, err); return -1; } if ((c = pic_mcp_open(&l.t, err, errcap)) && (tools = pic_mcp_list_tools(c, err, errcap))) { (void)snprintf(era, eracap, "%s", pic_mcp_era(c)); mcp_row_note(r->name, era, tools, NULL); n = (int)mcp_jint("SELECT json_array_length(?1)", tools, NULL, 0); free(tools); } pic_mcp_close(c); if (n < 0) { mcp_live_scrub(&l, err); mcp_row_note(r->name, NULL, NULL, err); } mcp_live_free(&l); return n; } /* ---- a call --------------------------------------------------------------------------------- */ /* TEXT cut to MCP_OUTPUT_MAX bytes in the middle, as Pi cuts it (malloc'd), naming WHERE the * whole text is kept; NULL when it fits. */ static char *mcp_cut_middle(const char *text, const char *where) { size_t len = strlen(text), head = MCP_OUTPUT_MAX / 2, tail, lines = 0, removed = 0; sqlite3_str *t; char *res, *out; if (len <= MCP_OUTPUT_MAX) { return NULL; } while (head > 0 && ((unsigned char)text[head] & 0xc0) == 0x80) { head--; } tail = len - (MCP_OUTPUT_MAX - MCP_OUTPUT_MAX / 2); while (tail < len && ((unsigned char)text[tail] & 0xc0) == 0x80) { tail++; } for (size_t i = head; i < tail; i++) { removed += ((unsigned char)text[i] & 0xc0) != 0x80; } for (size_t i = 0; i < len; i++) { lines += text[i] == '\n'; } lines += text[len - 1] != '\n'; t = sqlite3_str_new(NULL); sqlite3_str_appendf(t, "Warning: truncated output (original token count: %llu)\nTotal output lines: %llu\n\n", (unsigned long long)((len + 3) / 4), (unsigned long long)lines); sqlite3_str_append(t, text, (int)head); sqlite3_str_appendf(t, "\xe2\x80\xa6%llu chars truncated\xe2\x80\xa6", (unsigned long long)removed); sqlite3_str_appendall(t, text + tail); if (where) { sqlite3_str_appendf(t, "\n\n[Full output: %s (read it with the read tool, with offset and limit)]", where); } res = sqlite3_str_finish(t); out = res ? strdup(res) : NULL; sqlite3_free(res); return out; } /* A tools/call result as the text the model gets (malloc'd), and whether it is an error. */ static char *mcp_result_text(const char *result, int *is_error) { char *text = mcp_jtext( "SELECT group_concat(CASE json_extract(value, '$.type')" " WHEN 'text' THEN json_extract(value, '$.text')" " WHEN 'image' THEN '[image: ' || coalesce(json_extract(value, '$.mimeType'), 'unknown type') || ']'" " WHEN 'audio' THEN '[audio: ' || coalesce(json_extract(value, '$.mimeType'), 'unknown type') || ']'" " WHEN 'resource_link' THEN '[resource: ' || coalesce(json_extract(value, '$.uri'), '') || ']'" " WHEN 'resource' THEN coalesce(json_extract(value, '$.resource.text')," " '[resource: ' || coalesce(json_extract(value, '$.resource.uri'), '') || ']')" " ELSE '[' || coalesce(json_extract(value, '$.type'), 'content') || ']' END, char(10))" " FROM json_each(?1, '$.content') WHERE json_type(?1, '$.content') = 'array'", result, NULL); *is_error = (int)mcp_jint("SELECT coalesce(json_extract(?1, '$.isError') = 1, 0)", result, NULL, 0); if (!text || !*text) { free(text); text = mcp_jtext("SELECT json(json_extract(?1, '$.structuredContent'))" " WHERE json_type(?1, '$.structuredContent') IS NOT NULL", result, NULL); } return text ? text : strdup("(no output)"); } static char *mcp_fmt(int *is_error, int err, const char *fmt, ...) { char buf[PIC_ERR_CAP + 256]; va_list ap; va_start(ap, fmt); (void)vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); *is_error = err; return strdup(buf); } /* A stdio server kept running for the rest of this process once called (a request's calls to one * stdio server run one by one, in pic), stopped when it exits. */ typedef struct { const mcp_row *row; pid_t pid; pic_mcp_conn *c; mcp_live l; } mcp_kept; static mcp_kept mcp_kept_conns[16]; static size_t mcp_nkept; static void mcp_kept_drop(mcp_kept *k) { if (k->pid == getpid()) { pic_mcp_close(k->c); mcp_live_free(&k->l); } k->c = NULL; k->row = NULL; } static void mcp_kept_stop(void) { for (size_t i = 0; i < mcp_nkept; i++) { mcp_kept_drop(&mcp_kept_conns[i]); } } /* Calls TOOL of R with ARGUMENTS (a JSON object): the text and *IS_ERROR, malloc'd, with the * whole text in *FULL (malloc'd) when it was cut and WHERE names where that is kept. KEEP: a * stdio server stays running for the next call in this process. */ static char *mcp_row_call(const mcp_row *r, const char *workspace, const char *tool, const char *arguments, int quiet, int keep, const char *where, char **full, int *is_error) { char err[PIC_ERR_CAP], *params, *result, *text, *cut; pic_mcp_conn *c = NULL; mcp_kept *k = NULL; mcp_live own, *l = &own; int answered = 0; *full = NULL; err[0] = '\0'; keep = keep && r->command; for (size_t i = 0; keep && i < mcp_nkept && !k; i++) { if (mcp_kept_conns[i].row == r && mcp_kept_conns[i].pid == getpid() && mcp_kept_conns[i].c) { k = &mcp_kept_conns[i]; } } params = mcp_jtext("SELECT json_object('name', ?1, 'arguments', json(?2))", tool, arguments); if (!params) { return mcp_fmt(is_error, 1, "the tool's input is not a JSON object"); } if (k) { l = &k->l; c = k->c; } else { if (mcp_live_open(r, workspace, quiet, &own, err, sizeof err) != 0) { free(params); return mcp_fmt(is_error, 1, "MCP server %s: %s; the tool did not run", r->name, err); } if (keep && mcp_nkept < sizeof mcp_kept_conns / sizeof mcp_kept_conns[0]) { k = &mcp_kept_conns[mcp_nkept++]; k->row = r; k->pid = getpid(); k->l = own; l = &k->l; if (mcp_nkept == 1) { (void)atexit(mcp_kept_stop); } } c = pic_mcp_open(&l->t, err, sizeof err); if (k) { k->c = c; } } result = c ? pic_mcp_ask(c, "tools/call", params, tool, &answered, err, sizeof err) : NULL; free(params); if (!result) { int reached = c != NULL && strncmp(err, "cannot connect", 14) != 0; mcp_live_scrub(l, err); if (k) { mcp_kept_drop(k); /* a failed server starts again on the next call */ } else { pic_mcp_close(c); mcp_live_free(l); } if (!reached) { return mcp_fmt(is_error, 1, "MCP server %s could not be reached: %s; the tool did not run", r->name, err); } return mcp_fmt(is_error, 1, answered ? "MCP server %s: %s" : "MCP server %s did not answer: %s. Whether the call ran there is not known", r->name, err); } if (!k) { pic_mcp_close(c); mcp_live_free(l); } text = mcp_result_text(result, is_error); free(result); if (text && (cut = mcp_cut_middle(text, where))) { *full = text; return cut; } return text; } /* ---- the registry ---------------------------------------------------------------------------- */ typedef struct { pic_tool_def def; char *name, *schema, *tool; size_t server; } mcp_tool; static mcp_row *mcp_reg_rows; static size_t mcp_reg_nrows; static mcp_tool *mcp_reg_tools; static size_t mcp_reg_ntools; static int mcp_on(void) { return 1; } static char *mcp_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *h, int *is_error) { const mcp_tool *t = state; const char *input = h->input && *h->input ? h->input : "{}"; char *full = NULL, *out; (void)tool; *is_error = 0; if (h->started == NULL || h->started(h->ctx, NULL, 0) != 0) { return NULL; } if (args->bad_input) { return mcp_fmt(is_error, 1, "%s", args->bad_input); } if (mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", input, NULL, 0) != 1) { return mcp_fmt(is_error, 1, "the input of %s is not a JSON object", t->name); } out = mcp_row_call(&mcp_reg_rows[t->server], workspace, t->tool, input, 1, 1, h->output && h->output_name ? h->output_name : NULL, &full, is_error); if (full && h->output && h->output_name) { h->output->data = full; h->output->len = strlen(full); } else { free(full); } return out; } /* mcp__SERVER__TOOL with every character but letters, digits and '_' as '_' (Pi's and Codex's * rule), into out; a name over 64 characters, or one TAKEN, ends in '_' and 8 hex digits of * SHA-256 over SERVER, NUL, TOOL. */ static void mcp_tool_name(const char *server, const char *tool, int taken, char *out, size_t cap) { char name[512]; size_t n; (void)snprintf(name, sizeof name, "mcp__%s__%s", server, tool); for (char *p = name; *p; p++) { if (!isalnum((unsigned char)*p) && *p != '_') { *p = '_'; } } n = strlen(name); if (n <= 64 && !taken) { (void)snprintf(out, cap, "%s", name); return; } { unsigned char sum[32]; pic_noise_sha256(sum, server, strlen(server) + 1, tool, strlen(tool)); (void)snprintf(out, cap, "%.*s_%02x%02x%02x%02x", (int)(n < 55 ? n : 55), name, sum[0], sum[1], sum[2], sum[3]); } } int pic_mcp_register(void) { sqlite3 *db = mcp_jdb(); size_t total = 0; if (mcp_reg_rows || !db) { return mcp_reg_rows ? (int)mcp_reg_ntools : -1; } if (mcp_rows_load(NULL, &mcp_reg_rows, &mcp_reg_nrows) != 0) { return -1; } for (size_t i = 0; i < mcp_reg_nrows; i++) { total += mcp_reg_rows[i].enabled && mcp_reg_rows[i].tools ? (size_t)mcp_jint("SELECT json_array_length(?1)", mcp_reg_rows[i].tools, NULL, 0) : 0; } if (!total || !(mcp_reg_tools = calloc(total, sizeof *mcp_reg_tools))) { return 0; } for (size_t i = 0; i < mcp_reg_nrows; i++) { const mcp_row *r = &mcp_reg_rows[i]; sqlite3_stmt *q = NULL; size_t first = mcp_reg_ntools; if (!r->enabled || !r->tools || (r->exposure && strcmp(r->exposure, "hidden") == 0) || sqlite3_prepare_v2(db, "SELECT json_extract(value, '$.name'), coalesce(json_extract(value, '$.description'), '')," " json(json_extract(value, '$.inputSchema'))," " coalesce(json_extract(value, '$.annotations.readOnlyHint') = 1, 0)" " FROM json_each(?1) WHERE json_type(value, '$.name') = 'text'" " AND json_type(value, '$.inputSchema') = 'object'", -1, &q, NULL) != SQLITE_OK) { sqlite3_finalize(q); continue; } sqlite3_bind_text(q, 1, r->tools, -1, SQLITE_STATIC); while (mcp_reg_ntools < total && sqlite3_step(q) == SQLITE_ROW) { mcp_tool *t = &mcp_reg_tools[mcp_reg_ntools]; char plain[128]; t->tool = strdup((const char *)sqlite3_column_text(q, 0)); mcp_tool_name(r->name, t->tool ? t->tool : "", 0, plain, sizeof plain); t->name = strdup(plain); t->schema = mcp_jtext3(NULL, "SELECT json_object('name', ?1, 'description', ?2, 'input_schema', json(?3))", plain, (const char *)sqlite3_column_text(q, 1), (const char *)sqlite3_column_text(q, 2)); t->def.replay_safe = sqlite3_column_int(q, 3); t->server = i; if (!t->tool || !t->name || !t->schema) { free(t->tool); free(t->name); free(t->schema); memset(t, 0, sizeof *t); continue; } mcp_reg_ntools++; } sqlite3_finalize(q); /* tools of one server whose names come out the same all get the hash, as do long ones */ for (size_t ta = first; ta < mcp_reg_ntools; ta++) { for (size_t tb = first; tb < mcp_reg_ntools; tb++) { if (ta != tb && strcmp(mcp_reg_tools[ta].name, mcp_reg_tools[tb].name) == 0) { mcp_reg_tools[ta].def.builtin = 1; /* marked for the hash; cleared below */ } } } for (size_t ta = first; ta < mcp_reg_ntools; ta++) { mcp_tool *t = &mcp_reg_tools[ta]; if (t->def.builtin || strlen(t->name) > 64) { char named[128], *withname; mcp_tool_name(r->name, t->tool, 1, named, sizeof named); if ((withname = mcp_jtext3(NULL, "SELECT json_set(?1, '$.name', ?2)", t->schema, named, NULL))) { free(t->schema); t->schema = withname; } free(t->name); t->name = strdup(named); } } } for (size_t k = 0; k < mcp_reg_ntools; k++) { mcp_tool *t = &mcp_reg_tools[k]; if (!t->name) { continue; } t->def.name = t->name; t->def.schema = t->schema; t->def.sequential = mcp_reg_rows[t->server].command != NULL; /* one pipe per stdio server */ t->def.tier = PIC_TIER_BUNDLED; t->def.builtin = 0; t->def.by_default = mcp_on; t->def.run = mcp_run; t->def.state = t; (void)pic_tool_register(&t->def); } return (int)mcp_reg_ntools; } /* ---- pic mcp ------------------------------------------------------------------------------- */ static int mcp_load_one(const char *name, mcp_row **rows, size_t *n) { if (mcp_rows_load(name, rows, n) != 0) { fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr); return -1; } if (*n == 0) { fprintf(stderr, "pic: no MCP server is saved as %s (pic mcp list)\n", name); free(*rows); return -1; } return 0; } /* Saves S, connects and lists its tools, and says so. The exit status. */ static int mcp_add_spec(mcp_spec *s) { char err[PIC_ERR_CAP] = "", era[32]; mcp_row *rows; size_t n; int count, sealed = s->nheaders || s->nenv; if (mcp_spec_save(s, err, sizeof err) != 0) { fprintf(stderr, "pic: %s\n", err); return 1; } if (mcp_load_one(s->name, &rows, &n) != 0) { return 1; } count = mcp_row_refresh(&rows[0], era, sizeof era, err, sizeof err); if (count < 0) { printf("Added %s (%s).%s\n", s->name, s->url ? s->url : "stdio", !sealed ? "" : s->url ? " Its headers are sealed." : " Its environment is sealed."); fprintf(stderr, "pic: %s could not be reached, so it has no tools yet: %s (pic mcp list tries again)\n", s->name, err); mcp_rows_free(rows, n); return 1; } printf("Added %s (%s): %d tool%s, MCP %s.%s\n", s->name, s->url ? s->url : "stdio", count, count == 1 ? "" : "s", era, !sealed ? "" : s->url ? " Its headers are sealed in the credential store." : " Its environment is sealed in the credential store."); mcp_rows_free(rows, n); return 0; } static int mcp_cmd_add(int argc, char **argv) { char err[PIC_ERR_CAP] = ""; mcp_spec s; int rc; if (argc >= 1 && argv[0][0] == '{') { /* a pasted mcpServers snippet */ sqlite3 *db = mcp_jdb(); sqlite3_stmt *q = NULL; int added = 0; rc = 0; if (argc != 1 || mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", argv[0], NULL, 0) != 1) { fputs("pic: pic mcp add '{\"mcpServers\":{...}}' takes one JSON object\n", stderr); return 2; } if (!db || sqlite3_prepare_v2(db, "SELECT key, value FROM json_each(?1, CASE WHEN json_type(?1, '$.mcpServers') = 'object'" " THEN '$.mcpServers' ELSE '$' END) WHERE type = 'object'", -1, &q, NULL) != SQLITE_OK) { return 1; } sqlite3_bind_text(q, 1, argv[0], -1, SQLITE_STATIC); while (sqlite3_step(q) == SQLITE_ROW) { if (mcp_spec_json((const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1), &s, err, sizeof err) != 0) { fprintf(stderr, "pic: %s\n", err); rc = 1; } else { rc |= mcp_add_spec(&s); added++; } mcp_spec_free(&s); } sqlite3_finalize(q); if (!added && !rc) { fputs("pic: the snippet names no server\n", stderr); return 1; } return rc; } if (mcp_spec_parse(argc, argv, &s, err, sizeof err) != 0) { fprintf(stderr, "pic: %s\n", err); mcp_spec_free(&s); return 2; } rc = mcp_add_spec(&s); mcp_spec_free(&s); return rc; } /* pic mcp add-json NAME JSON, as Claude Code's. */ static int mcp_cmd_add_json(int argc, char **argv) { char err[PIC_ERR_CAP] = ""; mcp_spec s; int rc; if (argc != 2 || mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", argv[1], NULL, 0) != 1) { fputs("pic: pic mcp add-json NAME '{\"type\":\"http\",\"url\":...}'\n", stderr); return 2; } if (mcp_spec_json(argv[0], argv[1], &s, err, sizeof err) != 0) { fprintf(stderr, "pic: %s\n", err); mcp_spec_free(&s); return 2; } rc = mcp_add_spec(&s); mcp_spec_free(&s); return rc; } static int mcp_cmd_list(int argc, char **argv) { mcp_row *rows; size_t n, width = 4; int rc = 0; (void)argv; if (argc != 0) { fputs("pic: pic mcp list takes no arguments\n", stderr); return 2; } if (mcp_rows_load(NULL, &rows, &n) != 0) { fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr); return 1; } if (n == 0) { puts("No MCP servers (pic mcp add NAME URL adds one)."); free(rows); return 0; } for (size_t i = 0; i < n; i++) { width = strlen(rows[i].name) > width ? strlen(rows[i].name) : width; } for (size_t i = 0; i < n; i++) { mcp_row *r = &rows[i]; char err[PIC_ERR_CAP] = "", era[32] = ""; int count = -1; if (r->enabled) { count = mcp_row_refresh(r, era, sizeof era, err, sizeof err); } printf("%-*s %-5s %-10s ", (int)width, r->name, r->transport, era[0] ? era : (r->era ? r->era : "-")); if (!r->enabled) { printf("%lld tools disabled\n", mcp_jint("SELECT json_array_length(?1)", r->tools, NULL, 0)); } else if (count < 0) { printf("%lld tools not connected: %s\n", mcp_jint("SELECT json_array_length(?1)", r->tools, NULL, 0), err); rc = 1; } else { printf("%d tool%s connected\n", count, count == 1 ? "" : "s"); } } mcp_rows_free(rows, n); return rc; } static int mcp_cmd_get(int argc, char **argv) { sqlite3 *db = mcp_jdb(); sqlite3_stmt *q = NULL; mcp_row *rows, *r; size_t n; char *hn, *en; if (argc != 1) { fputs("pic: pic mcp get NAME\n", stderr); return 2; } if (mcp_load_one(argv[0], &rows, &n) != 0) { return 1; } r = &rows[0]; printf("%s\n transport: %s\n", r->name, r->transport); if (r->url) { printf(" url: %s\n", r->url); } if (r->command) { char *cmd = mcp_jtext("SELECT group_concat(value, ' ') FROM json_each(?1)", r->command, NULL); printf(" command: %s\n", cmd ? cmd : ""); free(cmd); } if (r->cwd) { printf(" cwd: %s\n", r->cwd); } hn = mcp_jtext("SELECT group_concat(value, ', ') FROM json_each(?1)", r->header_names, NULL); en = mcp_jtext("SELECT group_concat(value, ', ') FROM json_each(?1)", r->env_names, NULL); if (hn) { printf(" headers: %s (values sealed)\n", hn); } if (en) { printf(" environment: %s (values sealed)\n", en); } free(hn); free(en); if (r->description) { printf(" description: %s\n", r->description); } printf(" MCP revision: %s\n timeout: %d seconds\n %s\n", r->era ? r->era : "not yet connected", r->timeout, r->enabled ? "enabled" : "disabled"); if (r->exposure) { printf(" exposure: %s\n", r->exposure); } if (r->error) { printf(" last error: %s\n", r->error); } if (db && r->tools && sqlite3_prepare_v2(db, "SELECT json_extract(value, '$.name')," " coalesce(json_extract(value, '$.annotations.readOnlyHint') = 1, 0)" " FROM json_each(?1)", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, r->tools, -1, SQLITE_STATIC); printf(" tools:\n"); while (sqlite3_step(q) == SQLITE_ROW) { char name[128]; mcp_tool_name(r->name, (const char *)sqlite3_column_text(q, 0), 0, name, sizeof name); printf(" %s %s\n", name, sqlite3_column_int(q, 1) ? "read-only: run again after a crash" : "outcome unknown after a crash"); } } sqlite3_finalize(q); mcp_rows_free(rows, n); return 0; } static int mcp_cmd_remove(int argc, char **argv) { int r; if (argc != 1) { fputs("pic: pic mcp remove NAME\n", stderr); return 2; } if ((r = mcp_row_remove(argv[0])) < 0) { fputs("pic: cannot remove the server from ~/.pic/pic.sqlite\n", stderr); return 1; } if (r == 0) { fprintf(stderr, "pic: no MCP server is saved as %s (pic mcp list)\n", argv[0]); return 1; } printf("Removed %s and its sealed headers and environment.\n", argv[0]); return 0; } /* pic mcp call SERVER TOOL [JSON]: the tool's text on stdout; 1 when it is an error. */ static int mcp_cmd_call(int argc, char **argv) { mcp_row *rows; size_t n; char *full = NULL, *out; int is_error = 0; if (argc < 2 || argc > 3) { fputs("pic: pic mcp call SERVER TOOL ['{\"arg\":...}']\n", stderr); return 2; } if (argc == 3 && mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", argv[2], NULL, 0) != 1) { fputs("pic: the tool's arguments are a JSON object\n", stderr); return 2; } if (mcp_load_one(argv[0], &rows, &n) != 0) { return 1; } out = mcp_row_call(&rows[0], NULL, argv[1], argc == 3 ? argv[2] : "{}", 0, 0, NULL, &full, &is_error); printf("%s\n", full ? full : out ? out : ""); free(full); free(out); mcp_rows_free(rows, n); return is_error ? 1 : 0; } int pic_mcp_command(int argc, char **argv) { const char *verb = argc > 0 ? argv[0] : "list"; if (strcmp(verb, "add") == 0) { return mcp_cmd_add(argc - 1, argv + 1); } if (strcmp(verb, "add-json") == 0) { return mcp_cmd_add_json(argc - 1, argv + 1); } if (strcmp(verb, "list") == 0) { return mcp_cmd_list(argc > 0 ? argc - 1 : 0, argv + 1); } if (strcmp(verb, "get") == 0) { return mcp_cmd_get(argc - 1, argv + 1); } if (strcmp(verb, "remove") == 0) { return mcp_cmd_remove(argc - 1, argv + 1); } if (strcmp(verb, "call") == 0) { return mcp_cmd_call(argc - 1, argv + 1); } fputs("pic: pic mcp add | add-json | list | get NAME | remove NAME | call SERVER TOOL [JSON] (pic help mcp)\n", stderr); return 2; }