Skip to content
pi-c Artifact [d321805d40]
Login

Artifact [d321805d40]

Artifact d321805d40c89cf74d46257e8b73b2520765155a47803704b9f664ebd14bf691:


/* pic mcp serve (mcp_serve.h): pic's own tools offered to an MCP client over stdio, one
 * JSON-RPC message a line. It speaks the 2025 handshake (initialize) and the current revision
 * (server/discover, every request with its own _meta), answering each in the revision it was
 * asked in. A call runs the tool as a request would, but nothing is journaled and no hook runs:
 * as with claude mcp serve, the client is the one that asks its person first. stdout carries the
 * protocol only; anything else that writes to it goes to stderr. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "help.h"
#include "image.h"
#include "mcp_serve.h"
#include "mcp_wire.h"
#include "sqlite3.h"
#include "toolreg.h"

#define MSV_TOOLS_MAX 64

/* The 2025 revisions a client may ask for in initialize; another gets the newest. */
static const char *const msv_older[] = {"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"};

/* The first column of SQL's first row as text (malloc'd), over text arguments A and B, or NULL. */
static char *msv_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;
}

/* Whether NAME is one of the tools served: in play, built in, declared (not deferred), and not
 * one of those that belong to a conversation's journal. */
static int msv_served(const char *name) {
    const pic_tool_def *d = pic_tool_named(name);
    return d && d->builtin && pic_toolset_on(name) && !pic_tool_deferred(d) && strcmp(name, "send_message") != 0 &&
           strcmp(name, "wake") != 0;
}

/* tools/list's tools: a JSON array (malloc'd). */
static char *msv_tools(sqlite3 *db) {
    const char *names[MSV_TOOLS_MAX];
    size_t n = pic_toolset_names(names, MSV_TOOLS_MAX);
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *res, *out;
    int first = 1;
    sqlite3_str_appendall(t, "[");
    for (size_t i = 0; i < n && i < MSV_TOOLS_MAX; i++) {
        const pic_tool_def *d = pic_tool_named(names[i]);
        char *one;
        if (!msv_served(names[i])) {
            continue;
        }
        one = msv_text(db,
                       "SELECT json_object('name', json_extract(?1, '$.name'), 'description',"
                       " coalesce(json_extract(?1, '$.description'), ''), 'inputSchema',"
                       " json(coalesce(json_extract(?1, '$.input_schema'), '{\"type\":\"object\"}')),"
                       " 'annotations', json_object('readOnlyHint', json(?2)))",
                       d->schema, d->read_only ? "true" : "false");
        if (one) {
            sqlite3_str_appendf(t, "%s%s", first ? "" : ",", one);
            first = 0;
        }
        free(one);
    }
    sqlite3_str_appendall(t, "]");
    res = sqlite3_str_finish(t);
    out = strdup(res ? res : "[]");
    sqlite3_free(res);
    return out;
}

static int msv_started(void *ctx, const char *plan, size_t plan_len) {
    (void)ctx;
    (void)plan;
    (void)plan_len;
    return 0;
}

/* The arguments a tool reads from INPUT, as a request's call has them (loop.c's
 * parse_pending_input and load_edits): strings kept in OWN (freed by msv_args_free). */
typedef struct {
    char *s[5]; /* path, content, command, pattern, glob */
    char **old_text, **new_text;
    size_t nedits;
} msv_own;

static void msv_args_free(msv_own *o) {
    for (int i = 0; i < 5; i++) {
        free(o->s[i]);
    }
    for (size_t i = 0; i < o->nedits; i++) {
        free(o->old_text[i]);
        free(o->new_text[i]);
    }
    free(o->old_text);
    free(o->new_text);
}

static char *msv_col(sqlite3_stmt *q, int i) {
    return sqlite3_column_type(q, i) == SQLITE_NULL ? NULL : strdup((const char *)sqlite3_column_text(q, i));
}

static void msv_args(sqlite3 *db, const char *tool, const char *input, pic_tool_args *a, msv_own *o) {
    sqlite3_stmt *q = NULL;
    memset(a, 0, sizeof *a);
    memset(o, 0, sizeof *o);
    a->bad_input = "Tool input is not a JSON object.";
    if (sqlite3_prepare_v2(db,
                           "SELECT CASE json_type(?1,'$.path') WHEN 'text' THEN json_extract(?1,'$.path') END,"
                           " CASE json_type(?1,'$.content') WHEN 'text' THEN json_extract(?1,'$.content') END,"
                           " CASE json_type(?1,'$.command') WHEN 'text' THEN json_extract(?1,'$.command') END,"
                           " CASE json_type(?1,'$.pattern') WHEN 'text' THEN json_extract(?1,'$.pattern') END,"
                           " CASE json_type(?1,'$.glob') WHEN 'text' THEN json_extract(?1,'$.glob') END,"
                           " json_type(?1,'$.offset') IN ('integer','real'), CAST(json_extract(?1,'$.offset') AS INTEGER),"
                           " json_type(?1,'$.limit') IN ('integer','real'), CAST(json_extract(?1,'$.limit') AS INTEGER),"
                           " json_type(?1,'$.timeout') IN ('integer','real'), CAST(json_extract(?1,'$.timeout') AS INTEGER),"
                           " json_type(?1,'$.ignoreCase')='true', json_type(?1,'$.literal')='true',"
                           " json_type(?1,'$.context') IN ('integer','real'), CAST(json_extract(?1,'$.context') AS INTEGER)"
                           " WHERE json_valid(?1) AND json_type(?1)='object'",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, input, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            for (int i = 0; i < 5; i++) {
                o->s[i] = msv_col(q, i);
            }
            a->has_offset = sqlite3_column_int(q, 5);
            a->offset = (long)sqlite3_column_int64(q, 6);
            a->has_limit = sqlite3_column_int(q, 7);
            a->limit = (long)sqlite3_column_int64(q, 8);
            a->has_timeout = sqlite3_column_int(q, 9);
            a->timeout = (long)sqlite3_column_int64(q, 10);
            a->ignore_case = sqlite3_column_int(q, 11);
            a->literal = sqlite3_column_int(q, 12);
            a->has_context = sqlite3_column_int(q, 13);
            a->context = (long)sqlite3_column_int64(q, 14);
            a->bad_input = NULL;
        }
    }
    sqlite3_finalize(q);
    q = NULL;
    if (!a->bad_input && strcmp(tool, "edit") == 0 &&
        sqlite3_prepare_v2(db,
                           "WITH e(v) AS (SELECT CASE json_type(?1,'$.edits')"
                           "  WHEN 'array' THEN json_extract(?1,'$.edits')"
                           "  WHEN 'object' THEN json_array(json_extract(?1,'$.edits'))"
                           "  WHEN 'text' THEN CASE WHEN json_valid(json_extract(?1,'$.edits'))"
                           "    AND json_type(json_extract(?1,'$.edits'))='array' THEN json_extract(?1,'$.edits') END END)"
                           " SELECT json_type(value,'$.oldText')='text' AND json_type(value,'$.newText')='text',"
                           "  json_extract(value,'$.oldText'), json_extract(value,'$.newText') FROM e, json_each(e.v)"
                           " UNION ALL SELECT json_type(?1,'$.newText')='text', json_extract(?1,'$.oldText'),"
                           "  json_extract(?1,'$.newText') WHERE json_type(?1,'$.oldText')='text'",
                           -1, &q, NULL) == SQLITE_OK) {
        size_t cap = 0;
        sqlite3_bind_text(q, 1, input, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            if (!sqlite3_column_int(q, 0)) {
                a->bad_input = "Edit tool input is invalid. Each edit needs string oldText and newText.";
                continue;
            }
            if (o->nedits == cap) {
                size_t ncap = cap ? cap * 2 : 4;
                char **ot = realloc(o->old_text, ncap * sizeof *ot), **nt;
                if (!ot) {
                    break;
                }
                o->old_text = ot;
                if (!(nt = realloc(o->new_text, ncap * sizeof *nt))) {
                    break;
                }
                o->new_text = nt;
                cap = ncap;
            }
            o->old_text[o->nedits] = msv_col(q, 1);
            o->new_text[o->nedits] = msv_col(q, 2);
            o->nedits++;
        }
    }
    sqlite3_finalize(q);
    a->path = o->s[0];
    a->content = o->s[1];
    a->command = o->s[2];
    a->pattern = o->s[3];
    a->glob = o->s[4];
    a->nedits = o->nedits;
    a->old_text = (const char *const *)o->old_text;
    a->new_text = (const char *const *)o->new_text;
}

/* tools/call: the result object's members (malloc'd), {content, isError}. */
static char *msv_call(sqlite3 *db, const char *workspace, int exec_seconds, const char *name, const char *input) {
    struct pic_tool_image image;
    pic_tool_hooks h;
    pic_tool_args a;
    msv_own own;
    char *text = NULL, *out, *res, *b64 = NULL;
    int is_error = 1;
    sqlite3_str *t;
    memset(&image, 0, sizeof image);
    memset(&h, 0, sizeof h);
    if (!name || !msv_served(name)) {
        text = msv_text(db, "SELECT 'Tool ' || coalesce(?1, '') || ' not found'", name, NULL);
    } else {
        msv_args(db, name, input, &a, &own);
        h.exec_seconds = exec_seconds;
        h.started = msv_started;
        h.input = input;
        h.image = &image;
        is_error = 0;
        text = pic_toolset_run(workspace, name, &a, &h, &is_error);
        msv_args_free(&own);
        if (!text) {
            text = strdup("the tool did not run");
            is_error = 1;
        }
    }
    if (image.data && image.len && (b64 = malloc(4 * ((image.len + 2) / 3) + 1))) {
        b64[pic_base64_encode(image.data, image.len, b64)] = '\0';
    }
    free(image.data);
    t = sqlite3_str_new(NULL);
    {
        char *content = msv_text(db, "SELECT json_array(json_object('type', 'text', 'text', ?1))", text ? text : "", NULL);
        if (content && b64) { /* the read tool's image, beside its text */
            char *img = msv_text(db, "SELECT json_object('type', 'image', 'data', ?1, 'mimeType', ?2)", b64,
                                 image.mime ? image.mime : "image/png"),
                 *both = img ? msv_text(db, "SELECT json_insert(?1, '$[#]', json(?2))", content, img) : NULL;
            if (both) {
                free(content);
                content = both;
            }
            free(img);
        }
        sqlite3_str_appendf(t, "\"content\":%s", content ? content : "[]");
        free(content);
    }
    sqlite3_str_appendf(t, ",\"isError\":%s", is_error ? "true" : "false");
    res = sqlite3_str_finish(t);
    out = strdup(res ? res : "\"content\":[],\"isError\":true");
    sqlite3_free(res);
    free(text);
    free(b64);
    return out;
}

int pic_mcp_serve(const char *workspace, int exec_seconds) {
    sqlite3 *db = NULL;
    FILE *out;
    char *line = NULL, version[32];
    size_t cap = 0;
    ssize_t n;
    int fd = dup(STDOUT_FILENO);
    if (fd < 0 || dup2(STDERR_FILENO, STDOUT_FILENO) < 0 || !(out = fdopen(fd, "w")) ||
        sqlite3_open(":memory:", &db) != SQLITE_OK) {
        fputs("pic: mcp serve cannot start\n", stderr);
        sqlite3_close(db);
        return 1;
    }
    pic_version(version, sizeof version);
    while ((n = getline(&line, &cap, stdin)) > 0) {
        char *id, *method, *params, *body = NULL, *res;
        sqlite3_str *t;
        int modern;
        while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) {
            line[--n] = '\0';
        }
        if (n == 0) {
            continue;
        }
        if (!(method = msv_text(db, "SELECT coalesce(json_extract(?1, '$.method'), '') WHERE json_valid(?1)"
                                    " AND json_type(?1) = 'object'",
                                line, NULL))) {
            fputs("{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32700,\"message\":\"Parse error\"}}\n", out);
            fflush(out);
            continue;
        }
        id = msv_text(db,
                      "SELECT json_quote(json_extract(?1, '$.id')) WHERE json_type(?1, '$.id') IN ('integer', 'text', 'real')",
                      line, NULL);
        if (!id) { /* a notification (or a response): nothing to answer */
            free(method);
            continue;
        }
        params = msv_text(db, "SELECT json(coalesce(json_extract(?1, '$.params'), '{}'))", line, NULL);
        { /* the current revision: every request says so in its _meta */
            char *m = params ? msv_text(db, "SELECT 1 WHERE json_extract(?1, '$._meta.\"io.modelcontextprotocol/protocolVersion\"')"
                                            " = ?2",
                                        params, PIC_MCP_CURRENT)
                             : NULL;
            modern = m != NULL;
            free(m);
        }
        t = sqlite3_str_new(NULL);
        if (strcmp(method, "initialize") == 0) {
            char *asked = msv_text(db, "SELECT json_extract(?1, '$.protocolVersion')", params, NULL);
            const char *era = msv_older[0];
            for (size_t i = 0; asked && i < sizeof msv_older / sizeof msv_older[0]; i++) {
                era = strcmp(asked, msv_older[i]) == 0 ? msv_older[i] : era;
            }
            sqlite3_str_appendf(t, "\"protocolVersion\":\"%s\",\"capabilities\":{\"tools\":{}},"
                                   "\"serverInfo\":{\"name\":\"pic\",\"version\":\"%s\"}",
                                era, version);
            free(asked);
        } else if (strcmp(method, "server/discover") == 0) {
            sqlite3_str_appendf(t, "\"supportedVersions\":[\"%s\",\"%s\"],\"capabilities\":{\"tools\":{}},"
                                   "\"_meta\":{\"io.modelcontextprotocol/serverInfo\":{\"name\":\"pic\",\"version\":\"%s\"}}",
                                PIC_MCP_CURRENT, msv_older[0], version);
            modern = 1;
        } else if (strcmp(method, "ping") == 0) {
            sqlite3_str_appendall(t, "");
        } else if (strcmp(method, "tools/list") == 0) {
            char *tools = msv_tools(db);
            sqlite3_str_appendf(t, "\"tools\":%s", tools ? tools : "[]");
            free(tools);
        } else if (strcmp(method, "tools/call") == 0) {
            char *name = msv_text(db, "SELECT json_extract(?1, '$.name') WHERE json_type(?1, '$.name') = 'text'", params, NULL),
                 *input = msv_text(db, "SELECT json(coalesce(json_extract(?1, '$.arguments'), '{}'))", params, NULL),
                 *got = msv_call(db, workspace, exec_seconds, name, input ? input : "{}");
            sqlite3_str_appendall(t, got);
            free(got);
            free(name);
            free(input);
        } else {
            body = msv_text(db,
                            "SELECT json_object('jsonrpc', '2.0', 'id', json(?1), 'error', json_object('code', -32601,"
                            " 'message', 'Method not found: ' || ?2))",
                            id, method);
        }
        res = sqlite3_str_finish(t);
        if (body) {
            fprintf(out, "%s\n", body);
        } else {
            fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s%s%s}}\n", id,
                    modern ? "\"resultType\":\"complete\"" : "", modern && res && *res ? "," : "", res ? res : "");
        }
        fflush(out);
        sqlite3_free(res);
        free(body);
        free(params);
        free(method);
        free(id);
    }
    free(line);
    fclose(out);
    sqlite3_close(db);
    return 0;
}