Skip to content
pi-c Artifact [d41234434c]
Login

Artifact [d41234434c]

Artifact d41234434cf5fc65c0f0c08eb1992c2a9f6639f9cc3b3a8ed834543c68071336:


/* 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. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "cred.h"
#include "image.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 *tool_exposure;  /* {"TOOL or PATTERN": exposure}, JSON; NULL: none */
    char *headers_helper; /* Claude Code's: a command printing a JSON object of headers; NULL: none */
    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;
    int bang; /* its values follow Pi's rule, a leading ! a command: pic mcp add's flags, not JSON */
} 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);
    free(s->tool_exposure);
    free(s->headers_helper);
    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"};

/* Whether X is an exposure. */
static int mcp_exposure_known(const char *x) {
    for (size_t i = 0; x && i < sizeof mcp_exposures / sizeof mcp_exposures[0]; i++) {
        if (strcmp(x, mcp_exposures[i]) == 0) {
            return 1;
        }
    }
    return 0;
}

static const char mcp_exposure_words[] = "an exposure is direct, deferred, codemode or hidden";

/* TOOL_EXPOSURE (a JSON object of tool names or patterns to exposures) checked: 0, or -1 with err. */
static int mcp_tool_exposure_check(const char *tool_exposure, char *err, size_t errcap) {
    sqlite3 *db = mcp_jdb();
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (!tool_exposure) {
        return 0;
    }
    if (!db || mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", tool_exposure, NULL, 0) != 1) {
        (void)snprintf(err, errcap, "toolExposure maps tool names to exposures");
        return -1;
    }
    if (sqlite3_prepare_v2(db, "SELECT key, CASE WHEN type = 'text' THEN value END FROM json_each(?1)", -1, &q, NULL) !=
        SQLITE_OK) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    sqlite3_bind_text(q, 1, tool_exposure, -1, SQLITE_STATIC);
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        const char *x = (const char *)sqlite3_column_text(q, 1);
        if (!mcp_exposure_known(x)) {
            (void)snprintf(err, errcap, "%.100s's exposure \"%.40s\": %s", (const char *)sqlite3_column_text(q, 0),
                           x ? x : "", mcp_exposure_words);
            rc = -1;
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* 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->argc && s->headers_helper) {
        (void)snprintf(err, errcap, "headersHelper is for an HTTP server; %s is a stdio server", s->name);
        return -1;
    }
    if (s->exposure && !mcp_exposure_known(s->exposure)) {
        (void)snprintf(err, errcap, "--exposure is direct, deferred, codemode or hidden");
        return -1;
    }
    if (mcp_tool_exposure_check(s->tool_exposure, err, errcap) != 0) {
        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);
    s->bang = 1;
    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, "--tool-exposure") == 0) { /* TOOL=EXPOSURE, a TOOL may be a pattern */
            const char *at = strrchr(v, '=');
            char tool[256], *grown;
            if (!at || at == v || (size_t)(at - v) >= sizeof tool || !mcp_exposure_known(at + 1)) {
                (void)snprintf(err, errcap, "--tool-exposure is TOOL=EXPOSURE: %s", mcp_exposure_words);
                return -1;
            }
            (void)snprintf(tool, sizeof tool, "%.*s", (int)(at - v), v);
            grown = mcp_jtext3(NULL, "SELECT json_set(coalesce(?1, '{}'), '$.\"' || replace(?2, '\"', '') || '\"', ?3)",
                               s->tool_exposure, tool, at + 1);
            if (!grown) {
                goto oom;
            }
            free(s->tool_exposure);
            s->tool_exposure = grown;
        } 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->tool_exposure = mcp_jtext("SELECT json(json_extract(?1, '$.toolExposure'))"
                                     " WHERE json_type(?1, '$.toolExposure') IS NOT NULL",
                                     entry, NULL);
        s->description = d;
        s->exposure = x;
        s->cwd = c;
        s->headers_helper = mcp_jtext("SELECT json_extract(?1, '$.headersHelper')"
                                      " WHERE json_type(?1, '$.headersHelper') = 'text' AND json_extract(?1, '$.headersHelper') <> ''",
                                      entry, NULL);
        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 ------------------------------------------------------------------------------------- */

/* Why a trusted project's files were not read, one line each ("" for none): the last merge's. */
static char mcp_file_warnings[2048];

/* Whether two server names are one: alike once '-' is '_' (their tools' names are). */
static int mcp_same_name(const char *a, const char *b) {
    for (; *a && *b; a++, b++) {
        if (*a != *b && !((*a == '-' || *a == '_') && (*b == '-' || *b == '_'))) {
            return 0;
        }
    }
    return *a == *b;
}

/* What in a project override ENTRY of the file PATH is no exposure (malloc'd), or NULL. */
static char *mcp_layer_warning(const char *path, const char *entry) {
    char *bad = mcp_jtext("SELECT group_concat(w, '; ') FROM ("
                          " SELECT 'exposure ' || json_quote(json_extract(?1, '$.exposure')) ||"
                          "  ' is not an exposure, so the server' || char(39) || 's tools are left out' w"
                          "  WHERE json_type(?1, '$.exposure') NOT IN ('null')"
                          "  AND (json_type(?1, '$.exposure') <> 'text' OR json_extract(?1, '$.exposure') NOT IN"
                          "  ('direct', 'deferred', 'codemode', 'codemode-deferred', 'hidden'))"
                          " UNION ALL SELECT key || char(39) || 's toolExposure ' ||"
                          "  CASE WHEN type = 'text' THEN json_quote(value) ELSE coalesce(json(atom), json(value)) END ||"
                          "  ' is not an exposure, so the tool is left out'"
                          "  FROM json_each(?1, '$.toolExposure') WHERE json_type(?1, '$.toolExposure') = 'object'"
                          "  AND type <> 'null' AND (type <> 'text' OR value NOT IN"
                          "  ('direct', 'deferred', 'codemode', 'codemode-deferred', 'hidden'))"
                          " UNION ALL SELECT 'toolExposure is not an object, so the server' || char(39) ||"
                          "  's tools are left out' WHERE json_type(?1, '$.toolExposure') NOT IN ('object', 'null'))",
                          entry, NULL),
         *out = NULL;
    if (bad && *bad) {
        size_t n = strlen(path) + strlen(bad) + 3;
        if ((out = malloc(n))) {
            (void)snprintf(out, n, "%s: %s", path, bad);
        }
    }
    free(bad);
    return out;
}

#define MCP_LAYERS 2 /* the project files: .mcp.json and .pic/mcp.json */

typedef struct {
    char *name, *transport, *url, *command, *cwd, *header_names, *env_names, *description, *exposure, *era, *tools,
        *error, *tool_exposure, *instructions, *headers_helper, *prompts;
    /* A trusted project's overrides of this server, one layer a project file (exposure and
     * toolExposure above stay the server's own): each may only narrow (mcp_exposure_of). A layer's
     * exposure is text ("?" when it is no exposure, or its toolExposure no object), its
     * toolExposure as written, and its file; warning: what in the files pic did not take. */
    char *layer_exposure[MCP_LAYERS], *layer_tool_exposure[MCP_LAYERS], *layer_file[MCP_LAYERS], *warning;
    int nlayers;
    unsigned char *sealed;
    int sealed_n, timeout, enabled, resources;
    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. A
     * --mcp-config server (config) has them too, its workspace the key its tool list is kept under. */
    char *source, *entry, *workspace;
    int config;
} mcp_row;

/* Adds NOTE (malloc'd, taken; NULL: nothing) to R's warning. */
static void mcp_row_warn(mcp_row *r, char *note) {
    if (!note) {
        return;
    }
    if (r->warning) {
        size_t n = strlen(r->warning) + strlen(note) + 3;
        char *both = malloc(n);
        if (both) {
            (void)snprintf(both, n, "%s; %s", r->warning, note);
            free(r->warning);
            r->warning = both;
        }
        free(note);
    } else {
        r->warning = note;
    }
}

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->tool_exposure);
    free(r->instructions);
    free(r->headers_helper);
    free(r->prompts);
    for (int i = 0; i < r->nlayers; i++) {
        free(r->layer_exposure[i]);
        free(r->layer_tool_exposure[i]);
        free(r->layer_file[i]);
    }
    free(r->warning);
    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);
static int mcp_config_merge(const char *only, mcp_row **rows, size_t *n);

/* --mcp-config's servers, as JSON objects of mcpServers, and --strict-mcp-config. */
static char **mcp_cfg_texts;
static size_t mcp_cfg_n;
static int mcp_cfg_strict;
#define MCP_CONFIG_KEY "--mcp-config" /* their rows' workspace */

/* What a --mcp-config server listed, kept in this process only: its entry may hold secrets, so
 * nothing of it is written to the database. */
typedef struct {
    char *name, *entry, *era, *tools, *error, *instructions, *prompts;
    long long listed_ms;
    int resources;
} mcp_cfg_listing;
static mcp_cfg_listing *mcp_cfg_listings;
static size_t mcp_cfg_nlistings;

static mcp_cfg_listing *mcp_cfg_listing_of(const char *name) {
    for (size_t i = 0; i < mcp_cfg_nlistings; i++) {
        if (strcmp(mcp_cfg_listings[i].name, name) == 0) {
            return &mcp_cfg_listings[i];
        }
    }
    return NULL;
}

static char *mcp_dup_or_null(const char *s) { return s ? strdup(s) : NULL; }

/* 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),"
                                  " resources, tool_exposure, instructions, headers_helper, prompts FROM picu_mcp_server"
                                  " WHERE (?1 IS NULL OR name = ?1) AND NOT ?2 ORDER BY name",
                                  -1, &q, NULL) != SQLITE_OK) {
        sqlite3_finalize(q);
        return -1;
    }
    sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 2, mcp_cfg_strict);
    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);
        r->resources = sqlite3_column_int(q, 17);
        r->tool_exposure = mcp_col_dup(q, 18);
        r->instructions = mcp_col_dup(q, 19);
        r->headers_helper = mcp_col_dup(q, 20);
        r->prompts = mcp_col_dup(q, 21);
        (*n)++;
    }
    sqlite3_finalize(q);
    *out = rows;
    if (!mcp_cfg_strict && mcp_project_merge(workspace, name, out, n) != 0) {
        return -1;
    }
    return mcp_config_merge(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 (SELECT json_group_array(v) FROM (SELECT 0 k, json_extract(?1, '$.command') v"
                           " 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->tool_exposure = mcp_jtext("SELECT json(json_extract(?1, '$.toolExposure')) WHERE json_type(?1, '$.toolExposure') = 'object'",
                                 entry, NULL);
    r->headers_helper = mcp_jtext("SELECT json_extract(?1, '$.headersHelper') WHERE json_type(?1, '$.headersHelper') = 'text'"
                                  " AND json_extract(?1, '$.headersHelper') <> ''",
                                  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 (strcmp(path, MCP_CONFIG_KEY) == 0) { /* --mcp-config's: what this process listed */
        const mcp_cfg_listing *c = mcp_cfg_listing_of(name);
        if (c && c->entry && strcmp(c->entry, entry) == 0) {
            r->era = mcp_dup_or_null(c->era);
            r->tools = mcp_dup_or_null(c->tools);
            r->listed_ms = c->listed_ms;
            if (!r->error) {
                r->error = mcp_dup_or_null(c->error);
            }
            r->resources = c->resources;
            r->instructions = mcp_dup_or_null(c->instructions);
            r->prompts = mcp_dup_or_null(c->prompts);
        }
        db = NULL;
    }
    if (db && sqlite3_prepare_v2(db,
                                 "SELECT era, tools, coalesce(listed_ms, 0), error, resources, instructions, prompts 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);
            }
            r->resources = sqlite3_column_int(q, 4);
            r->instructions = mcp_col_dup(q, 5);
            r->prompts = mcp_col_dup(q, 6);
        }
    }
    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 and toolExposure, 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();
    mcp_file_warnings[0] = '\0';
    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 (mcp_jint("SELECT json_valid(?1) AND coalesce(json_type(?1, '$.mcpServers'), 'object') = 'object'", text, NULL,
                     0) != 1) {
            size_t len = strlen(mcp_file_warnings);
            (void)snprintf(mcp_file_warnings + len, sizeof mcp_file_warnings - len, "%s%s %s; its servers are ignored",
                           len ? "\n" : "", path,
                           mcp_jint("SELECT json_valid(?1)", text, NULL, 0) ? "has an mcpServers that is not an object"
                                                                           : "is not valid JSON");
        }
        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 && !mcp_same_name(name, only)) {
                continue;
            }
            for (size_t i = 0; i < *n; i++) {
                at = mcp_same_name((*rows)[i].name, name) ? 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 && !only) { /* narrows nothing: no server of the name */
                    size_t len = strlen(mcp_file_warnings);
                    (void)snprintf(mcp_file_warnings + len, sizeof mcp_file_warnings - len,
                                   "%s%s names %s, which is none of your servers nor one defined above it: the entry changes nothing", len ? "\n" : "",
                                   path, name);
                } else if (at < *n && (*rows)[at].nlayers == MCP_LAYERS) {
                    char note[PATH_MAX + MCP_NAME_CAP + 120];
                    (void)snprintf(note, sizeof note, "%s: the entry %s was dropped, as %s has %d entries narrowing it already",
                                   path, name, (*rows)[at].name, MCP_LAYERS);
                    mcp_row_warn(&(*rows)[at], strdup(note));
                }
                if (at < *n && (*rows)[at].nlayers < MCP_LAYERS) { /* a layer that may only narrow */
                    mcp_row *u = &(*rows)[at];
                    int k = u->nlayers++;
                    u->enabled = u->enabled && mcp_jint("SELECT json_type(?1, '$.enabled') <> 'false'", entry, NULL, 1) != 0;
                    u->layer_file[k] = strdup(path);
                    u->layer_exposure[k] = mcp_jtext(
                        "SELECT CASE WHEN json_type(?1, '$.toolExposure') NOT IN ('object', 'null') THEN '?'"
                        " WHEN coalesce(json_type(?1, '$.exposure'), 'null') = 'null' THEN NULL"
                        " WHEN json_type(?1, '$.exposure') = 'text' THEN json_extract(?1, '$.exposure') ELSE '?' END"
                        " WHERE json_type(?1, '$.exposure') IS NOT NULL OR json_type(?1, '$.toolExposure') IS NOT NULL",
                        entry, NULL);
                    u->layer_tool_exposure[k] = mcp_jtext("SELECT json(json_extract(?1, '$.toolExposure'))"
                                                          " WHERE json_type(?1, '$.toolExposure') = 'object'",
                                                          entry, NULL);
                    mcp_row_warn(u, mcp_layer_warning(path, entry));
                }
                continue;
            }
            if (at < *n && !(*rows)[at].source) { /* the user's server's name: a project may only narrow it */
                char note[PATH_MAX + 2 * MCP_NAME_CAP + 160];
                (void)snprintf(note, sizeof note,
                               "%s defines %s, which is one of your servers: pic ignores it (an entry there without"
                               " command, url or type can still narrow yours)",
                               path, name);
                mcp_row_warn(&(*rows)[at], strdup(note));
                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;
}

/* --mcp-config's servers (or ONLY's) merged into ROWS, each replacing a server of its name. */
static int mcp_config_merge(const char *only, mcp_row **rows, size_t *n) {
    sqlite3 *db = mcp_jdb();
    for (size_t f = 0; db && f < mcp_cfg_n; f++) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(db,
                               "SELECT key, json(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, mcp_cfg_texts[f], -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 && !mcp_same_name(name, only)) {
                continue;
            }
            for (size_t i = 0; i < *n; i++) {
                at = mcp_same_name((*rows)[i].name, name) ? i : at;
            }
            if (mcp_project_row(MCP_CONFIG_KEY, MCP_CONFIG_KEY, name, entry, &r) != 0) {
                mcp_row_free(&r);
                continue;
            }
            r.config = 1;
            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);
                    sqlite3_finalize(q);
                    return -1;
                }
                *rows = grown;
                (*rows)[(*n)++] = r;
            }
        }
        sqlite3_finalize(q);
    }
    return 0;
}

static void mcp_close_devfd(const char *v) {
    char *end = NULL;
    long fd = strncmp(v, "/dev/fd/", 8) == 0 && v[8] ? strtol(v + 8, &end, 10) : -1;
    if (fd > 2 && end && !*end) { /* the interface's handoff (tui/app.c): read once, then nothing else may */
        (void)close((int)fd);
    }
}

int pic_mcp_configs(const char *const *values, size_t n, int strict, char *err, size_t errcap) {
    int rc = 0;
    mcp_cfg_strict = strict;
    for (size_t i = 0; i < n; i++) {
        const char *v = values[i];
        char *text, **grown;
        if (rc != 0) {
            mcp_close_devfd(v);
            continue;
        }
        text = v[0] == '{' ? strdup(v) : mcp_slurp(v);
        mcp_close_devfd(v);
        if (!text) {
            (void)snprintf(err, errcap, "--mcp-config %.200s: %s", v, v[0] == '{' ? "out of memory" : "cannot read the file");
            rc = -1;
            continue;
        }
        if (mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object' AND"
                     " coalesce(json_type(?1, '$.mcpServers'), 'object') = 'object'",
                     text, NULL, 0) != 1) {
            (void)snprintf(err, errcap, "--mcp-config %.200s: not a JSON object of mcpServers", v[0] == '{' ? "(JSON)" : v);
            free(text);
            rc = -1;
            continue;
        }
        if (!(grown = realloc(mcp_cfg_texts, (mcp_cfg_n + 1) * sizeof *grown))) {
            free(text);
            (void)snprintf(err, errcap, "out of memory");
            rc = -1;
            continue;
        }
        mcp_cfg_texts = grown;
        mcp_cfg_texts[mcp_cfg_n++] = text;
    }
    return rc;
}

const char *const *pic_mcp_config_texts(size_t *n) {
    *n = mcp_cfg_n;
    return (const char *const *)mcp_cfg_texts;
}

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_appendf(t, "]%s}", s->bang ? ",\"bang\":true" : "");
    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, tool_exposure,"
                           " headers_helper) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 1, ?12, json(?13), ?14)",
                           -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());
        sqlite3_bind_text(q, 13, s->tool_exposure, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 14, s->headers_helper, -1, SQLITE_STATIC);
        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, TOOLS, whether it has RESOURCES, its INSTRUCTIONS and PROMPTS 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, int resources, const char *instructions,
                         const char *prompts, const char *error) {
    sqlite3 *db;
    sqlite3_stmt *q = NULL;
    const char *name = r->name;
    if (r->config) { /* in memory only: never written */
        mcp_cfg_listing *c = mcp_cfg_listing_of(name), *grown;
        if (c && tools) {
            free(c->era);
            free(c->tools);
            free(c->instructions);
            free(c->prompts);
            c->era = c->tools = c->instructions = c->prompts = NULL;
        } else if (c && (!c->entry || strcmp(c->entry, r->entry) != 0)) { /* another entry's listing is not this one's */
            free(c->era);
            free(c->tools);
            free(c->instructions);
            free(c->prompts);
            c->era = c->tools = c->instructions = c->prompts = NULL;
            c->listed_ms = 0;
            c->resources = 0;
        }
        if (!c) {
            if (!(grown = realloc(mcp_cfg_listings, (mcp_cfg_nlistings + 1) * sizeof *grown))) {
                return;
            }
            mcp_cfg_listings = grown;
            c = &mcp_cfg_listings[mcp_cfg_nlistings];
            memset(c, 0, sizeof *c);
            if (!(c->name = strdup(name))) {
                return;
            }
            mcp_cfg_nlistings++;
        }
        free(c->entry);
        c->entry = strdup(r->entry);
        free(c->error);
        c->error = tools ? NULL : mcp_dup_or_null(error);
        if (tools) {
            c->era = mcp_dup_or_null(era);
            c->tools = strdup(tools);
            c->listed_ms = mcp_now_ms();
            c->resources = resources != 0;
            c->instructions = mcp_dup_or_null(instructions);
            c->prompts = mcp_dup_or_null(prompts);
        }
        return;
    }
    db = pic_userdb(NULL, 0);
    if (db && r->source) {
        if (sqlite3_prepare_v2(db,
                               "INSERT INTO picu_mcp_project(workspace, name, entry, era, tools, listed_ms, error, resources,"
                               " instructions, prompts) VALUES(?1, ?2, json(?3), ?4, coalesce(json(?5), '[]'), ?6, ?7, ?8,"
                               " ?9, json(?10))"
                               " 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),"
                               " resources = iif(?5 IS NULL AND entry = excluded.entry, resources, excluded.resources),"
                               " instructions = iif(?5 IS NULL AND entry = excluded.entry, instructions,"
                               " excluded.instructions),"
                               " prompts = iif(?5 IS NULL AND entry = excluded.entry, prompts, excluded.prompts),"
                               " 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);
            sqlite3_bind_int(q, 8, tools && resources);
            sqlite3_bind_text(q, 9, tools ? instructions : NULL, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 10, tools ? prompts : NULL, -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,"
                                         " resources = ?6, instructions = ?7, prompts = json(?8) 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());
            sqlite3_bind_int(q, 6, resources != 0);
            sqlite3_bind_text(q, 7, instructions, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 8, prompts, -1, SQLITE_STATIC);
        } 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;
}

#define MCP_COMMAND_SECONDS 10 /* Pi's and Claude Code's limit on a value's or a helper's command */

/* Pi's !command value: what COMMAND printed, trimmed (malloc'd), or NULL with err. */
static char *mcp_command_value(const char *server, const char *what, const char *command, char *err, size_t errcap) {
    char why[256] = "", *out = pic_mcp_run(command, NULL, MCP_COMMAND_SECONDS, why, sizeof why);
    size_t n;
    if (!out) {
        (void)snprintf(err, errcap, "%s's %s: %s", server, what, why);
        return NULL;
    }
    for (n = strlen(out); n > 0 && strchr(" \t\r\n", out[n - 1]); n--) {
    }
    out[n] = '\0';
    if (n == 0) {
        (void)snprintf(err, errcap, "%s's %s: the command printed nothing", server, what);
        free(out);
        return NULL;
    }
    return out;
}

/* Claude Code's headersHelper: R's command, run with CLAUDE_CODE_MCP_SERVER_NAME and _URL set,
 * prints a JSON object of headers; each is added to L's, replacing one of the same name. 0, or
 * -1 with err. */
static int mcp_helper_headers(const mcp_row *r, mcp_live *l, char *err, size_t errcap) {
    char why[256] = "", *name_env, *url_env, *out;
    const char *env[3];
    sqlite3 *db = mcp_jdb();
    sqlite3_stmt *q = NULL;
    int rc = -1;
    name_env = malloc(strlen(r->name) + 32);
    url_env = malloc(strlen(r->url) + 32);
    if (!name_env || !url_env || !db) {
        free(name_env);
        free(url_env);
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    (void)snprintf(name_env, strlen(r->name) + 32, "CLAUDE_CODE_MCP_SERVER_NAME=%s", r->name);
    (void)snprintf(url_env, strlen(r->url) + 32, "CLAUDE_CODE_MCP_SERVER_URL=%s", r->url);
    env[0] = name_env;
    env[1] = url_env;
    env[2] = NULL;
    out = pic_mcp_run(r->headers_helper, env, MCP_COMMAND_SECONDS, why, sizeof why);
    free(name_env);
    free(url_env);
    if (!out) {
        (void)snprintf(err, errcap, "%s's headersHelper: %s", r->name, why);
        return -1;
    }
    if (mcp_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", out, NULL, 0) != 1 ||
        mcp_jint("SELECT count(*) FROM json_each(?1) WHERE type <> 'text'", out, NULL, 1) != 0) {
        (void)snprintf(err, errcap, "%s's headersHelper did not print a JSON object of header names to text values", r->name);
        goto done;
    }
    if (sqlite3_prepare_v2(db, "SELECT key, value FROM json_each(?1)", -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "out of memory");
        goto done;
    }
    sqlite3_bind_text(q, 1, out, -1, SQLITE_STATIC);
    rc = 0;
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        const char *k = (const char *)sqlite3_column_text(q, 0), *v = (const char *)sqlite3_column_text(q, 1), *value;
        char name[128], *line;
        size_t kn = strlen(k), len = kn + strlen(v) + 3;
        if (!(line = malloc(len))) {
            rc = -1;
            break;
        }
        (void)snprintf(line, len, "%s: %s", k, v);
        if (mcp_header_split(line, name, sizeof name, &value, err, errcap) != 0) {
            rc = -1;
        }
        for (size_t i = 0; rc == 0 && i < l->nheaders; i++) { /* the helper's wins over one of its name */
            if (strncasecmp(l->headers[i], k, kn) == 0 && l->headers[i][kn] == ':') {
                pic_cred_wipe(l->headers[i], strlen(l->headers[i]));
                free(l->headers[i]);
                memmove(&l->headers[i], &l->headers[i + 1], (l->nheaders - i - 1) * sizeof *l->headers);
                l->nheaders--;
                i--;
            }
        }
        if (rc == 0 && mcp_push(&l->headers, &l->nheaders, line) != 0) {
            rc = -1;
        }
        pic_cred_wipe(line, strlen(line));
        free(line);
    }
    if (rc != 0 && !err[0]) {
        (void)snprintf(err, errcap, "out of memory");
    }
done:
    sqlite3_finalize(q);
    pic_cred_wipe(out, strlen(out));
    free(out);
    return rc;
}

/* Whether R comes from pic's own project file (.pic/mcp.json, in Pi's format, where a leading !
 * is a command), not Claude Code's .mcp.json or --mcp-config (where it is literal). */
static int mcp_pi_file(const mcp_row *r) {
    size_t n = r->source ? strlen(r->source) : 0, m = strlen("/.pic/mcp.json");
    return !r->config && n > m && strcmp(r->source + n - m, "/.pic/mcp.json") == 0;
}

/* 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, bang = 0;
    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->config ? 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;
        bang = mcp_pi_file(r);
        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;
        }
        goto helper; /* nothing sealed, but a headersHelper may still give headers */
    }
    {
        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;
    bang = mcp_jint("SELECT json_extract(?1, '$.bang') IS 1", plain, NULL, 0) == 1;
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);
        /* Pi's rule, only where Pi's format wrote it: a leading ! is a command, $! a literal ! */
        if (!(value = bang && v[0] == '!' ? mcp_command_value(r->name, what, v + 1, err, errcap)
                                          : mcp_expand(r->name, what, bang && strncmp(v, "$!", 2) == 0 ? v + 1 : 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;
helper:
    if (r->headers_helper && r->url && mcp_helper_headers(r, l, err, errcap) != 0) {
        goto fail;
    }
    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 (and its prompts, when it has them), and asks whether it has
 * resources (*RESOURCES, may be NULL), recording them (or why not) in its row. The number of
 * tools, or -1 with err; *NPROMPTS (may be NULL) the number of prompts. */
static int mcp_row_refresh(const mcp_row *r, char *era, size_t eracap, int *resources, int *nprompts, char *err,
                           size_t errcap) {
    mcp_live l;
    pic_mcp_conn *c;
    char *tools;
    int n = -1, has = 0, np = 0;
    era[0] = '\0';
    if (nprompts) {
        *nprompts = 0;
    }
    if (mcp_live_open(r, NULL, 0, &l, err, errcap) != 0) {
        mcp_row_note(r, NULL, NULL, 0, NULL, NULL, err);
        return -1;
    }
    l.t.era = NULL; /* asked again, with the server's capabilities */
    if ((c = pic_mcp_open(&l.t, err, errcap)) && (tools = pic_mcp_list_tools(c, err, errcap))) {
        const char *caps = pic_mcp_capabilities(c);
        char perr[PIC_ERR_CAP], *prompts = NULL;
        has = caps && mcp_jint("SELECT json_type(?1, '$.resources') = 'object'", caps, NULL, 0) == 1;
        if (caps && mcp_jint("SELECT json_type(?1, '$.prompts') = 'object'", caps, NULL, 0) == 1) {
            prompts = pic_mcp_list_prompts(c, perr, sizeof perr); /* none, when it cannot list them */
            np = prompts ? (int)mcp_jint("SELECT json_array_length(?1)", prompts, NULL, 0) : 0;
        }
        (void)snprintf(era, eracap, "%s", pic_mcp_era(c));
        mcp_row_note(r, era, tools, has, pic_mcp_instructions(c), prompts, NULL);
        n = (int)mcp_jint("SELECT json_array_length(?1)", tools, NULL, 0);
        free(tools);
        free(prompts);
    }
    pic_mcp_close(c);
    if (n < 0) {
        mcp_live_scrub(&l, err);
        mcp_row_note(r, NULL, NULL, 0, NULL, NULL, err);
    }
    mcp_live_free(&l);
    if (resources) {
        *resources = has;
    }
    if (nprompts) {
        *nprompts = np;
    }
    return n;
}

/* ---- a call --------------------------------------------------------------------------------- */

/* A variable's value V as a positive whole number, or 0 when it is unset or not one. */
static long mcp_env_count(const char *v) {
    char *end;
    long n = v && *v ? strtol(v, &end, 10) : 0;
    return v && *v && !*end && n > 0 && n < 100000000 ? n : 0;
}

/* The bytes of a result the model gets: Claude Code's MAX_MCP_OUTPUT_TOKENS (four bytes a token)
 * when it is set, else Pi's MCP_OUTPUT_MAX. */
static size_t mcp_output_max(void) {
    long tokens = mcp_env_count(getenv("MAX_MCP_OUTPUT_TOKENS"));
    return tokens ? (size_t)tokens * 4 : MCP_OUTPUT_MAX;
}

/* 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 max = mcp_output_max(), len = strlen(text), head = max / 2, tail, lines = 0, removed = 0;
    sqlite3_str *t;
    char *res, *out;
    if (len <= max) {
        return NULL;
    }
    while (head > 0 && ((unsigned char)text[head] & 0xc0) == 0x80) {
        head--;
    }
    tail = len - (max - 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;
}

/* The servers listed again in this request: one relist each, however often they say their lists
 * changed. Cleared at the start of each request (pic_tool_on_request). */
static char **mcp_relisted;
static size_t mcp_nrelisted;

static void mcp_relist_reset(void) {
    for (size_t i = 0; i < mcp_nrelisted; i++) {
        free(mcp_relisted[i]);
    }
    free(mcp_relisted);
    mcp_relisted = NULL;
    mcp_nrelisted = 0;
}

static void mcp_kept_stop(void) {
    for (size_t i = 0; i < mcp_nkept; i++) {
        mcp_kept_drop(&mcp_kept_conns[i]);
    }
    mcp_relist_reset();
}

/* What the list_changed notifications C brought (CHANGED, PIC_MCP_*_CHANGED) say of R, listed
 * again on C and recorded in its row: the tools and the prompts, and resources when the server
 * now lists some (a notification alone does not make it a server with resources). The registry
 * keeps what it has; the next request takes the new lists. At most once per server in a request. */
static void mcp_row_relist(const mcp_row *r, pic_mcp_conn *c, int changed) {
    char err[PIC_ERR_CAP], *tools = NULL, *prompts = NULL;
    int resources = r->resources;
    for (size_t i = 0; i < mcp_nrelisted; i++) {
        if (strcmp(mcp_relisted[i], r->name) == 0) {
            return;
        }
    }
    {
        char *copy = strdup(r->name), **grown = copy ? realloc(mcp_relisted, (mcp_nrelisted + 1) * sizeof *grown) : NULL;
        if (!grown) {
            free(copy);
            return;
        }
        mcp_relisted = grown;
        mcp_relisted[mcp_nrelisted++] = copy;
    }
    if (changed & PIC_MCP_TOOLS_CHANGED) {
        tools = pic_mcp_list_tools(c, err, sizeof err);
    }
    if (changed & PIC_MCP_PROMPTS_CHANGED) {
        prompts = pic_mcp_list_prompts(c, err, sizeof err);
    }
    if ((changed & PIC_MCP_RESOURCES_CHANGED) && !resources) {
        int answered = 0;
        char *page = pic_mcp_ask(c, "resources/list", "{}", NULL, &answered, err, sizeof err);
        resources = page && mcp_jint("SELECT json_type(?1, '$.resources') = 'array'", page, NULL, 0) == 1;
        free(page);
    }
    mcp_row_note(r, pic_mcp_era(c), tools ? tools : r->tools ? r->tools : "[]", resources, r->instructions,
                 prompts ? prompts : r->prompts, NULL);
    free(tools);
    free(prompts);
}

/* Asks R METHOD with PARAMS (NAME: what it is about, for Mcp-Name): the result (malloc'd), or
 * NULL with err (secrets scrubbed) and *WHY: -1 its target could not be made (nothing was sent),
 * 0 R could not be reached (nothing ran there), 1 it answered with an error, 2 it did not answer
 * (whether it acted is not known). KEEP: a stdio
 * server stays running for the next request in this process. */
static char *mcp_row_ask(const mcp_row *r, const char *workspace, const char *method, const char *params,
                         const char *name, int quiet, int keep, int *why, char *err, size_t errcap) {
    pic_mcp_conn *c = NULL;
    mcp_kept *k = NULL;
    mcp_live own, *l = &own;
    char *result;
    int answered = 0;
    err[0] = '\0';
    *why = 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];
        }
    }
    if (k) {
        l = &k->l;
        c = k->c;
    } else {
        if (mcp_live_open(r, workspace, quiet, &own, err, errcap) != 0) {
            *why = -1;
            return NULL;
        }
        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, errcap);
        if (k) {
            k->c = c;
        }
    }
    { /* Claude Code's MCP_TOOL_TIMEOUT (milliseconds) for a tool's call, else the server's */
        long ms = strcmp(method, "tools/call") == 0 ? mcp_env_count(getenv("MCP_TOOL_TIMEOUT")) : 0;
        l->t.timeout = ms ? (int)((ms + 999) / 1000 < 86400 ? (ms + 999) / 1000 : 86400)
                          : r->timeout > 0 ? r->timeout : MCP_TIMEOUT;
    }
    result = c ? pic_mcp_ask(c, method, params, name, &answered, err, errcap) : NULL;
    if (!result) {
        *why = c != NULL && strncmp(err, "cannot connect", 14) != 0 ? (answered ? 1 : 2) : 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);
        }
        return NULL;
    }
    {
        int changed = pic_mcp_changed(c);
        if (changed) {
            mcp_row_relist(r, c, changed);
        }
    }
    if (!k) {
        pic_mcp_close(c);
        mcp_live_free(l);
    }
    return result;
}

/* 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;
    int why;
    *full = NULL;
    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");
    }
    result = mcp_row_ask(r, workspace, "tools/call", params, tool, quiet, keep, &why, err, sizeof err);
    free(params);
    if (!result) {
        if (why <= 0) {
            return mcp_fmt(is_error, 1, why ? "MCP server %s: %s; the tool did not run"
                                            : "MCP server %s could not be reached: %s; the tool did not run",
                           r->name, err);
        }
        return mcp_fmt(is_error, 1,
                       why == 1 ? "MCP server %s: %s" : "MCP server %s did not answer: %s. Whether the call ran there is not known",
                       r->name, err);
    }
    text = mcp_result_text(result, is_error);
    free(result);
    if (text && (cut = mcp_cut_middle(text, where))) {
        *full = text;
        return cut;
    }
    return text;
}

/* ---- exposure ------------------------------------------------------------------------------ */

/* "mcp__SERVER__" as SERVER's tool names start (every character but letters, digits and '_' as
 * '_'), into OUT. */
static void mcp_server_prefix(const char *server, char *out, size_t cap) {
    (void)snprintf(out, cap, "mcp__%s__", server);
    for (char *p = out; *p; p++) {
        if (!isalnum((unsigned char)*p) && *p != '_') {
            *p = '_';
        }
    }
}

/* Whether PATTERN ('*' any run of characters) matches all of S. */
static int mcp_star(const char *p, const char *s) {
    if (!*p) {
        return !*s;
    }
    if (*p == '*') {
        for (;; s++) {
            if (mcp_star(p + 1, s)) {
                return 1;
            }
            if (!*s) {
                return 0;
            }
        }
    }
    return *s == *p && mcp_star(p + 1, s + 1);
}

/* X with its alias resolved: "direct" when X is not set, "hidden" when it is not an exposure (a
 * project's file is not checked when it is written). */
static const char *mcp_exposure_name(const char *x) {
    if (!x || strcmp(x, "direct") == 0) {
        return "direct";
    }
    if (!mcp_exposure_known(x)) {
        return "hidden";
    }
    return strcmp(x, "deferred") == 0 ? "deferred" : strcmp(x, "hidden") == 0 ? "hidden" : "codemode";
}

/* TOOL's exposure in one layer, EXPOSURE and TOOL_EXPOSURE, as Pi's toolExposure decides it: its
 * exact name, else the first pattern that matches, else the layer's EXPOSURE, else DFLT (TOOL
 * NULL: the server's). A null entry is no opinion; any other value that is no exposure, a number
 * or an unknown word, is hidden. */
static const char *mcp_exposure_in(const char *exposure, const char *tool_exposure, const char *tool, const char *dflt) {
    sqlite3 *db = mcp_jdb();
    sqlite3_stmt *q = NULL;
    const char *x = NULL;
    if (tool && tool_exposure && db &&
        sqlite3_prepare_v2(db,
                           "SELECT key, CASE WHEN type = 'text' THEN value END FROM json_each(?1)"
                           " WHERE type <> 'null' AND (key = ?2 OR instr(key, '*')) ORDER BY key <> ?2, id",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, tool_exposure, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, tool, -1, SQLITE_STATIC);
        while (!x && sqlite3_step(q) == SQLITE_ROW) {
            if (mcp_star((const char *)sqlite3_column_text(q, 0), tool)) {
                const char *v = (const char *)sqlite3_column_text(q, 1);
                x = v ? mcp_exposure_name(v) : "hidden";
            }
        }
    }
    sqlite3_finalize(q);
    return x ? x : exposure ? mcp_exposure_name(exposure) : dflt;
}

/* How widely X reaches the model: direct 3, deferred 2, codemode 1, hidden 0. */
static int mcp_exposure_rank(const char *x) {
    return strcmp(x, "direct") == 0 ? 3 : strcmp(x, "deferred") == 0 ? 2 : strcmp(x, "codemode") == 0 ? 1 : 0;
}

/* TOOL's exposure on R (TOOL NULL: the server's): its own, narrowed by each project layer that
 * has an opinion, so a project may only narrow; *BY (may be NULL) the file of the layer that
 * narrowed it, NULL when none did. */
static const char *mcp_exposure_by(const mcp_row *r, const char *tool, const char **by) {
    const char *x = mcp_exposure_in(r->exposure, r->tool_exposure, tool, "direct");
    if (by) {
        *by = NULL;
    }
    for (int i = 0; i < r->nlayers; i++) {
        const char *theirs = mcp_exposure_in(r->layer_exposure[i], r->layer_tool_exposure[i], tool, NULL);
        if (theirs && mcp_exposure_rank(theirs) < mcp_exposure_rank(x)) {
            x = theirs;
            if (by) {
                *by = r->layer_file[i];
            }
        }
    }
    return x;
}

static const char *mcp_exposure_of(const mcp_row *r, const char *tool) { return mcp_exposure_by(r, tool, NULL); }

/* ---- the registry ---------------------------------------------------------------------------- */

typedef struct {
    pic_tool_def def;
    char *name, *schema, *tool;
    size_t server;
} mcp_tool;

static const char *mcp_user_tool_server(const mcp_row *rows, size_t n, const char *name);
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;
}

/* ---- resources: Pi's (and Codex's) three tools over every server that has them ------------- */

#define MCP_RES_PAGES 100        /* pages of one server a listing of every server follows */
#define MCP_RES_MAX (1 << 20)     /* bytes of items a listing of every server gathers */

static const char mcp_res_list_params[] =
    "\"input_schema\":{\"type\":\"object\",\"properties\":{\"server\":{\"type\":\"string\",\"description\":\"MCP server "
    "name. Omit to list every server with resources.\"},\"cursor\":{\"type\":\"string\",\"description\":\"Opaque cursor "
    "from a previous call with the same server; omit for the first page.\"}},\"additionalProperties\":false}}";
static char mcp_res_list_schema[1024], mcp_res_templates_schema[1024];
static const char mcp_res_read_schema[] =
    "{\"name\":\"read_mcp_resource\",\"description\":\"Read a specific resource from an MCP server given the server "
    "name and resource URI.\",\"input_schema\":{\"type\":\"object\",\"properties\":{\"server\":{\"type\":\"string\","
    "\"description\":\"MCP server name exactly as configured. Must match the 'server' field returned by "
    "list_mcp_resources.\"},\"uri\":{\"type\":\"string\",\"description\":\"Resource URI to read. Must be one of the URIs "
    "returned by list_mcp_resources.\"}},\"required\":[\"server\",\"uri\"],\"additionalProperties\":false}}";

static char *mcp_res_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
                         const pic_tool_hooks *h, int *is_error);
static pic_tool_def mcp_res_defs[3] = {
    {"list_mcp_resources", mcp_res_list_schema, 1, 0, PIC_TIER_BUNDLED, 0, mcp_on, mcp_res_run, NULL, 0},
    {"list_mcp_resource_templates", mcp_res_templates_schema, 1, 0, PIC_TIER_BUNDLED, 0, mcp_on, mcp_res_run, NULL, 0},
    {"read_mcp_resource", mcp_res_read_schema, 1, 0, PIC_TIER_BUNDLED, 0, mcp_on, mcp_res_run, NULL, 0},
};

/* Whether the resource tools reach R: enabled, not hidden, and its capabilities named resources. */
static int mcp_res_reaches(const mcp_row *r) {
    return r->enabled && r->resources && strcmp(mcp_exposure_of(r, NULL), "hidden") != 0;
}

/* The names of the servers with resources, for a message (malloc'd). */
static char *mcp_res_names(void) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *res, *out;
    int any = 0;
    for (size_t i = 0; i < mcp_reg_nrows; i++) {
        if (mcp_res_reaches(&mcp_reg_rows[i])) {
            sqlite3_str_appendf(t, "%s%s", any ? ", " : "", mcp_reg_rows[i].name);
            any = 1;
        }
    }
    res = sqlite3_str_finish(t);
    out = strdup(res ? res : "");
    sqlite3_free(res);
    return out;
}

/* One page of METHOD's KEY items from R after CURSOR (NULL: the first), MCP Apps and icons left
 * out and each tagged with its server: a JSON array (malloc'd) and *NEXT (malloc'd, NULL at the
 * end), or NULL with err. */
static char *mcp_res_page(const mcp_row *r, const char *workspace, const char *method, const char *key,
                          const char *cursor, char **next, char *err, size_t errcap) {
    char *params = cursor ? mcp_jtext("SELECT json_object('cursor', ?1)", cursor, NULL) : NULL, *res, *items;
    int why;
    *next = NULL;
    res = mcp_row_ask(r, workspace, method, params, NULL, 1, 1, &why, err, errcap);
    free(params);
    if (!res) {
        return NULL;
    }
    items = mcp_jtext3(NULL,
                       "SELECT json_group_array(json(json_patch(json_object('server', ?2), json_remove(value, '$._meta',"
                       " '$.icons')))) FROM json_each(?1, '$.' || ?3) WHERE json_type(?1, '$.' || ?3) = 'array'"
                       " AND type = 'object' AND coalesce(json_extract(value, '$.uri'), json_extract(value, '$.uriTemplate'),"
                       " '') NOT LIKE 'ui://%' AND coalesce(json_extract(value, '$.mimeType'), '') NOT LIKE '%profile%mcp-app%'",
                       res, r->name, key);
    *next = mcp_jtext("SELECT json_extract(?1, '$.nextCursor') WHERE json_type(?1, '$.nextCursor') = 'text'"
                      " AND json_extract(?1, '$.nextCursor') <> ''",
                      res, NULL);
    free(res);
    if (!items) {
        free(*next);
        *next = NULL;
        (void)snprintf(err, errcap, "out of memory");
    }
    return items;
}

/* A listing as Pi gives it: {server, KEY: [...], nextCursor} for one server's page, or every page
 * of every server as {KEY: [...], errors: [{server, error}]}. */
static char *mcp_res_list(const char *workspace, const char *input, const char *method, const char *key, int *is_error) {
    char *server = mcp_jtext("SELECT trim(json_extract(?1, '$.server')) WHERE json_type(?1, '$.server') = 'text'"
                             " AND trim(json_extract(?1, '$.server')) <> ''",
                             input, NULL),
         *cursor = mcp_jtext("SELECT trim(json_extract(?1, '$.cursor')) WHERE json_type(?1, '$.cursor') = 'text'"
                             " AND trim(json_extract(?1, '$.cursor')) <> ''",
                             input, NULL),
         err[PIC_ERR_CAP], *out = NULL;
    sqlite3_str *t;
    if (server) {
        const mcp_row *r = NULL;
        char *page, *next = NULL;
        for (size_t i = 0; i < mcp_reg_nrows && !r; i++) {
            r = mcp_res_reaches(&mcp_reg_rows[i]) && strcmp(mcp_reg_rows[i].name, server) == 0 ? &mcp_reg_rows[i] : NULL;
        }
        if (!r) {
            char *names = mcp_res_names();
            out = mcp_fmt(is_error, 1, "MCP server \"%s\" has no resources%s%s", server,
                          names && *names ? ". Servers with resources: " : "", names ? names : "");
            free(names);
        } else if (!(page = mcp_res_page(r, workspace, method, key, cursor, &next, err, sizeof err))) {
            out = mcp_fmt(is_error, 1, "MCP server %s: %s", r->name, err);
        } else {
            t = sqlite3_str_new(NULL);
            sqlite3_str_appendall(t, "{\"server\":");
            pic_rpc_quote(t, r->name);
            sqlite3_str_appendf(t, ",\"%s\":%s", key, page);
            if (next) {
                sqlite3_str_appendall(t, ",\"nextCursor\":");
                pic_rpc_quote(t, next);
            }
            sqlite3_str_appendall(t, "}");
            out = sqlite3_str_finish(t);
            free(page);
            free(next);
            if (out) {
                char *own = strdup(out);
                sqlite3_free(out);
                out = own;
            }
        }
    } else if (cursor) {
        out = mcp_fmt(is_error, 1, "cursor can only be used when a server is specified");
    } else {
        sqlite3_str *errs = sqlite3_str_new(NULL);
        int first = 1, nerr = 0;
        const char *cut = NULL;
        char *res;
        t = sqlite3_str_new(NULL);
        sqlite3_str_appendf(t, "{\"%s\":[", key);
        for (size_t i = 0; i < mcp_reg_nrows && !cut; i++) {
            const mcp_row *r = &mcp_reg_rows[i];
            char *at = NULL, *page, *next = NULL;
            int pages = 0;
            if (!mcp_res_reaches(r)) {
                continue;
            }
            do {
                page = mcp_res_page(r, workspace, method, key, at, &next, err, sizeof err);
                free(at);
                at = next;
                if (!page) {
                    sqlite3_str_appendall(errs, nerr++ ? ",{\"server\":" : "{\"server\":");
                    pic_rpc_quote(errs, r->name);
                    sqlite3_str_appendall(errs, ",\"error\":");
                    pic_rpc_quote(errs, err);
                    sqlite3_str_appendall(errs, "}");
                    break;
                }
                if ((size_t)sqlite3_str_length(t) + strlen(page) > (size_t)MCP_RES_MAX) {
                    cut = "the listing stopped at 1 MB: list one server at a time, with server and cursor";
                } else if (strcmp(page, "[]") != 0) { /* the array's members, without its brackets */
                    sqlite3_str_appendf(t, "%s%.*s", first ? "" : ",", (int)strlen(page) - 2, page + 1);
                    first = 0;
                }
                free(page);
            } while (at && !cut && ++pages < MCP_RES_PAGES);
            if (at && !cut) {
                cut = "a server had more than 100 pages: list it with server and cursor";
            }
            free(at);
        }
        sqlite3_str_appendall(t, "]");
        res = sqlite3_str_finish(errs);
        if (nerr) {
            sqlite3_str_appendf(t, ",\"errors\":[%s]", res ? res : "");
        }
        if (cut) {
            sqlite3_str_appendf(t, ",\"cut\":\"%s\"", cut);
        }
        sqlite3_free(res);
        sqlite3_str_appendall(t, "}");
        res = sqlite3_str_finish(t);
        out = res ? strdup(res) : NULL;
        sqlite3_free(res);
    }
    free(server);
    free(cursor);
    return out;
}

/* read_mcp_resource: each content as text (several labelled with their URIs), an image attached
 * when H keeps one, and other binary content named, not shown. */
static char *mcp_res_read(const char *workspace, const char *input, const pic_tool_hooks *h, int *is_error) {
    char *server = mcp_jtext("SELECT trim(json_extract(?1, '$.server')) WHERE json_type(?1, '$.server') = 'text'"
                             " AND trim(json_extract(?1, '$.server')) <> ''",
                             input, NULL),
         *uri = mcp_jtext("SELECT trim(json_extract(?1, '$.uri')) WHERE json_type(?1, '$.uri') = 'text'"
                          " AND trim(json_extract(?1, '$.uri')) <> ''",
                          input, NULL),
         err[PIC_ERR_CAP], *params = NULL, *res = NULL, *out = NULL;
    const mcp_row *r = NULL;
    sqlite3 *db = mcp_jdb();
    sqlite3_stmt *q = NULL;
    sqlite3_str *t;
    int why, n = 0, attached = 0;
    for (size_t i = 0; server && i < mcp_reg_nrows && !r; i++) {
        r = mcp_res_reaches(&mcp_reg_rows[i]) && strcmp(mcp_reg_rows[i].name, server) == 0 ? &mcp_reg_rows[i] : NULL;
    }
    if (!server || !uri) {
        out = mcp_fmt(is_error, 1, "%s must be provided", server ? "uri" : "server");
        goto done;
    }
    if (!r) {
        char *names = mcp_res_names();
        out = mcp_fmt(is_error, 1, "MCP server \"%s\" has no resources%s%s", server,
                      names && *names ? ". Servers with resources: " : "", names ? names : "");
        free(names);
        goto done;
    }
    params = mcp_jtext("SELECT json_object('uri', ?1)", uri, NULL);
    if (!params || !db || !(res = mcp_row_ask(r, workspace, "resources/read", params, uri, 1, 1, &why, err, sizeof err))) {
        out = mcp_fmt(is_error, 1, "MCP server %s: %s", r->name, params && db ? err : "out of memory");
        goto done;
    }
    n = (int)mcp_jint("SELECT json_array_length(?1, '$.contents') WHERE json_type(?1, '$.contents') = 'array'", res, NULL, 0);
    if (sqlite3_prepare_v2(db,
                           "SELECT coalesce(json_extract(value, '$.uri'), ''), json_extract(value, '$.mimeType'),"
                           " CASE WHEN json_type(value, '$.text') = 'text' THEN json_extract(value, '$.text') END,"
                           " CASE WHEN json_type(value, '$.blob') = 'text' THEN json_extract(value, '$.blob') END"
                           " FROM json_each(?1, '$.contents') WHERE type = 'object'",
                           -1, &q, NULL) != SQLITE_OK) {
        out = mcp_fmt(is_error, 1, "out of memory");
        goto done;
    }
    sqlite3_bind_text(q, 1, res, -1, SQLITE_STATIC);
    t = sqlite3_str_new(NULL);
    for (int k = 0; sqlite3_step(q) == SQLITE_ROW; k++) {
        const char *at = (const char *)sqlite3_column_text(q, 0), *mime = (const char *)sqlite3_column_text(q, 1),
                   *text = (const char *)sqlite3_column_text(q, 2), *blob = (const char *)sqlite3_column_text(q, 3);
        if (k) {
            sqlite3_str_appendall(t, "\n");
        }
        if (n > 1) {
            sqlite3_str_appendf(t, "%s:\n", at);
        }
        if (text) {
            sqlite3_str_appendall(t, text);
        } else if (blob) {
            size_t bn = strlen(blob), len;
            unsigned char *bytes = malloc(3 * (bn / 4) + 3);
            len = bytes ? pic_base64_decode(blob, bn, bytes) : (size_t)-1;
            if (len == (size_t)-1) {
                sqlite3_str_appendf(t, "[resource %s: not base64]", at);
            } else {
                pic_image img = {NULL, bytes, len, 0, 0};
                const char *inline_mime = pic_image_inline_mime(mime ? mime : "");
                if (inline_mime && h->image && !attached && pic_image_check(&img, NULL, NULL, 0) == PIC_IMAGE_OK) {
                    sqlite3_str_appendf(t, "[image: %s]", img.mime);
                    h->image->mime = img.mime;
                    h->image->data = bytes;
                    h->image->len = len;
                    h->image->width = img.width;
                    h->image->height = img.height;
                    bytes = NULL;
                    attached = 1;
                } else {
                    sqlite3_str_appendf(t, "[resource %s: %s, %llu bytes, not shown]", at, mime ? mime : "binary",
                                        (unsigned long long)len);
                }
            }
            free(bytes);
        }
    }
    sqlite3_finalize(q);
    if (sqlite3_str_length(t) == 0) {
        sqlite3_str_appendf(t, "Resource %s is empty.", uri);
    }
    {
        char *done_text = sqlite3_str_finish(t);
        out = done_text ? strdup(done_text) : NULL;
        sqlite3_free(done_text);
    }
done:
    free(server);
    free(uri);
    free(params);
    free(res);
    return out;
}

static char *mcp_res_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
                         const pic_tool_hooks *h, int *is_error) {
    const char *input = h->input && *h->input ? h->input : "{}";
    char *out, *cut;
    (void)state;
    *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", tool);
    }
    out = strcmp(tool, "read_mcp_resource") == 0 ? mcp_res_read(workspace, input, h, is_error)
          : strcmp(tool, "list_mcp_resources") == 0 ? mcp_res_list(workspace, input, "resources/list", "resources", is_error)
                                                    : mcp_res_list(workspace, input, "resources/templates/list",
                                                                   "resourceTemplates", is_error);
    if (!out) {
        return mcp_fmt(is_error, 1, "out of memory");
    }
    if ((cut = mcp_cut_middle(out, h->output && h->output_name ? h->output_name : NULL))) {
        if (h->output && h->output_name) {
            h->output->data = out;
            h->output->len = strlen(out);
        } else {
            free(out);
        }
        return cut;
    }
    return out;
}

/* What R's tools stand for in readOnlyTools, into OUT: "mcp__SERVER__" for the user's own server;
 * a project's server stands for a name no entry can match, so a grant the user wrote for a name
 * never covers a project's server that merely has it. */
static void mcp_row_grant(const mcp_row *r, char *out, size_t cap) {
    if (r->source && !r->config) { /* --mcp-config's servers are the user's, given for this run */
        (void)snprintf(out, cap, "mcp-project:%s", r->name);
    } else {
        mcp_server_prefix(r->name, out, cap);
    }
}

/* A project server's tool: what a call stands for in readOnlyTools (pic_tool_stand_for). */
static char *mcp_tool_stands_for(const pic_tool_def *def, const char *input);

/* What a resource call with INPUT stands for in readOnlyTools: its server's grant name, or every
 * server's a listing without one reaches (pic_tool_stand_for). */
static char *mcp_res_stands_for(const pic_tool_def *def, const char *input) {
    char *server = mcp_jtext("SELECT trim(json_extract(?1, '$.server')) WHERE json_type(?1, '$.server') = 'text'"
                             " AND trim(json_extract(?1, '$.server')) <> ''",
                             input, NULL),
         *res, *out;
    sqlite3_str *t = sqlite3_str_new(NULL);
    char prefix[MCP_NAME_CAP + 16];
    (void)def;
    if (server) {
        mcp_server_prefix(server, prefix, sizeof prefix);
        for (size_t i = 0; i < mcp_reg_nrows; i++) {
            if (mcp_same_name(mcp_reg_rows[i].name, server)) {
                mcp_row_grant(&mcp_reg_rows[i], prefix, sizeof prefix);
            }
        }
        sqlite3_str_appendall(t, prefix);
    }
    for (size_t i = 0; !server && i < mcp_reg_nrows; i++) {
        if (mcp_res_reaches(&mcp_reg_rows[i])) {
            mcp_row_grant(&mcp_reg_rows[i], prefix, sizeof prefix);
            sqlite3_str_appendf(t, "%s%s", sqlite3_str_length(t) ? "\n" : "", prefix);
        }
    }
    res = sqlite3_str_finish(t);
    out = strdup(res ? res : "");
    sqlite3_free(res);
    free(server);
    return out;
}

/* Registers the resource tools when a server they reach has resources, with the widest exposure
 * among those servers (Pi): direct, else deferred, else codemode. */
static void mcp_res_register(void) {
    int rank = 0, sequential = 0; /* 3 direct, 2 deferred, 1 codemode */
    for (size_t i = 0; i < mcp_reg_nrows; i++) {
        const mcp_row *r = &mcp_reg_rows[i];
        const char *x;
        int k;
        if (!mcp_res_reaches(r)) {
            continue;
        }
        x = mcp_exposure_of(r, NULL);
        k = strcmp(x, "direct") == 0 ? 3 : strcmp(x, "deferred") == 0 ? 2 : 1;
        rank = k > rank ? k : rank;
        sequential |= r->command != NULL; /* one pipe per stdio server */
    }
    if (!rank) {
        return;
    }
    (void)snprintf(mcp_res_list_schema, sizeof mcp_res_list_schema,
                   "{\"name\":\"list_mcp_resources\",\"description\":\"Lists resources provided by MCP servers. Resources "
                   "allow servers to share data that provides context to language models, such as files, database "
                   "schemas, or application-specific information. Prefer resources over web search when possible.\",%s",
                   mcp_res_list_params);
    (void)snprintf(mcp_res_templates_schema, sizeof mcp_res_templates_schema,
                   "{\"name\":\"list_mcp_resource_templates\",\"description\":\"Lists resource templates provided by MCP "
                   "servers. Parameterized resource templates allow servers to share data that takes parameters and "
                   "provides context to language models, such as files, database schemas, or application-specific "
                   "information. Prefer resource templates over web search when possible.\",%s",
                   mcp_res_list_params);
    for (size_t i = 0; i < 3; i++) {
        mcp_res_defs[i].sequential = sequential;
        if (pic_tool_register(&mcp_res_defs[i]) != 0) {
            continue;
        }
        (void)pic_tool_stand_for(&mcp_res_defs[i], mcp_res_stands_for); /* a permission mode's view */
        if (rank < 3) {
            (void)pic_tool_defer(&mcp_res_defs[i], rank == 2 ? PIC_DEFER_SEARCH : PIC_DEFER_CODEMODE);
        }
    }
}

/* 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]);
    }
}

static char *mcp_tool_stands_for(const pic_tool_def *def, const char *input) {
    const mcp_tool *t = def->state;
    char grant[MCP_NAME_CAP + 32];
    (void)input;
    mcp_row_grant(&mcp_reg_rows[t->server], grant, sizeof grant);
    return strdup(grant);
}

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;
    }
    (void)pic_tool_on_request(mcp_relist_reset);
    for (size_t i = 0; i < mcp_reg_nrows; i++) { /* a --mcp-config server not listed yet: list it now */
        mcp_row *r = &mcp_reg_rows[i], again;
        char err[PIC_ERR_CAP] = "", era[32];
        if (!r->config || r->listed_ms || !r->enabled || r->error) {
            continue;
        }
        if (mcp_row_refresh(r, era, sizeof era, NULL, NULL, err, sizeof err) < 0) {
            (void)fprintf(stderr, "pic: MCP server %s (--mcp-config) could not be reached: %s\n", r->name, err);
        }
        if (mcp_project_row(MCP_CONFIG_KEY, MCP_CONFIG_KEY, r->name, r->entry, &again) == 0) {
            again.config = 1;
            mcp_row_free(r);
            *r = again;
        } else {
            mcp_row_free(&again);
        }
    }
    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 ||
            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];
            if (strcmp(mcp_exposure_of(r, (const char *)sqlite3_column_text(q, 0)), "hidden") == 0) {
                continue;
            }
            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];
        const char *x;
        if (!t->name) {
            continue;
        }
        x = mcp_exposure_of(&mcp_reg_rows[t->server], t->tool);
        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;
        if (mcp_reg_rows[t->server].source && mcp_user_tool_server(mcp_reg_rows, mcp_reg_nrows, t->def.name)) {
            continue; /* one of the user's tools has the name, enabled or not: the project's is left out */
        }
        if (pic_tool_register_new(&t->def) != 0) {
            /* a name another server's tool has: a project's tool never takes the user's (it is left
             * out, and pic mcp get says so); else this one gets the hash, as within one server */
            const pic_tool_def *other = pic_tool_named(t->def.name);
            int users = other && other->run == mcp_run && !mcp_reg_rows[((const mcp_tool *)other->state)->server].source;
            char named[128], *withname;
            if (mcp_reg_rows[t->server].source && users) {
                continue;
            }
            mcp_tool_name(mcp_reg_rows[t->server].name, t->tool, 1, named, sizeof named);
            if (!(withname = mcp_jtext3(NULL, "SELECT json_set(?1, '$.name', ?2)", t->schema, named, NULL))) {
                continue;
            }
            free(t->schema);
            free(t->name);
            t->schema = withname;
            t->name = strdup(named);
            t->def.name = t->name;
            t->def.schema = t->schema;
            if (!t->name || pic_tool_register_new(&t->def) != 0) {
                (void)fprintf(stderr, "pic: MCP tool %s from %s is left out: its name is taken\n", t->tool,
                              mcp_reg_rows[t->server].name);
                continue;
            }
        }
        if (mcp_reg_rows[t->server].source) {
            (void)pic_tool_stand_for(&t->def, mcp_tool_stands_for); /* readOnlyTools never covers it */
        }
        if (strcmp(x, "direct") != 0) {
            /* declared only once tool_search returns it (toolsearch.c); codemode's: called from scripts */
            (void)pic_tool_defer(&t->def, strcmp(x, "deferred") == 0 ? PIC_DEFER_SEARCH : PIC_DEFER_CODEMODE);
        }
    }
    mcp_res_register();
    return (int)mcp_reg_ntools;
}

/* ---- prompts: Claude Code's /mcp__SERVER__PROMPT commands ---------------------------------- */

/* Whether R's prompts are offered: enabled and not hidden. */
static int mcp_prompts_reach(const mcp_row *r) {
    return r->enabled && r->prompts && strcmp(mcp_exposure_of(r, NULL), "hidden") != 0;
}

char *pic_mcp_prompt_commands(void) {
    sqlite3 *db = mcp_jdb();
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *res, *out;
    int first = 1;
    sqlite3_str_appendall(t, "[");
    for (size_t i = 0; db && i < mcp_reg_nrows; i++) {
        const mcp_row *r = &mcp_reg_rows[i];
        sqlite3_stmt *q = NULL;
        if (!mcp_prompts_reach(r) ||
            sqlite3_prepare_v2(db,
                               "SELECT json_extract(value, '$.name'), coalesce(json_extract(value, '$.description'), ''),"
                               " (SELECT coalesce(group_concat(CASE WHEN json_extract(a.value, '$.required') = 1"
                               "  THEN '<' || json_extract(a.value, '$.name') || '>'"
                               "  ELSE '[' || json_extract(a.value, '$.name') || ']' END, ' '), '')"
                               "  FROM json_each(p.value, '$.arguments') a WHERE json_type(p.value, '$.arguments') = 'array')"
                               " FROM json_each(?1) p WHERE json_type(value, '$.name') = 'text'",
                               -1, &q, NULL) != SQLITE_OK) {
            sqlite3_finalize(q);
            continue;
        }
        sqlite3_bind_text(q, 1, r->prompts, -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);
            sqlite3_str_appendall(t, ",\"description\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 1));
            sqlite3_str_appendall(t, ",\"source\":\"mcp\",\"argumentHint\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 2));
            sqlite3_str_appendall(t, "}");
            first = 0;
        }
        sqlite3_finalize(q);
    }
    sqlite3_str_appendall(t, "]");
    res = sqlite3_str_finish(t);
    out = strdup(res ? res : "[]");
    sqlite3_free(res);
    return out;
}

/* The words of S, split at spaces, a "..." or '...' kept whole, as a JSON array (malloc'd). */
static char *mcp_words(const char *s) {
    sqlite3_str *t = sqlite3_str_new(NULL), *w = NULL;
    char *res, *out;
    int first = 1;
    sqlite3_str_appendall(t, "[");
    for (;;) {
        char quote = 0;
        s += strspn(s, " \t\r\n");
        if (!*s) {
            break;
        }
        w = sqlite3_str_new(NULL);
        for (; *s && (quote || !strchr(" \t\r\n", *s)); s++) {
            if (!quote && (*s == '"' || *s == '\'')) {
                quote = *s;
            } else if (quote && *s == quote) {
                quote = 0;
            } else {
                sqlite3_str_appendchar(w, 1, *s);
            }
        }
        res = sqlite3_str_finish(w);
        sqlite3_str_appendall(t, first ? "" : ",");
        pic_rpc_quote(t, res ? res : "");
        sqlite3_free(res);
        first = 0;
    }
    sqlite3_str_appendall(t, "]");
    res = sqlite3_str_finish(t);
    out = res ? strdup(res) : NULL;
    sqlite3_free(res);
    return out;
}

int pic_mcp_prompt_expand(const char *workspace, const char *text, char **out, char *err, size_t errcap) {
    char cmd[160], *words = NULL, *args = NULL, *params = NULL, *res = NULL, *missing = NULL, *prompt = NULL;
    const mcp_row *r = NULL;
    size_t n;
    int why, rc = -1;
    *out = NULL;
    if (strncmp(text, "/mcp__", 6) != 0 || (n = strcspn(text + 1, " \t\r\n")) >= sizeof cmd) {
        return 0;
    }
    (void)snprintf(cmd, sizeof cmd, "%.*s", (int)n, text + 1);
    for (size_t i = 0; i < mcp_reg_nrows && !prompt; i++) {
        sqlite3 *db = mcp_jdb();
        sqlite3_stmt *q = NULL;
        if (!db || !mcp_prompts_reach(&mcp_reg_rows[i]) ||
            sqlite3_prepare_v2(db, "SELECT json_extract(value, '$.name'), json(value) FROM json_each(?1)"
                                   " WHERE json_type(value, '$.name') = 'text'",
                               -1, &q, NULL) != SQLITE_OK) {
            sqlite3_finalize(q);
            continue;
        }
        sqlite3_bind_text(q, 1, mcp_reg_rows[i].prompts, -1, SQLITE_STATIC);
        while (!prompt && sqlite3_step(q) == SQLITE_ROW) {
            char name[128];
            mcp_tool_name(mcp_reg_rows[i].name, (const char *)sqlite3_column_text(q, 0), 0, name, sizeof name);
            if (strcmp(name, cmd) == 0) {
                r = &mcp_reg_rows[i];
                prompt = strdup((const char *)sqlite3_column_text(q, 1));
            }
        }
        sqlite3_finalize(q);
    }
    if (!prompt) {
        return 0;
    }
    /* the words in the order of the prompt's arguments, the rest joined into the last */
    if (!(words = mcp_words(text + 1 + n)) ||
        !(args = mcp_jtext("SELECT coalesce(json_group_object(json_extract(a.value, '$.name'),"
                           " CASE WHEN a.key + 1 = json_array_length(?1, '$.arguments')"
                           " THEN (SELECT group_concat(w.value, ' ') FROM json_each(?2) w WHERE w.key >= a.key)"
                           " ELSE json_extract(?2, '$[' || a.key || ']') END), '{}')"
                           " FROM json_each(?1, '$.arguments') a WHERE json_type(?1, '$.arguments') = 'array'"
                           " AND a.key < json_array_length(?2)",
                           prompt, words))) {
        (void)snprintf(err, errcap, "out of memory");
        goto done;
    }
    missing = mcp_jtext("SELECT group_concat(json_extract(value, '$.name'), ', ') FROM json_each(?1, '$.arguments')"
                        " WHERE json_type(?1, '$.arguments') = 'array' AND json_extract(value, '$.required') = 1"
                        " AND json_type(?2, '$.\"' || replace(json_extract(value, '$.name'), '\"', '') || '\"') IS NULL",
                        prompt, args);
    if (missing && *missing) {
        (void)snprintf(err, errcap, "/%s needs %s", cmd, missing);
        goto done;
    }
    params = mcp_jtext("SELECT json_object('name', json_extract(?1, '$.name'), 'arguments', json(?2))", prompt, args);
    {
        char *pname = mcp_jtext("SELECT json_extract(?1, '$.name')", prompt, NULL);
        res = params ? mcp_row_ask(r, workspace, "prompts/get", params, pname, 1, 1, &why, err, errcap) : NULL;
        free(pname);
    }
    if (!res) {
        char was[PIC_ERR_CAP];
        (void)snprintf(was, sizeof was, "%s", params ? err : "out of memory");
        (void)snprintf(err, errcap, "MCP server %s: %s", r->name, was);
        goto done;
    }
    *out = mcp_jtext("SELECT group_concat(CASE json_extract(value, '$.content.type')"
                     " WHEN 'text' THEN json_extract(value, '$.content.text')"
                     " WHEN 'resource' THEN coalesce(json_extract(value, '$.content.resource.text'),"
                     "  '[resource: ' || coalesce(json_extract(value, '$.content.resource.uri'), '') || ']')"
                     " WHEN 'resource_link' THEN '[resource: ' || coalesce(json_extract(value, '$.content.uri'), '') || ']'"
                     " ELSE '[' || coalesce(json_extract(value, '$.content.type'), 'content') || ']' END, char(10, 10))"
                     " FROM json_each(?1, '$.messages') WHERE json_type(?1, '$.messages') = 'array'",
                     res, NULL);
    if (!*out || !**out) {
        free(*out);
        *out = NULL;
        (void)snprintf(err, errcap, "MCP server %s's prompt /%s gave no messages", r->name, cmd);
        goto done;
    }
    rc = 1;
done:
    free(words);
    free(args);
    free(params);
    free(res);
    free(missing);
    free(prompt);
    return rc;
}

/* ---- @server:uri: Claude Code's resource mentions ------------------------------------------ */

#define MCP_MENTIONS_MAX 16 /* resources one message may name */

/* What resources/read gave for URI as text (malloc'd): each content's text, binary named. */
static char *mcp_res_text(const char *res) {
    return mcp_jtext("SELECT group_concat(CASE WHEN json_type(value, '$.text') = 'text' THEN json_extract(value, '$.text')"
                     " ELSE '[resource ' || coalesce(json_extract(value, '$.uri'), '') || ': ' ||"
                     " coalesce(json_extract(value, '$.mimeType'), 'binary') || ', not shown]' END, char(10))"
                     " FROM json_each(?1, '$.contents') WHERE json_type(?1, '$.contents') = 'array' AND type = 'object'",
                     res, NULL);
}

int pic_mcp_mentions(const char *workspace, const char *text, char **out, char *err, size_t errcap) {
    sqlite3_str *t = NULL;
    char seen[MCP_MENTIONS_MAX][512];
    int nseen = 0, rc = 0;
    *out = NULL;
    for (const char *p = strchr(text, '@'); p && nseen < MCP_MENTIONS_MAX; p = strchr(p + 1, '@')) {
        const mcp_row *r = NULL;
        size_t sn, un;
        char server[MCP_NAME_CAP], uri[512], *params, *res, *body, *cut;
        int why, dup = 0;
        if (p > text && !strchr(" \t\r\n(\"'", p[-1])) {
            continue; /* inside a word: an address, not a mention */
        }
        sn = strspn(p + 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-");
        if (sn == 0 || sn >= sizeof server || p[1 + sn] != ':') {
            continue;
        }
        (void)snprintf(server, sizeof server, "%.*s", (int)sn, p + 1);
        un = strcspn(p + 2 + sn, " \t\r\n\"'");
        while (un > 0 && strchr(".,;:!?)", p[2 + sn + un - 1])) {
            un--; /* the sentence's punctuation, not the URI's */
        }
        if (un == 0 || un >= sizeof uri) {
            continue;
        }
        (void)snprintf(uri, sizeof uri, "%.*s", (int)un, p + 2 + sn);
        for (size_t i = 0; i < mcp_reg_nrows && !r; i++) {
            r = mcp_res_reaches(&mcp_reg_rows[i]) && strcmp(mcp_reg_rows[i].name, server) == 0 ? &mcp_reg_rows[i] : NULL;
        }
        if (!r) {
            continue; /* none of the servers with resources */
        }
        (void)snprintf(seen[nseen], sizeof seen[nseen], "%.*s", (int)(sn + 1 + un), p + 1);
        for (int i = 0; i < nseen; i++) {
            dup |= strcmp(seen[i], seen[nseen]) == 0;
        }
        if (dup) {
            continue;
        }
        nseen++;
        params = mcp_jtext("SELECT json_object('uri', ?1)", uri, NULL);
        res = params ? mcp_row_ask(r, workspace, "resources/read", params, uri, 1, 1, &why, err, errcap) : NULL;
        free(params);
        if (!res) {
            char was[PIC_ERR_CAP];
            (void)snprintf(was, sizeof was, "%s", err);
            (void)snprintf(err, errcap, "@%s:%s: MCP server %s: %s", server, uri, server, was[0] ? was : "out of memory");
            rc = -1;
            break;
        }
        body = mcp_res_text(res);
        free(res);
        cut = body ? mcp_cut_middle(body, NULL) : NULL;
        if (!t) {
            t = sqlite3_str_new(NULL);
            sqlite3_str_appendall(t, text);
        }
        sqlite3_str_appendf(t, "\n\n<resource server=\"%s\" uri=\"", server);
        for (const char *c = uri; *c; c++) {
            sqlite3_str_appendall(t, *c == '"' ? "&quot;" : *c == '&' ? "&amp;" : *c == '<' ? "&lt;" : "");
            if (!strchr("\"&<", *c)) {
                sqlite3_str_appendchar(t, 1, *c);
            }
        }
        sqlite3_str_appendf(t, "\">\n%s\n</resource>", cut ? cut : body ? body : "");
        free(cut);
        free(body);
    }
    if (t) {
        char *res = sqlite3_str_finish(t);
        if (rc == 0 && res) {
            *out = strdup(res);
            rc = *out ? 1 : -1;
        }
        sqlite3_free(res);
    }
    return rc;
}

#define MCP_INSTRUCTIONS_MAX 8192    /* bytes of one server's instructions the system prompt takes */
#define MCP_INSTRUCTIONS_TOTAL 32768 /* and of every server's, in all */

char *pic_mcp_prompt_section(void) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *res, *out = NULL;
    int any = 0, left_out = 0;
    size_t used = 0;
    for (size_t i = 0; i < mcp_reg_nrows; i++) {
        const mcp_row *r = &mcp_reg_rows[i];
        const char *text = r->instructions;
        size_t n, whole;
        if (!r->enabled || !text || strcmp(mcp_exposure_of(r, NULL), "hidden") == 0) {
            continue;
        }
        text += strspn(text, " \t\r\n");
        for (n = strlen(text); n > 0 && strchr(" \t\r\n", text[n - 1]); n--) {
        }
        if (n == 0) {
            continue;
        }
        whole = n;
        if (used >= MCP_INSTRUCTIONS_TOTAL) { /* the section is full: this server's are left out */
            left_out++;
            continue;
        }
        if (n > MCP_INSTRUCTIONS_MAX || n > MCP_INSTRUCTIONS_TOTAL - used) { /* cut at a character's start */
            size_t cap = MCP_INSTRUCTIONS_TOTAL - used < MCP_INSTRUCTIONS_MAX ? MCP_INSTRUCTIONS_TOTAL - used
                                                                               : MCP_INSTRUCTIONS_MAX;
            for (n = cap; n > 0 && ((unsigned char)text[n] & 0xc0) == 0x80; n--) {
            }
        }
        used += n;
        if (!any) {
            sqlite3_str_appendall(t, "# MCP Server Instructions\n\nThe following MCP servers have provided instructions for"
                                     " how to use their tools and resources:");
            any = 1;
        }
        sqlite3_str_appendf(t, "\n\n## %s\n%.*s%s", r->name, (int)n, text, n < whole ? "\xe2\x80\xa6" : "");
    }
    if (left_out) {
        sqlite3_str_appendf(t, "\n\n(The instructions of %d more server%s are left out: the servers' instructions here are"
                               " limited to %d KB in all.)",
                            left_out, left_out == 1 ? "" : "s", MCP_INSTRUCTIONS_TOTAL / 1024);
    }
    res = sqlite3_str_finish(t);
    if (any && res) {
        out = strdup(res);
    }
    sqlite3_free(res);
    return out;
}

/* ---- 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: 0 with *COUNT, ERA, whether it has *RESOURCES and its
 * number of *NPROMPTS (may be NULL); 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, int *resources, int *nprompts, 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, resources, nprompts, err, errcap);
    mcp_rows_free(rows, n);
    return *count < 0 ? (*count = 0, 1) : 0;
}

/* Prints each !command value S will run when connecting (Pi's rule, pic mcp add's flags only),
 * so a pasted value starting with ! is visible. */
static void mcp_say_bang_commands(const mcp_spec *s) {
    if (!s->bang) {
        return;
    }
    for (size_t i = 0; i < s->nheaders; i++) {
        size_t n = strcspn(s->headers[i], ":");
        const char *v = s->headers[i] + n + 2;
        if (v[0] == '!') {
            printf("  %.*s runs: %s\n", (int)n, s->headers[i], v + 1);
        }
    }
    for (size_t i = 0; i < s->nenv; i++) {
        size_t n = strcspn(s->env[i], "=");
        const char *v = s->env[i] + n + 1;
        if (v[0] == '!') {
            printf("  %.*s runs: %s\n", (int)n, s->env[i], v + 1);
        }
    }
}

/* 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, resources = 0, nprompts = 0, sealed = s->nheaders || s->nenv,
               rc = mcp_add_quiet(s, &count, era, sizeof era, &resources, &nprompts, err, sizeof err);
    char extra[64] = "";
    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.");
        mcp_say_bang_commands(s);
        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;
    }
    if (nprompts) {
        (void)snprintf(extra, sizeof extra, " and %d prompt%s", nprompts, nprompts == 1 ? "" : "s");
    }
    printf("Added %s (%s): %d tool%s%s%s, MCP %s.%s\n", s->name, s->url ? s->url : "stdio", count, count == 1 ? "" : "s",
           resources ? (nprompts ? ", resources" : " and resources") : "", extra, era,
           !sealed ? "" : s->url ? " Its headers are sealed in the credential store." : " Its environment is sealed in the credential store.");
    mcp_say_bang_commands(s);
    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;
}

/* Whether one of the user's servers has NAME, or a name alike once '-' is '_'. */
static int mcp_name_taken(const char *name) {
    mcp_row *rows = NULL;
    size_t n = 0;
    int taken = 0;
    if (mcp_rows_load(NULL, NULL, &rows, &n) == 0) {
        for (size_t i = 0; i < n && !taken; i++) {
            taken = mcp_same_name(rows[i].name, name);
        }
    }
    mcp_rows_free(rows, n);
    return taken;
}

/* Claude Desktop's configuration file: macOS's, else the one under ~/.config (Linux, WSL). */
static char *mcp_desktop_config(char *path, size_t cap) {
    static const char *const where[] = {"Library/Application Support/Claude", ".config/Claude"};
    const char *home = getenv("HOME");
    for (size_t i = 0; home && i < sizeof where / sizeof where[0]; i++) {
        char *text;
        (void)snprintf(path, cap, "%s/%s/claude_desktop_config.json", home, where[i]);
        if ((text = mcp_slurp(path))) {
            return text;
        }
    }
    return NULL;
}

/* pic mcp add-from-claude-desktop [-s user|local] [NAME...], as Claude Code's: Claude Desktop's
 * servers (the NAMEs, or every one) added as pic mcp add-json adds them; a name one of yours has
 * gets _1, _2, ... */
static int mcp_cmd_add_desktop(int argc, char **argv) {
    char path[PATH_MAX + 64], *text;
    sqlite3 *db = mcp_jdb();
    sqlite3_stmt *q = NULL;
    int rc = 0, added = 0, k = 0;
    for (; k < argc && argv[k][0] == '-'; k += 2) {
        if ((strcmp(argv[k], "-s") != 0 && strcmp(argv[k], "--scope") != 0) || k + 1 >= argc ||
            (strcmp(argv[k + 1], "user") != 0 && strcmp(argv[k + 1], "local") != 0)) {
            fputs("pic: pic mcp add-from-claude-desktop [-s user|local] [NAME...]\n", stderr);
            return 2;
        }
    }
    if (!(text = mcp_desktop_config(path, sizeof path))) {
        fprintf(stderr, "pic: no Claude Desktop configuration at %s\n", path);
        return 1;
    }
    if (!db || mcp_jint("SELECT json_valid(?1) AND json_type(?1, '$.mcpServers') = 'object'", text, NULL, 0) != 1) {
        fprintf(stderr, "pic: %s has no mcpServers object\n", path);
        free(text);
        return 1;
    }
    for (int i = k; i < argc; i++) {
        if (mcp_jint("SELECT json_type(?1, '$.mcpServers.\"' || replace(?2, '\"', '') || '\"') = 'object'", text, argv[i], 0) != 1) {
            fprintf(stderr, "pic: Claude Desktop has no MCP server %s (%s)\n", argv[i], path);
            rc = 1;
        }
    }
    if (sqlite3_prepare_v2(db, "SELECT key, json(value) FROM json_each(?1, '$.mcpServers') WHERE type = 'object'", -1, &q,
                           NULL) != SQLITE_OK) {
        free(text);
        return 1;
    }
    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);
        char err[PIC_ERR_CAP] = "", as[MCP_NAME_CAP + 8];
        int wanted = k == argc;
        mcp_spec spec;
        for (int i = k; i < argc && !wanted; i++) {
            wanted = strcmp(argv[i], name) == 0;
        }
        if (!wanted) {
            continue;
        }
        (void)snprintf(as, sizeof as, "%s", name);
        for (int n = 1; mcp_name_taken(as) && n < 100; n++) {
            (void)snprintf(as, sizeof as, "%.56s_%d", name, n);
        }
        if (mcp_spec_json(as, entry, &spec, err, sizeof err) != 0) {
            fprintf(stderr, "pic: %s: %s\n", name, err);
            rc = 1;
        } else {
            rc |= mcp_add_spec(&spec);
            added++;
        }
        mcp_spec_free(&spec);
    }
    sqlite3_finalize(q);
    free(text);
    if (!added && !rc) {
        printf("Claude Desktop has no MCP servers (%s).\n", path);
    }
    return rc;
}

/* The last merge's file warnings on stderr, one "pic: warning:" line each. */
static void mcp_say_file_warnings(void) {
    for (const char *w = mcp_file_warnings, *e; *w; w = *e ? e + 1 : e) {
        e = w + strcspn(w, "\n");
        fprintf(stderr, "pic: warning: %.*s\n", (int)(e - w), w);
    }
}

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;
    }
    mcp_say_file_warnings();
    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, NULL, NULL, err, sizeof err);
        }
        printf("%-*s  %-5s  %-10s  ", (int)width, r->name, r->transport, era[0] ? era : (r->era ? r->era : "-"));
        if (r->source) {
            printf(r->config ? "config  " : "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;
    }
    mcp_say_file_warnings();
    r = &rows[0];
    printf("%s\n  transport: %s\n", r->name, r->transport);
    if (r->config) {
        printf("  from: --mcp-config (its values are as given there, not sealed)\n");
    } else 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->headers_helper) {
        printf("  headers helper: %s\n", r->headers_helper);
    }
    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");
    {
        const char *by, *x = mcp_exposure_by(r, NULL, &by);
        if (r->exposure || by) {
            printf("  exposure: %s%s%s\n", x, by ? ", narrowed by " : "", by ? by : "");
        }
    }
    if (r->resources) {
        printf("  resources: offered (list_mcp_resources, read_mcp_resource)\n");
    }
    if (r->error) {
        printf("  last error: %s\n", r->error);
    }
    if (r->warning) {
        printf("  warning: %s\n", r->warning);
    }
    if (r->source) { /* a project's tool named as one of the user's is left out (pic_mcp_register) */
        mcp_row *all = NULL;
        size_t nall = 0;
        if (mcp_rows_load(mcp_cli_ws, NULL, &all, &nall) == 0 && db && r->tools &&
            sqlite3_prepare_v2(db, "SELECT json_extract(value, '$.name') FROM json_each(?1)"
                                   " WHERE json_type(value, '$.name') = 'text'",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, r->tools, -1, SQLITE_STATIC);
            while (sqlite3_step(q) == SQLITE_ROW) {
                char name[128];
                const char *mine;
                mcp_tool_name(r->name, (const char *)sqlite3_column_text(q, 0), 0, name, sizeof name);
                if ((mine = mcp_user_tool_server(all, nall, name))) {
                    printf("  warning: %s: %s is one of your tools (%s); pic leaves this one out\n", r->source, name, mine);
                }
            }
        }
        sqlite3_finalize(q);
        q = NULL;
        mcp_rows_free(all, nall);
    }
    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) {
            const char *tool = (const char *)sqlite3_column_text(q, 0), *by, *x = mcp_exposure_by(r, tool, &by);
            int own = by || strcmp(x, mcp_exposure_of(r, NULL)) != 0;
            char name[128];
            mcp_tool_name(r->name, tool, 0, name, sizeof name);
            printf("    %s  %s%s%s%s%s\n", name,
                   sqlite3_column_int(q, 1) ? "read-only: run again after a crash" : "outcome unknown after a crash",
                   own ? "  " : "", own ? x : "", by ? ", narrowed by " : "", by ? by : "");
        }
    }
    sqlite3_finalize(q);
    mcp_rows_free(rows, n);
    return 0;
}

/* The user's server (in ROWS) that has a tool named NAME as the model sees it, or NULL. */
static const char *mcp_user_tool_server(const mcp_row *rows, size_t n, const char *name) {
    sqlite3 *db = mcp_jdb();
    const char *found = NULL;
    for (size_t i = 0; db && i < n && !found; i++) {
        sqlite3_stmt *q = NULL;
        if (rows[i].source || !rows[i].tools ||
            sqlite3_prepare_v2(db, "SELECT json_extract(value, '$.name') FROM json_each(?1)"
                                   " WHERE json_type(value, '$.name') = 'text'",
                               -1, &q, NULL) != SQLITE_OK) {
            sqlite3_finalize(q);
            continue;
        }
        sqlite3_bind_text(q, 1, rows[i].tools, -1, SQLITE_STATIC);
        while (!found && sqlite3_step(q) == SQLITE_ROW) {
            char theirs[128];
            mcp_tool_name(rows[i].name, (const char *)sqlite3_column_text(q, 0), 0, theirs, sizeof theirs);
            found = strcmp(theirs, name) == 0 ? rows[i].name : NULL;
        }
        sqlite3_finalize(q);
    }
    return found;
}

/* 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;
}

/* Sets server NAME's exposure (TOOL NULL), or one of its tools' (TOOL, its name on the server or a
 * pattern), to X (NULL: back to what the server's is). 0, or -1 with err. A project's server is
 * its file's. */
static int mcp_set_exposure(const char *workspace, const char *name, const char *tool, const char *x, char *err,
                            size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    sqlite3_stmt *q = NULL;
    mcp_row *rows = NULL;
    size_t n = 0;
    char src[PATH_MAX + 32], *real = NULL;
    int rc = -1;
    if (x && !mcp_exposure_known(x)) {
        (void)snprintf(err, errcap, "%s", mcp_exposure_words);
        return -1;
    }
    if (mcp_project_source(workspace, name, src, sizeof src)) {
        (void)snprintf(err, errcap, "%s is the project's, in %s: set \"%s\" there", name, src,
                       tool ? "toolExposure" : "exposure");
        return -1;
    }
    if (!db || mcp_rows_load(NULL, name, &rows, &n) != 0 || n == 0) {
        (void)snprintf(err, errcap, "no MCP server is saved as %s (pic mcp list)", name);
        mcp_rows_free(rows, n);
        return -1;
    }
    if (tool && !strchr(tool, '*') &&
        mcp_jint("SELECT count(*) FROM json_each(?1) WHERE json_extract(value, '$.name') = ?2", rows[0].tools, tool, 0) == 0) {
        /* the tool as the model sees it, mcp__SERVER__TOOL: its name on the server */
        sqlite3 *jdb = mcp_jdb();
        sqlite3_stmt *t = NULL;
        if (jdb && sqlite3_prepare_v2(jdb, "SELECT json_extract(value, '$.name') FROM json_each(?1)"
                                           " WHERE json_type(value, '$.name') = 'text'",
                                      -1, &t, NULL) == SQLITE_OK) {
            sqlite3_bind_text(t, 1, rows[0].tools, -1, SQLITE_STATIC);
            while (!real && sqlite3_step(t) == SQLITE_ROW) {
                char full[128];
                mcp_tool_name(name, (const char *)sqlite3_column_text(t, 0), 0, full, sizeof full);
                real = strcmp(full, tool) == 0 ? strdup((const char *)sqlite3_column_text(t, 0)) : NULL;
            }
        }
        sqlite3_finalize(t);
        if (!real) {
            (void)snprintf(err, errcap, "%s has no tool %s (pic mcp get %s)", name, tool, name);
            mcp_rows_free(rows, n);
            return -1;
        }
        tool = real;
    }
    mcp_rows_free(rows, n);
    if (sqlite3_prepare_v2(db,
                           tool ? "UPDATE picu_mcp_server SET tool_exposure = nullif(CASE WHEN ?3 IS NULL"
                                  " THEN json_remove(coalesce(tool_exposure, '{}'), '$.\"' || replace(?2, '\"', '') || '\"')"
                                  " ELSE json_set(coalesce(tool_exposure, '{}'), '$.\"' || replace(?2, '\"', '') || '\"', ?3) END, '{}')"
                                  " WHERE name = ?1"
                                : "UPDATE picu_mcp_server SET exposure = ?3 WHERE name = ?1 AND ?2 IS NULL",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, tool, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 3, x, -1, SQLITE_STATIC);
        rc = sqlite3_step(q) == SQLITE_DONE && sqlite3_changes(db) == 1 ? 0 : -1;
    }
    free(real);
    sqlite3_finalize(q);
    if (rc != 0) {
        (void)snprintf(err, errcap, "cannot save the exposure in ~/.pic/pic.sqlite");
    }
    return rc;
}

/* pic mcp exposure [--unset] SERVER [TOOL] [EXPOSURE]. */
static int mcp_cmd_exposure(int argc, char **argv) {
    char err[PIC_ERR_CAP] = "";
    const char *server, *tool = NULL, *x = NULL;
    int unset = argc > 0 && strcmp(argv[0], "--unset") == 0;
    argc -= unset;
    argv += unset;
    if (argc < 1 || argc > 3 || (unset && argc > 2) || (!unset && argc < 2)) {
        fputs("pic: pic mcp exposure SERVER [TOOL] direct|deferred|codemode|hidden, or --unset SERVER [TOOL]\n", stderr);
        return 2;
    }
    server = argv[0];
    if (unset) {
        tool = argc == 2 ? argv[1] : NULL;
    } else {
        tool = argc == 3 ? argv[1] : NULL;
        x = argv[argc - 1];
    }
    if (mcp_set_exposure(mcp_cli_ws, server, tool, x, err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    if (tool) {
        char name[128];
        if (strncmp(tool, "mcp__", 5) == 0) {
            (void)snprintf(name, sizeof name, "%s", tool);
        } else {
            mcp_tool_name(server, tool, 0, name, sizeof name);
        }
        printf(x ? "%s is %s from the next request.\n" : "%s takes %s's exposure from the next request.\n", name,
               x ? x : server);
    } else {
        printf(x ? "%s is %s from the next request.\n" : "%s is direct from the next request.\n", server, x);
    }
    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, toolExposure, timeout, enabled, resources, era, error, listedAt, tools:
 * [{name, tool, readOnly, exposure, userExposure}]}]}, as saved: nothing is connected. exposure
 * is what reaches requests, userExposure what the user's own settings give (a project may narrow). */
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, "headersHelper", r->headers_helper);
        mcp_rpc_text(t, "exposure", r->exposure);
        sqlite3_str_appendf(t, ",\"toolExposure\":%s", r->tool_exposure ? r->tool_exposure : "null");
        {
            const char *by, *x = mcp_exposure_by(r, NULL, &by);
            mcp_rpc_text(t, "effectiveExposure", x);
            mcp_rpc_text(t, "narrowedBy", by);
            mcp_rpc_text(t, "warning", r->warning);
        }
        sqlite3_str_appendf(t, ",\"timeout\":%d,\"enabled\":%s,\"resources\":%s", r->timeout, r->enabled ? "true" : "false",
                            r->resources ? "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));
                {
                    const char *tool = (const char *)sqlite3_column_text(q, 0), *by, *x = mcp_exposure_by(r, tool, &by);
                    sqlite3_str_appendf(t, ",\"readOnly\":%s,\"exposure\":\"%s\",\"userExposure\":\"%s\"",
                                        sqlite3_column_int(q, 1) ? "true" : "false", x,
                                        mcp_exposure_in(r->exposure, r->tool_exposure, tool, "direct"));
                    mcp_rpc_text(t, "narrowedBy", by);
                    sqlite3_str_appendall(t, "}");
                }
                first = 0;
            }
        }
        sqlite3_finalize(q);
        sqlite3_str_appendall(t, "]}");
        free(cmd);
    }
    sqlite3_str_appendall(t, "],\"warnings\":[");
    for (const char *w = mcp_file_warnings, *e; *w; w = *e ? e + 1 : e) {
        char line[1024];
        e = w + strcspn(w, "\n");
        (void)snprintf(line, sizeof line, "%.*s", (int)(e - w), w);
        if (w != mcp_file_warnings) {
            sqlite3_str_appendall(t, ",");
        }
        pic_rpc_quote(t, line);
    }
    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, NULL, NULL, 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, NULL, NULL, 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;
}

/* set_mcp_tool_exposure name [tool] exposure: {"name", "tool", "exposure"}; tool absent: the
 * server's own, exposure null: back to the server's (or direct). From the next request. */
static int mcp_tool_exposure_answer(pic_rpc_call *c) {
    char *name = pic_rpc_text(c, "$.name"), *tool = pic_rpc_text(c, "$.tool"), *x = pic_rpc_text(c, "$.exposure");
    int rc = -1;
    if (!name) {
        (void)snprintf(c->err, sizeof c->err, "set_mcp_tool_exposure needs name, and exposure (null: unset)");
    } else if (mcp_set_exposure(c->workspace, name, tool, x, c->err, sizeof c->err) == 0) {
        sqlite3_str *t = sqlite3_str_new(NULL);
        sqlite3_str_appendall(t, "{\"name\":");
        pic_rpc_quote(t, name);
        mcp_rpc_text(t, "tool", tool);
        mcp_rpc_text(t, "exposure", x);
        sqlite3_str_appendall(t, "}");
        rc = mcp_rpc_done(c, t);
    }
    free(name);
    free(tool);
    free(x);
    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};
const pic_rpc_command pic_set_mcp_tool_exposure_rpc = {"set_mcp_tool_exposure",
                                                       "how an MCP server's tools, or one of them, reach the model",
                                                       MCP_RPC_FLAGS, mcp_tool_exposure_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, "add-from-claude-desktop") == 0) {
        return mcp_cmd_add_desktop(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);
    }
    if (strcmp(verb, "exposure") == 0) {
        return mcp_cmd_exposure(argc - 1, argv + 1);
    }
    fputs("pic: pic mcp add | add-json | add-from-claude-desktop | list | get NAME | remove NAME | exposure SERVER [TOOL] X | call SERVER TOOL [JSON]"
          " (pic help mcp)\n",
          stderr);
    return 2;
}