Skip to content
pi-c Artifact [0ee39522d1]
Login

Artifact [0ee39522d1]

Artifact 0ee39522d13286509bd34227080657bf70f1119b13ed31d475ce86e1b9dedffa:


/* 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 <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#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;
    /* A trusted project's server: the file it is in, its entry there (headers and environment as
     * written, not sealed) and the workspace's real path; all NULL for one of the user's. */
    char *source, *entry, *workspace;
} 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);
    free(r->source);
    free(r->entry);
    free(r->workspace);
    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));
}

static int mcp_project_merge(const char *workspace, const char *only, mcp_row **rows, size_t *n);

/* Every server (or NAME's) into *OUT: the user's, by name, then a trusted WORKSPACE's own (NULL:
 * none). 0, or -1 when the database cannot be read. */
static int mcp_rows_load(const char *workspace, 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 mcp_project_merge(workspace, name, out, n);
}

/* A small file whole (malloc'd), or NULL. */
static char *mcp_slurp(const char *path) {
    FILE *f = fopen(path, "rb");
    char *buf = NULL;
    long len;
    if (!f) {
        return NULL;
    }
    if (fseek(f, 0, SEEK_END) == 0 && (len = ftell(f)) >= 0 && len < (1L << 20) && fseek(f, 0, SEEK_SET) == 0 &&
        (buf = malloc((size_t)len + 1))) {
        if (fread(buf, 1, (size_t)len, f) == (size_t)len) {
            buf[len] = '\0';
        } else {
            free(buf);
            buf = NULL;
        }
    }
    fclose(f);
    return buf;
}

/* The project file names pic reads in a trusted workspace, the later winning: Claude Code's, then
 * pic's own (Pi's is .pi/mcp.json). Neither is ever written. */
static const char *const mcp_project_files[] = {".mcp.json", ".pic/mcp.json"};

/* NAME's entry ENTRY from the project file PATH as a row (its tool list from the cache when the
 * entry is the one listed). */
static int mcp_project_row(const char *real, const char *path, const char *name, const char *entry, mcp_row *r) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    char err[PIC_ERR_CAP] = "";
    mcp_spec spec;
    memset(r, 0, sizeof *r);
    r->name = strdup(name);
    r->source = strdup(path);
    r->entry = strdup(entry);
    r->workspace = strdup(real);
    r->url = mcp_jtext("SELECT json_extract(?1, '$.url') WHERE json_type(?1, '$.url') = 'text'", entry, NULL);
    r->transport = strdup(r->url ? "http" : "stdio");
    r->command = mcp_jtext("SELECT json_group_array(v) FROM (SELECT 0 k, json_extract(?1, '$.command') v"
                           " WHERE json_type(?1, '$.command') = 'text' UNION ALL SELECT 1 + key, value"
                           " FROM json_each(?1, '$.args') WHERE json_type(?1, '$.args') = 'array' ORDER BY k)"
                           " WHERE json_type(?1, '$.command') = 'text'",
                           entry, NULL);
    r->cwd = mcp_jtext("SELECT json_extract(?1, '$.cwd') WHERE json_type(?1, '$.cwd') = 'text'", entry, NULL);
    r->header_names = mcp_jtext("SELECT json_group_array(key) FROM json_each(?1, '$.headers')"
                                " WHERE json_type(?1, '$.headers') = 'object'",
                                entry, NULL);
    r->env_names = mcp_jtext("SELECT json_group_array(key) FROM json_each(?1, '$.env') WHERE json_type(?1, '$.env') = 'object'",
                             entry, NULL);
    r->description = mcp_jtext("SELECT json_extract(?1, '$.description') WHERE json_type(?1, '$.description') = 'text'",
                               entry, NULL);
    r->exposure = mcp_jtext("SELECT json_extract(?1, '$.exposure') WHERE json_type(?1, '$.exposure') = 'text'", entry, NULL);
    r->timeout = (int)mcp_jint("SELECT json_extract(?1, '$.timeout') WHERE json_type(?1, '$.timeout') = 'integer'", entry,
                               NULL, MCP_TIMEOUT);
    r->enabled = mcp_jint("SELECT json_type(?1, '$.enabled') <> 'false'", entry, NULL, 1) != 0;
    if (mcp_spec_json(name, entry, &spec, err, sizeof err) != 0) {
        r->error = strdup(err);
        r->enabled = 0;
    }
    mcp_spec_free(&spec);
    if (db && sqlite3_prepare_v2(db,
                                 "SELECT era, tools, coalesce(listed_ms, 0), error FROM picu_mcp_project"
                                 " WHERE workspace = ?1 AND name = ?2 AND entry = json(?3)",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, real, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, name, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 3, entry, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            r->era = mcp_col_dup(q, 0);
            r->tools = mcp_col_dup(q, 1);
            r->listed_ms = sqlite3_column_int64(q, 2);
            if (!r->error) {
                r->error = mcp_col_dup(q, 3);
            }
        }
    }
    sqlite3_finalize(q);
    if (!r->tools) {
        r->tools = strdup("[]");
    }
    return r->name && r->source && r->entry && r->workspace && r->transport && r->tools ? 0 : -1;
}

/* A trusted WORKSPACE's servers (or ONLY's), merged into ROWS: each replaces the user's server of
 * its name; an entry with no command, url or type only turns the user's on or off and sets its
 * exposure, as in Pi. 0, or -1 out of memory. */
static int mcp_project_merge(const char *workspace, const char *only, mcp_row **rows, size_t *n) {
    char real[PATH_MAX];
    sqlite3 *db = mcp_jdb();
    if (!workspace || !db || !realpath(workspace, real) || pic_trust_get(real) != 1) {
        return 0;
    }
    for (size_t f = 0; f < sizeof mcp_project_files / sizeof mcp_project_files[0]; f++) {
        char path[PATH_MAX + 32], *text;
        sqlite3_stmt *q = NULL;
        (void)snprintf(path, sizeof path, "%s/%s", real, mcp_project_files[f]);
        if (!(text = mcp_slurp(path))) {
            continue;
        }
        if (sqlite3_prepare_v2(db,
                               "SELECT key, json(value) FROM json_each(?1, '$.mcpServers') WHERE json_valid(?1)"
                               " AND json_type(?1, '$.mcpServers') = 'object' AND type = 'object'",
                               -1, &q, NULL) != SQLITE_OK) {
            free(text);
            continue;
        }
        sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            const char *name = (const char *)sqlite3_column_text(q, 0), *entry = (const char *)sqlite3_column_text(q, 1);
            size_t at = *n;
            mcp_row r;
            if (only && strcmp(name, only) != 0) {
                continue;
            }
            for (size_t i = 0; i < *n; i++) {
                at = strcmp((*rows)[i].name, name) == 0 ? i : at;
            }
            if (!mcp_jint("SELECT json_type(?1, '$.command') IS NOT NULL OR json_type(?1, '$.url') IS NOT NULL"
                          " OR json_type(?1, '$.type') IS NOT NULL",
                          entry, NULL, 0)) {
                if (at < *n) { /* an override of the user's server */
                    char *x = mcp_jtext("SELECT json_extract(?1, '$.exposure') WHERE json_type(?1, '$.exposure') = 'text'",
                                        entry, NULL);
                    (*rows)[at].enabled = mcp_jint("SELECT json_type(?1, '$.enabled') <> 'false'", entry, NULL, 1) != 0;
                    if (x) {
                        free((*rows)[at].exposure);
                        (*rows)[at].exposure = x;
                    }
                }
                continue;
            }
            if (mcp_project_row(real, path, name, entry, &r) != 0) {
                mcp_row_free(&r);
                continue;
            }
            if (at < *n) {
                mcp_row_free(&(*rows)[at]);
                (*rows)[at] = r;
            } else {
                mcp_row *grown = realloc(*rows, (*n + 1) * sizeof **rows);
                if (!grown) {
                    mcp_row_free(&r);
                    break;
                }
                *rows = grown;
                (*rows)[(*n)++] = r;
            }
        }
        sqlite3_finalize(q);
        free(text);
    }
    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 R's listing: ERA and TOOLS when it worked (TOOLS not NULL), else ERROR. A project's
 * server is recorded for its workspace and entry. */
static void mcp_row_note(const mcp_row *r, const char *era, const char *tools, const char *error) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    const char *name = r->name;
    if (db && r->source) {
        if (sqlite3_prepare_v2(db,
                               "INSERT INTO picu_mcp_project(workspace, name, entry, era, tools, listed_ms, error)"
                               " VALUES(?1, ?2, json(?3), ?4, coalesce(json(?5), '[]'), ?6, ?7)"
                               " ON CONFLICT(workspace, name) DO UPDATE SET"
                               " era = iif(?5 IS NULL AND entry = excluded.entry, era, excluded.era),"
                               " tools = iif(?5 IS NULL AND entry = excluded.entry, tools, excluded.tools),"
                               " listed_ms = iif(?5 IS NULL AND entry = excluded.entry, listed_ms, excluded.listed_ms),"
                               " entry = excluded.entry, error = excluded.error",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, r->workspace, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 2, name, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 3, r->entry, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 4, era, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 5, tools, -1, SQLITE_STATIC);
            if (tools) {
                sqlite3_bind_int64(q, 6, mcp_now_ms());
            }
            sqlite3_bind_text(q, 7, tools ? NULL : error, -1, SQLITE_STATIC);
            (void)sqlite3_step(q);
        }
        sqlite3_finalize(q);
        return;
    }
    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) {
    const char *doc,
        *values_sql = "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')";
    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 CAST(value AS TEXT) FROM json_each(?1) WHERE type IN ('text', 'integer', 'real')", -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) */
        workspace = r->workspace ? r->workspace : workspace;
        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->entry) { /* a project's server: its values as the trusted file writes them */
        doc = r->entry;
        values_sql = "SELECT 'h', key, value FROM json_each(?1, '$.headers') WHERE type = 'text'"
                     " UNION ALL SELECT 'e', key, CAST(value AS TEXT) FROM json_each(?1, '$.env')"
                     " WHERE type IN ('text', 'integer', 'real')";
        goto values;
    }
    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;
    }
    doc = plain;
values:
    if (sqlite3_prepare_v2(db, values_sql, -1, &q, NULL) != SQLITE_OK) {
        goto oom;
    }
    sqlite3_bind_text(q, 1, doc, -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, 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, 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, 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(const char *workspace) {
    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(workspace, 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 const char *mcp_cli_ws; /* the workspace pic mcp was given, or the current directory */

static int mcp_load_one(const char *name, mcp_row **rows, size_t *n) {
    if (mcp_rows_load(mcp_cli_ws, 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. */
/* Saves S, connects and lists its tools: 0 with *COUNT and ERA; 1 saved but not reached (err
 * says why); -1 not saved, with err. */
static int mcp_add_quiet(mcp_spec *s, int *count, char *era, size_t eracap, char *err, size_t errcap) {
    mcp_row *rows;
    size_t n;
    *count = 0;
    era[0] = '\0';
    if (mcp_spec_save(s, err, errcap) != 0) {
        return -1;
    }
    if (mcp_rows_load(NULL, s->name, &rows, &n) != 0 || n == 0) {
        free(rows);
        (void)snprintf(err, errcap, "cannot read ~/.pic/pic.sqlite");
        return -1;
    }
    *count = mcp_row_refresh(&rows[0], era, eracap, err, errcap);
    mcp_rows_free(rows, n);
    return *count < 0 ? (*count = 0, 1) : 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];
    int count, sealed = s->nheaders || s->nenv, rc = mcp_add_quiet(s, &count, era, sizeof era, err, sizeof err);
    if (rc < 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    if (rc > 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);
        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.");
    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(mcp_cli_ws, 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->source) {
            printf("project  ");
        }
        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->source) {
        printf("  from: %s (the project's; its values are kept there, not sealed)\n", r->source);
    }
    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%s\n", hn, r->source ? "" : " (values sealed)");
    }
    if (en) {
        printf("  environment: %s%s\n", en, r->source ? "" : " (values sealed)");
    }
    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;
}

/* The project file NAME comes from in the workspace, into OUT; 0 when it is not a project's. */
static int mcp_project_source(const char *workspace, const char *name, char *out, size_t cap) {
    mcp_row *rows = NULL;
    size_t n = 0;
    int found = 0;
    if (mcp_project_merge(workspace, name, &rows, &n) == 0) {
        for (size_t i = 0; i < n; i++) {
            if (rows[i].source) {
                (void)snprintf(out, cap, "%s", rows[i].source);
                found = 1;
            }
        }
    }
    mcp_rows_free(rows, n);
    return found;
}

static int mcp_cmd_remove(int argc, char **argv) {
    char src[PATH_MAX + 32];
    int r;
    if (argc != 1) {
        fputs("pic: pic mcp remove NAME\n", stderr);
        return 2;
    }
    if (mcp_project_source(mcp_cli_ws, argv[0], src, sizeof src)) {
        fprintf(stderr, "pic: %s is the project's, in %s; pic does not change that file\n", argv[0], src);
        return 1;
    }
    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;
}

/* ---- the RPC commands --------------------------------------------------------------------- */

static int mcp_rpc_done(pic_rpc_call *c, sqlite3_str *t) {
    char *res = sqlite3_str_finish(t);
    c->data = res ? strdup(res) : NULL;
    sqlite3_free(res);
    return c->data ? 0 : -1;
}

static void mcp_rpc_text(sqlite3_str *t, const char *key, const char *v) {
    sqlite3_str_appendf(t, ",\"%s\":", key);
    if (v) {
        pic_rpc_quote(t, v);
    } else {
        sqlite3_str_appendall(t, "null");
    }
}

/* get_mcp_servers: {"servers": [{name, source, transport, url, command, cwd, headers, env,
 * description, exposure, timeout, enabled, era, error, listedAt, tools: [{name, tool,
 * readOnly}]}]}, as saved: nothing is connected. */
static int mcp_get_answer(pic_rpc_call *c) {
    sqlite3 *db = mcp_jdb();
    sqlite3_str *t;
    mcp_row *rows;
    size_t n;
    if (!db || mcp_rows_load(c->workspace, NULL, &rows, &n) != 0) {
        (void)snprintf(c->err, sizeof c->err, "cannot read ~/.pic/pic.sqlite");
        return -1;
    }
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"servers\":[");
    for (size_t i = 0; i < n; i++) {
        mcp_row *r = &rows[i];
        sqlite3_stmt *q = NULL;
        char *cmd = r->command ? mcp_jtext("SELECT group_concat(value, ' ') FROM json_each(?1)", r->command, NULL) : NULL;
        sqlite3_str_appendall(t, i ? ",{\"name\":" : "{\"name\":");
        pic_rpc_quote(t, r->name);
        mcp_rpc_text(t, "source", r->source ? r->source : "user");
        mcp_rpc_text(t, "transport", r->transport);
        mcp_rpc_text(t, "url", r->url);
        mcp_rpc_text(t, "command", cmd);
        mcp_rpc_text(t, "cwd", r->cwd);
        sqlite3_str_appendf(t, ",\"headers\":%s,\"env\":%s", r->header_names ? r->header_names : "[]",
                            r->env_names ? r->env_names : "[]");
        mcp_rpc_text(t, "description", r->description);
        mcp_rpc_text(t, "exposure", r->exposure);
        sqlite3_str_appendf(t, ",\"timeout\":%d,\"enabled\":%s", r->timeout, r->enabled ? "true" : "false");
        mcp_rpc_text(t, "era", r->era);
        mcp_rpc_text(t, "error", r->error);
        if (r->listed_ms) {
            sqlite3_str_appendf(t, ",\"listedAt\":%lld", r->listed_ms);
        } else {
            sqlite3_str_appendall(t, ",\"listedAt\":null");
        }
        sqlite3_str_appendall(t, ",\"tools\":[");
        if (sqlite3_prepare_v2(db,
                               "SELECT json_extract(value, '$.name'),"
                               " coalesce(json_extract(value, '$.annotations.readOnlyHint') = 1, 0)"
                               " FROM json_each(?1) WHERE json_type(value, '$.name') = 'text'",
                               -1, &q, NULL) == SQLITE_OK) {
            int first = 1;
            sqlite3_bind_text(q, 1, r->tools ? r->tools : "[]", -1, SQLITE_STATIC);
            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);
                sqlite3_str_appendall(t, first ? "{\"name\":" : ",{\"name\":");
                pic_rpc_quote(t, name);
                mcp_rpc_text(t, "tool", (const char *)sqlite3_column_text(q, 0));
                sqlite3_str_appendf(t, ",\"readOnly\":%s}", sqlite3_column_int(q, 1) ? "true" : "false");
                first = 0;
            }
        }
        sqlite3_finalize(q);
        sqlite3_str_appendall(t, "]}");
        free(cmd);
    }
    sqlite3_str_appendall(t, "]}");
    mcp_rows_free(rows, n);
    return mcp_rpc_done(c, t);
}

/* add_mcp_server args: pic mcp add's arguments, as strings (a URL, a command, or one snippet):
 * {"servers": [{name, count, era, error}]}, error null for each reached; a server not reached is
 * kept. A refused argument list is an error. */
static int mcp_add_answer(pic_rpc_call *c) {
    sqlite3 *db = mcp_jdb();
    sqlite3_stmt *q = NULL;
    char **argv = NULL, *args = pic_rpc_text(c, "$.args");
    size_t argc = 0;
    sqlite3_str *t;
    int rc = -1, any = 0;
    if (!db || !args || mcp_jint("SELECT json_type(?1) = 'array'", args, NULL, 0) != 1) {
        free(args);
        (void)snprintf(c->err, sizeof c->err, "add_mcp_server needs args, pic mcp add's arguments as an array of strings");
        return -1;
    }
    if (sqlite3_prepare_v2(db, "SELECT CAST(value AS TEXT) FROM json_each(?1)", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, args, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            (void)mcp_push(&argv, &argc, (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    q = NULL;
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"servers\":[");
    if (argc == 1 && argv[0][0] == '{') { /* a snippet */
        if (sqlite3_prepare_v2(db,
                               "SELECT key, value FROM json_each(?1, CASE WHEN json_type(?1, '$.mcpServers') = 'object'"
                               " THEN '$.mcpServers' ELSE '$' END) WHERE json_valid(?1) AND type = 'object'",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, argv[0], -1, SQLITE_STATIC);
        }
    }
    for (int k = 0; argc > 0; k++) {
        mcp_spec s;
        char err[PIC_ERR_CAP] = "", era[32] = "";
        int count = 0, got;
        if (q) {
            if (sqlite3_step(q) != SQLITE_ROW) {
                break;
            }
            got = mcp_spec_json((const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1), &s, err,
                                sizeof err);
        } else if (k > 0) {
            break;
        } else {
            got = mcp_spec_parse((int)argc, argv, &s, err, sizeof err);
        }
        if (got != 0 || (got = mcp_add_quiet(&s, &count, era, sizeof era, err, sizeof err)) < 0) {
            mcp_spec_free(&s);
            (void)snprintf(c->err, sizeof c->err, "%s", err);
            goto done;
        }
        sqlite3_str_appendall(t, any ? ",{\"name\":" : "{\"name\":");
        pic_rpc_quote(t, s.name);
        sqlite3_str_appendf(t, ",\"count\":%d", count);
        mcp_rpc_text(t, "era", era[0] ? era : NULL);
        mcp_rpc_text(t, "error", got ? err : NULL);
        sqlite3_str_appendall(t, "}");
        any = 1;
        mcp_spec_free(&s);
    }
    if (!any) {
        (void)snprintf(c->err, sizeof c->err, "add_mcp_server: no server in the arguments");
        goto done;
    }
    sqlite3_str_appendall(t, "]}");
    rc = mcp_rpc_done(c, t);
    t = NULL;
done:
    if (t) {
        sqlite3_free(sqlite3_str_finish(t));
    }
    sqlite3_finalize(q);
    mcp_list_free(argv, argc, 1);
    free(args);
    return rc;
}

/* remove_mcp_server name: {"removed": true|false}; a project's server is the project file's. */
static int mcp_remove_answer(pic_rpc_call *c) {
    char *name = pic_rpc_text(c, "$.name"), src[PATH_MAX + 32];
    int r;
    if (!name) {
        (void)snprintf(c->err, sizeof c->err, "remove_mcp_server needs name");
        return -1;
    }
    if (mcp_project_source(c->workspace, name, src, sizeof src)) {
        (void)snprintf(c->err, sizeof c->err, "%s is the project's, in %s; pic does not change that file", name, src);
        free(name);
        return -1;
    }
    r = mcp_row_remove(name);
    free(name);
    if (r < 0) {
        (void)snprintf(c->err, sizeof c->err, "cannot remove the server from ~/.pic/pic.sqlite");
        return -1;
    }
    c->data = strdup(r ? "{\"removed\":true}" : "{\"removed\":false}");
    return c->data ? 0 : -1;
}

/* refresh_mcp_servers [name]: each enabled server (or that one) connected and listed again:
 * {"servers": [{name, count, era, error}]}. */
static int mcp_refresh_answer(pic_rpc_call *c) {
    char *name = pic_rpc_text(c, "$.name");
    mcp_row *rows;
    size_t n;
    sqlite3_str *t;
    int any = 0;
    if (mcp_rows_load(c->workspace, name, &rows, &n) != 0) {
        free(name);
        (void)snprintf(c->err, sizeof c->err, "cannot read ~/.pic/pic.sqlite");
        return -1;
    }
    free(name);
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"servers\":[");
    for (size_t i = 0; i < n; i++) {
        char err[PIC_ERR_CAP] = "", era[32] = "";
        int count;
        if (!rows[i].enabled) {
            continue;
        }
        count = mcp_row_refresh(&rows[i], era, sizeof era, err, sizeof err);
        sqlite3_str_appendall(t, any ? ",{\"name\":" : "{\"name\":");
        pic_rpc_quote(t, rows[i].name);
        sqlite3_str_appendf(t, ",\"count\":%d", count < 0 ? 0 : count);
        mcp_rpc_text(t, "era", era[0] ? era : NULL);
        mcp_rpc_text(t, "error", count < 0 ? err : NULL);
        sqlite3_str_appendall(t, "}");
        any = 1;
    }
    sqlite3_str_appendall(t, "]}");
    mcp_rows_free(rows, n);
    return mcp_rpc_done(c, t);
}

/* set_mcp_server_enabled name enabled: {"name", "enabled"}; a disabled server's tools are not
 * offered from the next request. A project's server is turned on or off in its file. */
static int mcp_enable_answer(pic_rpc_call *c) {
    char *name = pic_rpc_text(c, "$.name"), *on = pic_rpc_text(c, "$.enabled"), src[PATH_MAX + 32];
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1, yes = on && (strcmp(on, "1") == 0 || strcmp(on, "true") == 0);
    if (!name || !on) {
        (void)snprintf(c->err, sizeof c->err, "set_mcp_server_enabled needs name and enabled");
    } else if (mcp_project_source(c->workspace, name, src, sizeof src)) {
        (void)snprintf(c->err, sizeof c->err, "%s is the project's, in %s: set \"enabled\" there", name, src);
    } else if (db && sqlite3_prepare_v2(db, "UPDATE picu_mcp_server SET enabled = ?2 WHERE name = ?1", -1, &q, NULL) ==
                         SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_int(q, 2, yes);
        if (sqlite3_step(q) == SQLITE_DONE && sqlite3_changes(db) == 1) {
            sqlite3_str *t = sqlite3_str_new(NULL);
            sqlite3_str_appendall(t, "{\"name\":");
            pic_rpc_quote(t, name);
            sqlite3_str_appendf(t, ",\"enabled\":%s}", yes ? "true" : "false");
            rc = mcp_rpc_done(c, t);
        } else {
            (void)snprintf(c->err, sizeof c->err, "no MCP server is saved as %s", name);
        }
    }
    sqlite3_finalize(q);
    free(name);
    free(on);
    return rc;
}

#define MCP_RPC_FLAGS (PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE)
const pic_rpc_command pic_get_mcp_servers_rpc = {"get_mcp_servers", "the MCP servers and their saved tool lists",
                                                 MCP_RPC_FLAGS, mcp_get_answer};
const pic_rpc_command pic_add_mcp_server_rpc = {"add_mcp_server", "save an MCP server and list its tools", MCP_RPC_FLAGS,
                                                mcp_add_answer};
const pic_rpc_command pic_remove_mcp_server_rpc = {"remove_mcp_server", "forget an MCP server and its sealed values",
                                                   MCP_RPC_FLAGS, mcp_remove_answer};
const pic_rpc_command pic_refresh_mcp_servers_rpc = {"refresh_mcp_servers", "connect to the MCP servers and list them again",
                                                     MCP_RPC_FLAGS, mcp_refresh_answer};
const pic_rpc_command pic_set_mcp_server_enabled_rpc = {"set_mcp_server_enabled", "turn an MCP server on or off",
                                                        MCP_RPC_FLAGS, mcp_enable_answer};

int pic_mcp_command(int argc, char **argv, const char *workspace) {
    const char *verb = argc > 0 ? argv[0] : "list";
    static char here[PATH_MAX];
    mcp_cli_ws = workspace ? workspace : getcwd(here, sizeof here);
    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;
}