Skip to content
pi-c Documentation
Login

Documentation

/* The MCP protocol over streamable HTTP or a stdio pipe (mcp_wire.h). */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "help.h"
#include "http.h"
#include "image.h"
#include "mcp_wire.h"
#include "net.h"
#include "sqlite3.h"
#include "sse.h"

#define MCP_BODY_CAP (32u << 20)
#define MCP_LIST_PAGES 100

/* The 2025 handshake's revisions, newest first: pic asks for the first and accepts any. */
static const char *const mcp_older[] = {"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"};

static const pic_mcp_pipe_ops *mcp_pipes;
void pic_mcp_pipe_register(const pic_mcp_pipe_ops *ops) { mcp_pipes = ops; }

char *pic_mcp_run(const char *command, const char *const *env, int timeout, char *err, size_t errcap) {
    if (!mcp_pipes || !mcp_pipes->run) {
        (void)snprintf(err, errcap, "this build of pic cannot run commands");
        return NULL;
    }
    return mcp_pipes->run(command, env, timeout, err, errcap);
}

struct pic_mcp_conn {
    const pic_mcp_target *t;
    sqlite3 *db; /* :memory:, for the JSON functions */
    pic_net *net;
    pic_mcp_pipe *pipe;
    char era[16];
    int cached; /* the era is T's, not learnt on this connection */
    char session[256];
    char *instructions;
    char *capabilities; /* the server's, when this connection asked for them; NULL otherwise */
    long long next_id;
    int changed; /* PIC_MCP_*_CHANGED: the list_changed notifications seen */
};

/* One exchange's outcome: the status (200 for a pipe), the response to our id when one came, and
 * the body otherwise (for an error's words). */
typedef struct {
    int status;
    char *msg;
    char *body;
    size_t len;
    int too_big;
    char session[256];
} mcp_reply;

static void mw_reply_free(mcp_reply *r) {
    free(r->msg);
    free(r->body);
    memset(r, 0, sizeof *r);
}

static int mw_is_current(const char *era) { return era && strcmp(era, PIC_MCP_CURRENT) == 0; }

/* The first column of SQL's first row as text (malloc'd), over text arguments A, B (NULL binds
 * NULL), or NULL. */
static char *mw_text(sqlite3 *db, const char *sql, const char *a, const char *b) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) == SQLITE_OK) {
        if (sqlite3_bind_parameter_count(q) >= 1) {
            sqlite3_bind_text(q, 1, a, -1, SQLITE_STATIC);
        }
        if (sqlite3_bind_parameter_count(q) >= 2) {
            sqlite3_bind_text(q, 2, b, -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 long long mw_int(sqlite3 *db, const char *sql, const char *a, long long dflt) {
    char *v = mw_text(db, sql, a, NULL);
    long long n = v ? strtoll(v, NULL, 10) : dflt;
    free(v);
    return n;
}

#define MW_ANSWER_SQL                                                                                                     \
    "SELECT ?1 WHERE json_valid(?1) AND json_type(?1) = 'object' AND json_type(?1, '$.id') = 'integer'"                \
    " AND json_extract(?1, '$.id') = CAST(?2 AS INTEGER) AND (json_type(?1, '$.result') = 'object'"                     \
    " OR json_type(?1, '$.error') = 'object')"

/* JSON (malloc'd) when it is the response to ID: a valid object with that id and a result or an
 * error; else NULL. */
static char *mw_answer_to(sqlite3 *db, const char *json, long long id) {
    char want[32];
    (void)snprintf(want, sizeof want, "%lld", id);
    return mw_text(db, MW_ANSWER_SQL, json, want);
}

/* ---- streamable HTTP ------------------------------------------------------------------------ */

/* Notes a list_changed notification in JSON, a message that is not the answer. */
static void mw_note(pic_mcp_conn *c, const char *json) {
    long long bit = mw_int(c->db,
                           "SELECT CASE json_extract(?1, '$.method') WHEN 'notifications/tools/list_changed' THEN 1"
                           " WHEN 'notifications/prompts/list_changed' THEN 2 WHEN 'notifications/resources/list_changed'"
                           " THEN 4 ELSE 0 END WHERE json_valid(?1) AND json_type(?1, '$.id') IS NULL",
                           json, 0);
    c->changed |= (int)bit;
}

typedef struct {
    pic_mcp_conn *c;
    mcp_reply *rep;
    sqlite3 *db;
    long long id;
    pic_sse sse;
    int sse_on;
} mw_http_ctx;

static int mw_http_event(void *ctx, const char *event, const char *data, size_t n) {
    mw_http_ctx *h = ctx;
    (void)event;
    (void)n;
    if (!h->rep->msg && (h->rep->msg = mw_answer_to(h->db, data, h->id))) {
        return 1; /* the answer is in: stop reading */
    }
    mw_note(h->c, data);
    return 0;
}

static int mw_http_head(void *ctx, const pic_http_resp *r) {
    mw_http_ctx *h = ctx;
    if (r->status == 200 && strncasecmp(r->content_type, "text/event-stream", 17) == 0) {
        if (pic_sse_init(&h->sse, 1u << 20, MCP_BODY_CAP, mw_http_event, h) != 0) {
            return -1;
        }
        h->sse_on = 1;
    }
    return 0;
}

static int mw_http_body(void *ctx, const char *bytes, size_t n) {
    mw_http_ctx *h = ctx;
    mcp_reply *rep = h->rep;
    char *grown;
    if (h->sse_on) {
        return pic_sse_feed(&h->sse, bytes, n);
    }
    if (rep->len + n > MCP_BODY_CAP) {
        rep->too_big = 1;
        return 2;
    }
    if (!(grown = realloc(rep->body, rep->len + n + 1))) {
        return 2;
    }
    rep->body = grown;
    memcpy(rep->body + rep->len, bytes, n);
    rep->len += n;
    rep->body[rep->len] = '\0';
    return 0;
}

/* The header "PREFIXvalue" for V (malloc'd, whole however long): printable ASCII without leading
 * or trailing spaces as it is, otherwise the current revision's =?base64?...?= form; NULL out of
 * memory. */
static char *mw_header(const char *prefix, const char *v) {
    size_t n = strlen(v), pn = strlen(prefix), cap = pn + 4 * ((n + 2) / 3) + n + 16;
    int plain = n > 0 && v[0] != ' ' && v[n - 1] != ' ';
    char *out = malloc(cap);
    for (size_t i = 0; plain && i < n; i++) {
        plain = (unsigned char)v[i] >= 0x20 && (unsigned char)v[i] < 0x7f;
    }
    if (!out) {
        return NULL;
    }
    if (plain) {
        (void)snprintf(out, cap, "%s%s", prefix, v);
        return out;
    }
    memcpy(out, prefix, pn);
    memcpy(out + pn, "=?base64?", 9);
    n = pic_base64_encode((const unsigned char *)v, n, out + pn + 9);
    (void)snprintf(out + pn + 9 + n, cap - pn - 9 - n, "?=");
    return out;
}

static int mw_http_exchange(pic_mcp_conn *c, const char *method, const char *name, const char *body, long long id,
                         int notify, mcp_reply *rep, char *err, size_t errcap) {
    const pic_mcp_target *t = c->t;
    const char **h = calloc(t->nheaders + 8, sizeof *h);
    char version[64], mmethod[160], *mname = NULL, sess[300];
    size_t nh = 0;
    pic_http_resp r;
    mw_http_ctx ctx;
    int rc;
    if (!h) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    h[nh++] = "Content-Type: application/json";
    h[nh++] = "Accept: application/json, text/event-stream";
    h[nh++] = "User-Agent: pic";
    if (c->era[0]) {
        (void)snprintf(version, sizeof version, "MCP-Protocol-Version: %s", c->era);
        h[nh++] = version;
    }
    if (mw_is_current(c->era)) {
        (void)snprintf(mmethod, sizeof mmethod, "Mcp-Method: %s", method);
        h[nh++] = mmethod;
        if (name) {
            if (!(mname = mw_header("Mcp-Name: ", name))) {
                free(h);
                (void)snprintf(err, errcap, "out of memory");
                return -1;
            }
            h[nh++] = mname;
        }
    } else if (c->session[0]) {
        (void)snprintf(sess, sizeof sess, "Mcp-Session-Id: %s", c->session);
        h[nh++] = sess;
    }
    for (size_t i = 0; i < t->nheaders; i++) {
        h[nh++] = t->headers[i];
    }
    memset(&ctx, 0, sizeof ctx);
    ctx.c = c;
    ctx.rep = rep;
    ctx.db = c->db;
    ctx.id = id;
    pic_http_resp_init(&r, mw_http_body, &ctx);
    r.on_head = mw_http_head;
    r.want = "Mcp-Session-Id";
    rc = pic_http_post(c->net, t->url, h, nh, body, strlen(body), &r, t->timeout,
                       t->timeout > 60 ? t->timeout * 10 : 600, err, errcap);
    free(h);
    free(mname);
    if (ctx.sse_on) {
        pic_sse_free(&ctx.sse);
    }
    rep->status = r.status;
    (void)snprintf(rep->session, sizeof rep->session, "%s", r.wanted);
    if (rc != 0 && rep->msg) {
        return 0; /* stopped once the answer was in */
    }
    if (rc != 0) {
        if (strstr(err, "sent nothing for") || strstr(err, "past its deadline")) {
            char was[512];
            (void)snprintf(was, sizeof was, "%s", err);
            (void)snprintf(err, errcap, "timed out (no answer within %d seconds): %s", t->timeout, was);
        }
        return -1;
    }
    if (!notify && !rep->msg && r.status == 200 && rep->body) {
        rep->msg = mw_answer_to(c->db, rep->body, id);
    }
    return 0;
}

/* ---- the pipe --------------------------------------------------------------------------------- */

static int mw_pipe_exchange(pic_mcp_conn *c, const char *body, long long id, int notify, mcp_reply *rep, char *err,
                         size_t errcap) {
    char *line;
    if (mcp_pipes->send(c->pipe, body, strlen(body), err, errcap) != 0) {
        return -1;
    }
    rep->status = 200;
    if (notify) {
        return 0;
    }
    while ((line = mcp_pipes->recv(c->pipe, c->t->timeout, err, errcap))) {
        char *rid;
        if ((rep->msg = mw_answer_to(c->db, line, id))) {
            free(line);
            return 0;
        }
        mw_note(c, line);
        /* a request of the server's own: ping is answered, anything else is not supported */
        rid = mw_text(c->db,
                     "SELECT json_extract(?1, '$.id') WHERE json_valid(?1) AND json_type(?1, '$.method') = 'text'"
                     " AND json_type(?1, '$.id') IN ('integer', 'text')",
                     line, NULL);
        if (rid) {
            char *ans = mw_text(c->db,
                               "SELECT CASE json_extract(?1, '$.method') WHEN 'ping' THEN"
                               " json_object('jsonrpc', '2.0', 'id', json_extract(?1, '$.id'), 'result', json_object())"
                               " ELSE json_object('jsonrpc', '2.0', 'id', json_extract(?1, '$.id'), 'error',"
                               " json_object('code', -32601, 'message', 'pic does not support ' || json_extract(?1, '$.method')))"
                               " END",
                               line, NULL);
            if (ans) {
                (void)mcp_pipes->send(c->pipe, ans, strlen(ans), err, errcap);
            }
            free(ans);
            free(rid);
        }
        free(line);
    }
    if (strstr(err, "timed out") == NULL && strstr(err, "interrupted") == NULL) {
        char was[512];
        (void)snprintf(was, sizeof was, "%s", err);
        (void)snprintf(err, errcap, "the server stopped before it answered (%s)", was);
    }
    return -1;
}

/* ---- the protocol ------------------------------------------------------------------------------ */

/* Sends METHOD (a notification when NOTIFY) with PARAMS under the connection's revision: the
 * current one carries its _meta in the params. 0 when an exchange completed (any status), or
 * -1 with err. */
static int mcp_send(pic_mcp_conn *c, const char *method, const char *params, const char *name, int notify,
                    long long *id_out, mcp_reply *rep, char *err, size_t errcap) {
    char version[32], *p = NULL, *body;
    long long id = c->next_id++;
    sqlite3_str *b;
    int rc;
    memset(rep, 0, sizeof *rep);
    *id_out = id;
    pic_version(version, sizeof version);
    if (mw_is_current(c->era)) {
        p = mw_text(c->db,
                   "SELECT json_set(coalesce(json(?1), '{}'), '$._meta', json_object("
                   "'io.modelcontextprotocol/protocolVersion', '" PIC_MCP_CURRENT "',"
                   "'io.modelcontextprotocol/clientCapabilities', json_object(),"
                   "'io.modelcontextprotocol/clientInfo', json_object('name', 'pic', 'version', ?2)))",
                   params, version);
    } else if (params) {
        p = mw_text(c->db, "SELECT json(?1)", params, NULL);
    }
    if ((params || mw_is_current(c->era)) && !p) {
        (void)snprintf(err, errcap, "the request's parameters are not a JSON object");
        return -1;
    }
    b = sqlite3_str_new(NULL);
    sqlite3_str_appendall(b, "{\"jsonrpc\":\"2.0\",");
    if (!notify) {
        sqlite3_str_appendf(b, "\"id\":%lld,", id);
    }
    sqlite3_str_appendf(b, "\"method\":\"%s\"", method);
    if (p) {
        sqlite3_str_appendf(b, ",\"params\":%s", p);
    }
    sqlite3_str_appendall(b, "}");
    free(p);
    if (!(body = sqlite3_str_finish(b))) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    rc = c->pipe ? mw_pipe_exchange(c, body, id, notify, rep, err, errcap)
                 : mw_http_exchange(c, method, name, body, id, notify, rep, err, errcap);
    sqlite3_free(body);
    return rc;
}

/* The JSON-RPC error code of MSG (or of the body BODY when there is no MSG), or 0. */
static long long mw_error_code(pic_mcp_conn *c, const mcp_reply *rep) {
    const char *json = rep->msg ? rep->msg : rep->body;
    return json ? mw_int(c->db,
                        "SELECT CASE WHEN json_valid(?1) AND json_type(?1, '$.error.code') = 'integer'"
                        " THEN json_extract(?1, '$.error.code') ELSE 0 END",
                        json, 0)
                : 0;
}

static int mw_modern_code(long long code) { return code == -32020 || code == -32021 || code == -32022; }

/* Whether REP says the server does not speak the current revision: a 400, 404 or 405 whose body
 * is not one of its errors, or (a pipe) any error answer that is not. */
static int mw_speaks_older(pic_mcp_conn *c, const mcp_reply *rep) {
    long long code = mw_error_code(c, rep);
    if (mw_modern_code(code)) {
        return 0;
    }
    if (c->pipe) {
        return rep->msg && code != 0;
    }
    return (rep->status == 400 || rep->status == 404 || rep->status == 405) ||
           (rep->status == 200 && rep->msg && code != 0);
}

/* A plain sentence for a reply that is not a result, into err. */
static void mw_say_refusal(pic_mcp_conn *c, const mcp_reply *rep, char *err, size_t errcap) {
    const char *json = rep->msg ? rep->msg : rep->body;
    char *words = json ? mw_text(c->db,
                                "SELECT CAST(json_extract(?1, '$.error.code') AS TEXT) || ' ' ||"
                                " coalesce(json_extract(?1, '$.error.message'), '')"
                                " WHERE json_valid(?1) AND json_type(?1, '$.error') = 'object'",
                                json, NULL)
                       : NULL;
    if (rep->status == 401 || rep->status == 403) {
        (void)snprintf(err, errcap,
                       "%s refused the request (HTTP %d): it needs a token. Give one with -H \"Authorization: Bearer ...\""
                       " (pic mcp add again); pic does not sign in to MCP servers itself yet",
                       c->t->name, rep->status);
    } else if (words && rep->msg) {
        (void)snprintf(err, errcap, "%.300s", words);
    } else if (words) {
        (void)snprintf(err, errcap, "%s answered HTTP %d: %.300s", c->t->name, rep->status, words);
    } else if (rep->status == 202) {
        (void)snprintf(err, errcap, "%s accepted the request without answering it", c->t->name);
    } else if (rep->too_big) {
        (void)snprintf(err, errcap, "%s answered with more than %u MB", c->t->name, MCP_BODY_CAP >> 20);
    } else {
        (void)snprintf(err, errcap, "%s answered HTTP %d without a JSON-RPC response", c->t->name, rep->status);
    }
    free(words);
}

/* The 2025 handshake: initialize, then notifications/initialized. 0, or -1 with err. */
static int mw_handshake(pic_mcp_conn *c, char *err, size_t errcap) {
    char version[32], *params, *era = NULL;
    mcp_reply rep;
    long long id;
    int ok = 0;
    c->era[0] = '\0';
    c->session[0] = '\0';
    c->cached = 0;
    pic_version(version, sizeof version);
    params = mw_text(c->db,
                    "SELECT json_object('protocolVersion', ?1, 'capabilities', json_object(),"
                    " 'clientInfo', json_object('name', 'pic', 'version', ?2))",
                    mcp_older[0], version);
    if (!params || mcp_send(c, "initialize", params, NULL, 0, &id, &rep, err, errcap) != 0) {
        free(params);
        return -1;
    }
    free(params);
    if (rep.msg) {
        era = mw_text(c->db, "SELECT json_extract(?1, '$.result.protocolVersion') WHERE json_type(?1, '$.result') = 'object'",
                     rep.msg, NULL);
    }
    if (!era) {
        mw_say_refusal(c, &rep, err, errcap);
        mw_reply_free(&rep);
        return -1;
    }
    for (size_t i = 0; i < sizeof mcp_older / sizeof mcp_older[0]; i++) {
        ok |= strcmp(era, mcp_older[i]) == 0;
    }
    if (!ok) {
        (void)snprintf(err, errcap, "%s chose MCP revision %.40s, which pic does not speak", c->t->name, era);
        free(era);
        mw_reply_free(&rep);
        return -1;
    }
    (void)snprintf(c->era, sizeof c->era, "%s", era);
    free(era);
    free(c->instructions);
    c->instructions = mw_text(c->db, "SELECT json_extract(?1, '$.result.instructions')", rep.msg, NULL);
    free(c->capabilities);
    c->capabilities = mw_text(c->db, "SELECT coalesce(json(json_extract(?1, '$.result.capabilities')), '{}')", rep.msg, NULL);
    if (rep.session[0]) {
        for (const char *s = rep.session; *s; s++) {
            if ((unsigned char)*s < 0x21 || (unsigned char)*s > 0x7e) {
                (void)snprintf(err, errcap, "%s gave a session id that cannot be sent back", c->t->name);
                mw_reply_free(&rep);
                return -1;
            }
        }
        (void)snprintf(c->session, sizeof c->session, "%s", rep.session);
    }
    mw_reply_free(&rep);
    if (mcp_send(c, "notifications/initialized", NULL, NULL, 1, &id, &rep, err, errcap) != 0) {
        return -1;
    }
    if (rep.status >= 400) {
        mw_say_refusal(c, &rep, err, errcap);
        mw_reply_free(&rep);
        return -1;
    }
    mw_reply_free(&rep);
    return 0;
}

/* server/discover under the current revision, falling back to the handshake. */
static int mw_discover(pic_mcp_conn *c, char *err, size_t errcap) {
    mcp_reply rep;
    long long id;
    (void)snprintf(c->era, sizeof c->era, "%s", PIC_MCP_CURRENT);
    c->cached = 0;
    if (mcp_send(c, "server/discover", NULL, NULL, 0, &id, &rep, err, errcap) != 0) {
        return -1;
    }
    if (rep.msg && mw_error_code(c, &rep) == 0) {
        free(c->instructions);
        c->instructions = mw_text(c->db, "SELECT json_extract(?1, '$.result.instructions')", rep.msg, NULL);
        free(c->capabilities);
        c->capabilities =
            mw_text(c->db, "SELECT coalesce(json(json_extract(?1, '$.result.capabilities')), '{}')", rep.msg, NULL);
        mw_reply_free(&rep);
        return 0;
    }
    if (mw_speaks_older(c, &rep)) {
        mw_reply_free(&rep);
        return mw_handshake(c, err, errcap);
    }
    mw_say_refusal(c, &rep, err, errcap);
    mw_reply_free(&rep);
    return -1;
}

pic_mcp_conn *pic_mcp_open(const pic_mcp_target *t, char *err, size_t errcap) {
    pic_mcp_conn *c = calloc(1, sizeof *c);
    char nerr[256];
    int rc;
    if (!c) {
        (void)snprintf(err, errcap, "out of memory");
        return NULL;
    }
    c->t = t;
    c->next_id = 1;
    if (sqlite3_open(":memory:", &c->db) != SQLITE_OK) {
        (void)snprintf(err, errcap, "out of memory");
        pic_mcp_close(c);
        return NULL;
    }
    if (t->url) {
        if (!(c->net = pic_net_new(nerr, sizeof nerr))) {
            (void)snprintf(err, errcap, "%s", nerr);
            pic_mcp_close(c);
            return NULL;
        }
    } else if (!mcp_pipes) {
        (void)snprintf(err, errcap, "%s is a stdio server, and pic cannot start stdio servers in this build", t->name);
        pic_mcp_close(c);
        return NULL;
    } else if (!(c->pipe = mcp_pipes->start(t, err, errcap))) {
        pic_mcp_close(c);
        return NULL;
    }
    if (mw_is_current(t->era)) {
        (void)snprintf(c->era, sizeof c->era, "%s", PIC_MCP_CURRENT);
        c->cached = 1;
        return c;
    }
    rc = t->era && t->era[0] ? mw_handshake(c, err, errcap) : -1;
    if (rc != 0) {
        rc = mw_discover(c, err, errcap);
    }
    if (rc != 0) {
        pic_mcp_close(c);
        return NULL;
    }
    return c;
}

char *pic_mcp_ask(pic_mcp_conn *c, const char *method, const char *params, const char *name, int *answered, char *err,
                  size_t errcap) {
    mcp_reply rep;
    long long id;
    char *result = NULL;
    int again = 1;
    if (answered) {
        *answered = 0;
    }
    for (;;) {
        if (mcp_send(c, method, params, name, 0, &id, &rep, err, errcap) != 0) {
            return NULL;
        }
        if (again && !rep.msg && mw_is_current(c->era) && c->cached && mw_speaks_older(c, &rep)) {
            /* the server no longer speaks the revision it spoke: refused unread, so ask again */
            mw_reply_free(&rep);
            again = 0;
            if (mw_discover(c, err, errcap) != 0) {
                return NULL;
            }
            continue;
        }
        if (again && !rep.msg && !mw_is_current(c->era) && c->session[0] && rep.status == 404) {
            mw_reply_free(&rep); /* the session expired */
            again = 0;
            if (mw_handshake(c, err, errcap) != 0) {
                return NULL;
            }
            continue;
        }
        break;
    }
    if (answered) {
        *answered = rep.status != 0;
    }
    if (rep.msg && mw_error_code(c, &rep) == 0) {
        result = mw_text(c->db, "SELECT json_extract(?1, '$.result')", rep.msg, NULL);
        if (result && mw_int(c->db, "SELECT coalesce(json_extract(?1, '$.resultType') = 'input_required', 0)", result, 0)) {
            free(result);
            result = NULL;
            (void)snprintf(err, errcap, "%s asked for input from the user, which pic does not support yet", c->t->name);
        }
    } else {
        mw_say_refusal(c, &rep, err, errcap);
    }
    mw_reply_free(&rep);
    return result;
}

/* Every KEY entry of METHOD's pages that WHERE (SQL over value) keeps. */
static char *mw_list(pic_mcp_conn *c, const char *method, const char *key, const char *where, char *err, size_t errcap) {
    char *all = strdup("[]"), *cursor = NULL, sql[512], has[128];
    (void)snprintf(sql, sizeof sql,
                   "SELECT json_group_array(json(v)) FROM (SELECT 0 p, key k, value v FROM json_each(?1)"
                   " UNION ALL SELECT 1, key, value FROM json_each(?2, '$.%s') WHERE %s ORDER BY p, k)",
                   key, where);
    (void)snprintf(has, sizeof has, "SELECT json_type(?1, '$.%s') = 'array'", key);
    for (int page = 0; all && page < MCP_LIST_PAGES; page++) {
        char *params = cursor ? mw_text(c->db, "SELECT json_object('cursor', ?1)", cursor, NULL) : NULL;
        char *res = pic_mcp_ask(c, method, params, NULL, NULL, err, errcap), *more;
        free(params);
        free(cursor);
        cursor = NULL;
        if (!res) {
            free(all);
            return NULL;
        }
        if (mw_int(c->db, has, res, 0) != 1) {
            (void)snprintf(err, errcap, "%s answered %s without a list of %s", c->t->name, method, key);
            free(res);
            free(all);
            return NULL;
        }
        more = mw_text(c->db, sql, all, res);
        cursor = mw_text(c->db, "SELECT json_extract(?1, '$.nextCursor') WHERE json_type(?1, '$.nextCursor') = 'text'"
                               " AND json_extract(?1, '$.nextCursor') <> ''",
                        res, NULL);
        free(res);
        free(all);
        all = more;
        if (!cursor) {
            return all;
        }
    }
    free(cursor);
    if (all) {
        (void)snprintf(err, errcap, "%s's %s did not end after %d pages", c->t->name, method, MCP_LIST_PAGES);
    } else {
        (void)snprintf(err, errcap, "out of memory");
    }
    free(all);
    return NULL;
}

char *pic_mcp_list_tools(pic_mcp_conn *c, char *err, size_t errcap) {
    return mw_list(c, "tools/list", "tools",
                   "json_type(value, '$.name') = 'text' AND json_type(value, '$.inputSchema') = 'object'", err, errcap);
}

char *pic_mcp_list_prompts(pic_mcp_conn *c, char *err, size_t errcap) {
    return mw_list(c, "prompts/list", "prompts", "json_type(value, '$.name') = 'text'", err, errcap);
}

int pic_mcp_changed(pic_mcp_conn *c) {
    int bits = c->changed;
    c->changed = 0;
    return bits;
}

const char *pic_mcp_era(const pic_mcp_conn *c) { return c->era; }
const char *pic_mcp_instructions(const pic_mcp_conn *c) { return c->instructions; }
const char *pic_mcp_capabilities(const pic_mcp_conn *c) { return c->capabilities; }

void pic_mcp_close(pic_mcp_conn *c) {
    if (!c) {
        return;
    }
    if (c->net && c->session[0] && !mw_is_current(c->era)) {
        char sess[300], version[64], err[160];
        const char **h = calloc(c->t->nheaders + 3, sizeof *h);
        pic_http_resp r;
        size_t nh = 0;
        if (h) {
            (void)snprintf(sess, sizeof sess, "Mcp-Session-Id: %s", c->session);
            (void)snprintf(version, sizeof version, "MCP-Protocol-Version: %s", c->era);
            h[nh++] = sess;
            h[nh++] = version;
            for (size_t i = 0; i < c->t->nheaders; i++) {
                h[nh++] = c->t->headers[i];
            }
            pic_http_resp_init(&r, NULL, NULL);
            (void)pic_http_request(c->net, "DELETE", c->t->url, h, nh, NULL, 0, &r, 2, 2, err, sizeof err);
            free(h);
        }
    }
    if (c->pipe) {
        mcp_pipes->stop(c->pipe);
    }
    pic_net_free(c->net);
    sqlite3_close(c->db);
    free(c->instructions);
    free(c->capabilities);
    free(c);
}