Files
splinter/plugins/mcp/mcp.c
T
Konrad be947d61d8 splinter: resume, and an MCP client
--resume loads the newest session in the directory into the conversation and
shows it. The first version opened a fresh id beside the old one and resumed
nothing while claiming to; it now picks the newest sess-*.jsonl before the id is
generated. Verified: a session that was told 'die Zahl ist 4711' and restarted
with --resume answered '4711' when asked.

plugins/mcp speaks MCP over stdio: handshake, tools/list, and each server tool
registered under its published inputSchema - not an empty object, because a tool
whose parameters the model cannot see gets called with nothing.

Two bugs the tests would not have caught without a real server:
 * the reply id was matched with strstr(), and servers that write "id": 1 lost
   the match - the client waited for a reply it already had;
 * tool descriptions pointed into the parsed reply and dangled once it was
   freed, so the request carried garbage bytes and the endpoint answered 500.

Also SPLINTER_DUMP_REQUEST=<path> now keeps the request body; finding that
garbage meant seeing what was actually sent.
2026-11-08 09:49:12 +00:00

439 lines
10 KiB
C

/*
* splinter -- MCP client plugin.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* An MCP server holds tools; this makes them the harness's tools.
*
* Configure one server per plugin instance:
*
* SPLINTER_MCP_CMD="npx -y @modelcontextprotocol/server-filesystem /home"
*
* On load it speaks the handshake, asks for the tool list, and registers every
* tool it finds with the schema the server published - not with an empty object,
* because a tool whose parameters the model cannot see gets called with nothing
* (that bug cost a day once already).
*
* Each call is a tools/call round trip on the same pipe. The server's text
* content is the observation; anything else is reported as it came, so a failure
* looks like a failure and not like an empty answer.
*/
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "mcp.h"
#define RPC_TIMEOUT_MS 20000
struct server {
pid_t pid;
FILE *to; /* our writes become the server's stdin */
FILE *from;
int next_id;
int dead;
};
static struct server srv;
static struct sp_host *host;
static int ntools;
/*
* Slice the JSON object that follows "inputSchema" out of the raw line.
*
* libmcp parses but does not print, and a tool schema has to be handed back to
* the model exactly as the server wrote it. Brace matching that respects
* strings and escapes is small and has no dependency.
*/
static const char *
slice_object(const char *at, size_t *lenp)
{
const char *start;
int depth = 0, in_str = 0, esc = 0;
start = strchr(at, '{');
if (start == NULL)
return NULL;
for (at = start; *at != '\0'; at++) {
if (in_str) {
if (esc)
esc = 0;
else if (*at == '\\')
esc = 1;
else if (*at == '"')
in_str = 0;
continue;
}
if (*at == '"')
in_str = 1;
else if (*at == '{')
depth++;
else if (*at == '}') {
depth--;
if (depth == 0) {
*lenp = (size_t)(at - start) + 1;
return start;
}
}
}
return NULL;
}
/* One JSON-RPC round trip on the pipe. Result is the raw reply line. */
static char *
rpc(const char *method, const char *params, struct sp_buf *err)
{
struct pollfd pfd;
char line[16384];
int id = ++srv.next_id;
if (srv.dead)
return NULL;
if (params != NULL)
fprintf(srv.to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\","
"\"params\":%s}\n", id, method, params);
else
fprintf(srv.to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\"}\n",
id, method);
fflush(srv.to);
for (;;) {
pfd.fd = fileno(srv.from);
pfd.events = POLLIN;
if (poll(&pfd, 1, RPC_TIMEOUT_MS) <= 0) {
sp_buf_printf(err, "mcp: no answer to %s", method);
return NULL;
}
if (fgets(line, sizeof(line), srv.from) == NULL) {
srv.dead = 1;
sp_buf_printf(err, "mcp: server closed the pipe during %s",
method);
return NULL;
}
{
/*
* Match the id by parsing it, not by looking for a substring:
* servers differ in whitespace ("id": 1 vs "id":1), and a raw
* strstr() then never matches - the client waits for a reply
* it already has.
*/
mcp_json *v = mcp_parse(line);
int rid = v != NULL ?
mcp_arg_int(v, "id", -1) : -1;
if (v != NULL)
mcp_json_free(v);
if (rid != id)
continue; /* notification or another reply */
}
if (strstr(line, "\"error\"") != NULL) {
struct sp_buf msg;
if (sp_buf_init(&msg) == 0) {
mcp_json *v = mcp_parse(line);
if (v != NULL) {
const mcp_json *e = mcp_arg(v, "error");
if (e != NULL && mcp_arg_string(e,
"message") != NULL)
sp_buf_printf(&msg, "%s",
mcp_arg_string(e, "message"));
mcp_json_free(v);
}
sp_buf_printf(err, "mcp: %s failed: %s", method,
msg.p != NULL ? msg.p : line);
sp_buf_free(&msg);
} else
sp_buf_printf(err, "mcp: %s failed", method);
return NULL;
}
return strdup(line);
}
}
/* Start the server and keep both pipes. */
static int
spawn(struct sp_buf *err)
{
int to[2], from[2];
pid_t child;
const char *cmd = getenv("SPLINTER_MCP_CMD");
if (cmd == NULL || *cmd == '\0') {
sp_buf_puts(err, "mcp: SPLINTER_MCP_CMD is not set");
return -1;
}
if (pipe(to) != 0 || pipe(from) != 0) {
sp_buf_printf(err, "mcp: pipe: %s", strerror(errno));
return -1;
}
child = fork();
if (child < 0) {
sp_buf_printf(err, "mcp: fork: %s", strerror(errno));
return -1;
}
if (child == 0) {
(void)dup2(to[0], STDIN_FILENO);
(void)dup2(from[1], STDOUT_FILENO);
close(to[0]);
close(to[1]);
close(from[0]);
close(from[1]);
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
_exit(127);
}
close(to[0]);
close(from[1]);
srv.pid = child;
srv.to = fdopen(to[1], "w");
srv.from = fdopen(from[0], "r");
if (srv.to == NULL || srv.from == NULL) {
sp_buf_puts(err, "mcp: fdopen failed");
return -1;
}
return 0;
}
/* ---- tool call ---- */
static int
call_tool(const char *args, struct sp_buf *out, void *ctx)
{
const char *tool = ctx;
struct sp_buf params, err;
char *reply;
mcp_json *v;
if (sp_buf_init(&params) != 0 || sp_buf_init(&err) != 0)
return -1;
sp_buf_printf(&params, "{\"name\":\"%s\",\"arguments\":%s}", tool,
args != NULL && args[0] == '{' ? args : "{}");
reply = rpc("tools/call", params.p, &err);
sp_buf_free(&params);
if (reply == NULL) {
sp_buf_printf(out, "error: %s", err.p != NULL ? err.p : "mcp call");
sp_buf_free(&err);
return 0;
}
sp_buf_free(&err);
v = mcp_parse(reply);
if (v == NULL) {
sp_buf_printf(out, "%s", reply);
free(reply);
return 0;
}
{
const mcp_json *res = mcp_arg(v, "result");
const mcp_json *content = res != NULL ? mcp_arg(res, "content") : NULL;
const mcp_json *first = content != NULL ? mcp_array_at(content, 0) : NULL;
const char *text = first != NULL ?
mcp_arg_string(first, "text") : NULL;
if (text != NULL)
sp_buf_printf(out, "%s", text);
else
sp_buf_printf(out, "%s", reply);
}
mcp_json_free(v);
free(reply);
return 0;
}
/* ---- registration ---- */
static int
register_tools(struct sp_buf *err)
{
char *reply;
const char *schema_at;
mcp_json*v;
const mcp_json *result, *tools;
size_t i;
int added = 0;
reply = rpc("tools/list", "{}", err);
if (reply == NULL)
return -1;
v = mcp_parse(reply);
if (v == NULL) {
free(reply);
return -1;
}
result = mcp_arg(v, "result");
tools = result != NULL ? mcp_arg(result, "tools") : NULL;
if (tools == NULL) {
mcp_json_free(v);
free(reply);
return 0;
}
/* the schemas, in array order, from the raw text */
schema_at = reply;
for (i = 0; ; i++) {
const mcp_json *t = mcp_array_at(tools, i);
const char *name, *desc;
const char *slice;
size_t len = 0;
char *toolname;
struct sp_tool tool;
if (t == NULL)
break;
name = mcp_arg_string(t, "name");
desc = mcp_arg_string(t, "description");
if (name == NULL)
continue;
slice = strstr(schema_at, "inputSchema");
if (slice != NULL)
slice = slice_object(slice, &len);
if (slice != NULL)
schema_at = slice;
toolname = malloc(strlen(name) + 8);
if (toolname == NULL)
continue;
snprintf(toolname, strlen(name) + 8, "mcp_%s", name);
memset(&tool, 0, sizeof(tool));
tool.name = toolname;
/*
* The description points into the parsed reply, which is freed below;
* the registry copies the struct, not the string. Keeping the pointer
* put garbage bytes into the request - the endpoint answered 500 and
* the model never saw a usable tool.
*/
tool.description = strdup(desc != NULL ? desc : "MCP tool");
if (tool.description == NULL)
continue;
if (slice != NULL) {
char *copy = malloc(len + 1);
if (copy != NULL) {
memcpy(copy, slice, len);
copy[len] = '\0';
tool.params = copy;
}
}
if (tool.params == NULL)
tool.params = "{\"type\":\"object\",\"properties\":{}}";
/* an MCP server can do anything; the class is the honest default */
tool.auth = SP_AUTH_MUTATE;
tool.run = call_tool;
tool.ctx = (void *)toolname;
if (sp_host_add_tool(host, &tool) == 0)
added++;
}
mcp_json_free(v);
free(reply);
return added;
}
/* ---- plugin entry points ---- */
/* The sidebar says how many tools the server offered; a silent zero is a bug. */
static int
mcp_widget_tick(struct sp_host *h, const char *name, void *ctx)
{
char line[96];
(void)ctx;
if (srv.dead)
snprintf(line, sizeof(line), "%d tools, server gone", ntools);
else
snprintf(line, sizeof(line), "%d tools", ntools);
(void)sp_host_widget_text(h, name, line);
return 0;
}
static const struct sp_widget widget = {
"mcp",
mcp_widget_tick,
NULL,
NULL,
2000
};
static int
mcp_init(struct sp_host *h)
{
struct sp_buf err, p;
char *reply;
int n;
host = h;
if (sp_buf_init(&err) != 0)
return -1;
if (spawn(&err) != 0) {
(void)sp_host_note(h, err.p != NULL ? err.p : "mcp: cannot start");
sp_buf_free(&err);
return -1;
}
if (sp_buf_init(&p) != 0) {
sp_buf_free(&err);
return -1;
}
sp_buf_printf(&p, "{\"protocolVersion\":\"2024-11-05\","
"\"capabilities\":{},\"clientInfo\":{\"name\":\"splinter\","
"\"version\":\"" SP_VERSION "\"}}");
reply = rpc("initialize", p.p, &err);
sp_buf_free(&p);
if (reply == NULL) {
(void)sp_host_note(h, err.p != NULL ? err.p : "mcp: handshake");
sp_buf_free(&err);
return -1;
}
free(reply);
/* the handshake is not finished until the server is told so */
fprintf(srv.to, "{\"jsonrpc\":\"2.0\",\"method\":"
"\"notifications/initialized\"}\n");
fflush(srv.to);
n = register_tools(&err);
if (n <= 0) {
(void)sp_host_note(h, err.p != NULL ? err.p :
"mcp: the server offered no tools");
sp_buf_free(&err);
return -1;
}
ntools = n;
(void)sp_host_add_widget(h, &widget);
sp_buf_free(&err);
return 0;
}
static void
mcp_shutdown(struct sp_host *h)
{
(void)h;
if (srv.dead || srv.pid <= 0)
return;
(void)kill(srv.pid, SIGTERM);
(void)waitpid(srv.pid, NULL, 0);
srv.dead = 1;
}
static const struct sp_plugin plugin = {
SP_PLUGIN_ABI,
"mcp",
"1.0",
mcp_init,
NULL,
mcp_shutdown
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &plugin;
}