Each change has a test that fails against the code before it.
Also note: 8900d7f ("telegram: refuse to start without a token") swept in
work of this round that its message does not describe - an OLLAMA_KEY no longer
overwrites the key of the operator's last exit (config.c), parallel delegates
are killed and reaped after a timeout (delegate.c), lcm/cps never leave a tool
result without its call, cps keeps working past 256 messages, Telegram ids are
parsed as 64 bit, and 'run' also hides SPLINTER_OLLAMA_KEY_* and
SPLINTER_MCP_TOKEN.
MCP client (plugins/mcp)
- fgets into char[16384] split every longer reply into unparseable pieces; a
big tools/list or file read never arrived. A reply sharing one write with a
notification sat in stdio's buffer, invisible to poll(). Lines are now
buffered on the fd (up to 16 MiB). An error is the top-level "error" member,
not the text "error" anywhere in the line. test_mcpclient.
kids
- Rules were matched against the raw JSON, so "run ls*" never matched. They
now see the command, path or url. A 'run' command that can chain, substitute
or redirect is never whitelisted. The glob is linear instead of exponential.
test_kids, which also covers the approval-command quoting and the domain
checks from the first round.
Plugin life (src/plugin.c, ABI 2)
- An init() that failed kept what it had registered (tools, gate, widget
threads); it is now rolled back. shutdown() was never called; the host calls
it, newest plugin first, after the widget threads have stopped.
- A widget slot is filled before it is counted, and the count is read under the
lock, so tick threads never see a half-made slot.
- SP_PLUGIN_ABI is 2: struct sp_gate grew block_turn while the ABI stayed 1.
test_lifecycle, with tests/plugin_lifecycle.so.
UI
- Ctrl-C and Ctrl-D cancel under the lock and wake a turn waiting for approval
(it waited forever); Ctrl-D cancelled nothing before the join.
- A steer the turn already took is not sent again as the next message.
- KEY_RESIZE re-cuts the windows; Ctrl-L repaints instead of sending the
half-typed line; key codes above 255 are not typed into the input.
- Markdown attributes went to stdscr while the text went to ui_hist: bold and
code never showed. They now build on the line's role colour.
Checked in tmux: UTF-8 input, resize to 70x20, Ctrl-L, Ctrl-D, bold.
Telegram
- Replies are split on UTF-8 boundaries; a cut umlaut made Telegram refuse the
chunk and the rest of the answer was lost.
Build
- Seven plugins linked with an undefined $(PLUGIN_LDFLAGS): no rpath, no LIBS.
All eleven now carry $ORIGIN/../..; objects depend on the interface headers.
Seen, not changed: sp_session_append fsyncs every line; under disk load an
answer appears up to 15 s late. Not a deadlock, and the same before this round.
make check: 26 test binaries, green, also under ASan/UBSan.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
488 lines
11 KiB
C
488 lines
11 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 */
|
|
int from; /* its stdout, read without stdio */
|
|
struct sp_buf in; /* bytes read but not yet a whole line */
|
|
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;
|
|
}
|
|
|
|
#define RPC_MAX_LINE (16u * 1024 * 1024)
|
|
|
|
/*
|
|
* The next line from the server, without its newline. 1 a line, 0 timeout,
|
|
* -1 the pipe is gone or the line is beyond RPC_MAX_LINE.
|
|
*
|
|
* fgets() into a char[16384] split every longer reply - a tools/list of a big
|
|
* server, a file read - into pieces that do not parse; the client then waited
|
|
* for an answer it had already received in parts. And poll() on the fd of a
|
|
* stdio stream does not see what stdio has already buffered: two messages in
|
|
* one write left the second one unseen until the timeout. So the bytes are
|
|
* buffered here, where poll() and the buffer agree.
|
|
*/
|
|
static int
|
|
read_line(struct sp_buf *line, int timeout_ms)
|
|
{
|
|
for (;;) {
|
|
char *nl = srv.in.p != NULL ?
|
|
memchr(srv.in.p, '\n', srv.in.len) : NULL;
|
|
char chunk[65536];
|
|
ssize_t got;
|
|
struct pollfd pfd;
|
|
|
|
if (nl != NULL) {
|
|
size_t n = (size_t)(nl - srv.in.p);
|
|
|
|
sp_buf_clear(line);
|
|
if (sp_buf_add(line, srv.in.p, n) != 0)
|
|
return -1;
|
|
memmove(srv.in.p, nl + 1, srv.in.len - n - 1);
|
|
srv.in.len -= n + 1;
|
|
srv.in.p[srv.in.len] = '\0';
|
|
return 1;
|
|
}
|
|
if (srv.in.len > RPC_MAX_LINE)
|
|
return -1;
|
|
pfd.fd = srv.from;
|
|
pfd.events = POLLIN;
|
|
if (poll(&pfd, 1, timeout_ms) <= 0)
|
|
return 0;
|
|
got = read(srv.from, chunk, sizeof(chunk));
|
|
if (got < 0 && errno == EINTR)
|
|
continue;
|
|
if (got <= 0)
|
|
return -1;
|
|
if (sp_buf_add(&srv.in, chunk, (size_t)got) != 0)
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
/* 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 sp_buf line;
|
|
int id = ++srv.next_id, rc;
|
|
|
|
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);
|
|
if (sp_buf_init(&line) != 0)
|
|
return NULL;
|
|
|
|
for (;;) {
|
|
mcp_json *v;
|
|
const mcp_json *e;
|
|
int rid;
|
|
char *res;
|
|
|
|
rc = read_line(&line, RPC_TIMEOUT_MS);
|
|
if (rc == 0) {
|
|
sp_buf_printf(err, "mcp: no answer to %s", method);
|
|
sp_buf_free(&line);
|
|
return NULL;
|
|
}
|
|
if (rc < 0) {
|
|
srv.dead = 1;
|
|
sp_buf_printf(err, "mcp: server closed the pipe (or sent "
|
|
"a line over 16 MiB) during %s", method);
|
|
sp_buf_free(&line);
|
|
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.
|
|
*/
|
|
v = mcp_parse(line.p);
|
|
rid = v != NULL ? mcp_arg_int(v, "id", -1) : -1;
|
|
if (rid != id) {
|
|
if (v != NULL)
|
|
mcp_json_free(v);
|
|
continue; /* notification or another reply */
|
|
}
|
|
/*
|
|
* An error is the top-level "error" member, not the text "error"
|
|
* anywhere in the line - a file that contains it is a result.
|
|
*/
|
|
e = mcp_arg(v, "error");
|
|
if (e != NULL) {
|
|
const char *m = mcp_arg_string(e, "message");
|
|
|
|
sp_buf_printf(err, "mcp: %s failed: %s", method,
|
|
m != NULL ? m : line.p);
|
|
mcp_json_free(v);
|
|
sp_buf_free(&line);
|
|
return NULL;
|
|
}
|
|
mcp_json_free(v);
|
|
res = line.p; /* the caller frees it */
|
|
return res;
|
|
}
|
|
}
|
|
|
|
/* 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 = from[0];
|
|
if (srv.to == NULL || sp_buf_init(&srv.in) != 0) {
|
|
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(¶ms) != 0 || sp_buf_init(&err) != 0)
|
|
return -1;
|
|
sp_buf_printf(¶ms, "{\"name\":\"%s\",\"arguments\":%s}", tool,
|
|
args != NULL && args[0] == '{' ? args : "{}");
|
|
reply = rpc("tools/call", params.p, &err);
|
|
sp_buf_free(¶ms);
|
|
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;
|
|
}
|