Files
lotherk 80f055711d races: five data races fixed, make check-tsan to keep them fixed
Found with ThreadSanitizer over the whole suite, not by reading:

- ack: sp_ack_dir() returned one static buffer. The waiter and the
  answerer (the gateway is both) sprintf'd into each other's path, so an
  approval request could be looked for in the wrong place. One buffer per
  thread now; test_ack asserts the two threads get different addresses.
- mcp: `stopping` was a plain volatile int with no happens-before, so a
  server thread could read 0 after shutdown killed its child and keep
  using buffers that teardown frees. Acquire/release accessors.
- foreign: fr.ready was set before the paths it guards were filled, so a
  second thread returned early and read empty paths; the flag and the host
  handle are now an atomic pair (publish) plus a mutex (the init itself).
- embed: catch_up() read c->path, c->offset and c->id outside the lock. A
  session switch mid-index published the old file's byte offset into the
  new session's index - everything below that offset was never searched
  again. A generation counter makes that run drop its batch, and the
  search path takes its snapshot under the same lock.

Proof, both directions:
- make check-tsan: 45/45 test binaries free of races (new target; the
  tree is rebuilt under TSan and back, like check-asan).
- test_embed's new gated test (a server that holds the batch until the
  session has been switched): without the generation check short.emb ends
  with 4 records, 1 of them leaked from the other session; with it, 1
  and 0. The test is deterministic, so it fails on a plain build too.
- test_ack: reverting to `static char root[]` fails
  "the two threads do not share one buffer".
- make check: all tests passed; make check-asan: 45/45 clean.
2026-11-23 08:30:29 +00:00

1356 lines
33 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.
*
* Two transports, because servers come in two shapes:
*
* mcp junction { url = http://192.168.1.148:8090/mcp
* header = "Authorization: Bearer ${JUNCTION_TOKEN}" }
* mcp files { cmd = "npx -y @modelcontextprotocol/server-filesystem /home" }
*
* `url` speaks the streamable-HTTP transport: one POST per JSON-RPC message,
* answered either with one JSON object or with an SSE stream of `data:` lines.
* `cmd` starts a program whose stdin/stdout carry the same messages. The old
* single-server environment variable still works and is one stdio server:
*
* 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 to the server the tool came from. With
* one server the tools are mcp_<name>; with several they are mcp_<server>_<name>,
* so two servers that both offer "search" stay apart. 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 <ctype.h>
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdint.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "config.h"
#include "curl.h"
#include "mcp.h"
#define RPC_TIMEOUT_MS 20000
#define HTTP_TIMEOUT_S "60"
#define RPC_MAX_LINE (16u * 1024u * 1024u)
#define MAX_SERVERS SP_CONFIG_MAX_MCP
struct server {
char id[32];
int http; /* 1: streamable HTTP, 0: stdio child */
char url[SP_CONFIG_MCP_URL];
char header[SP_CONFIG_MCP_HEADER];
char cmd[SP_CONFIG_MCP_CMD];
char session[160]; /* Mcp-Session-Id, echoed back */
pid_t pid;
volatile pid_t http_pid; /* the curl of a round trip in flight */
FILE *to; /* stdio: our writes become the server's stdin */
int from; /* stdio: its stdout, read without stdio */
struct sp_buf in; /* bytes read but not yet a whole line */
int next_id;
int dead;
int ntools;
volatile int up; /* handshake done and answering */
int registered; /* its tools are in the registry (once) */
pthread_mutex_t lock; /* one round trip at a time */
pthread_t th; /* the reconnect thread, joined on shutdown */
int th_started;
int th_done; /* set under done_mu right before it returns */
};
#define RETRY_S 10
/*
* Written by the main thread in mcp_shutdown, read by every server thread in
* its loop. `volatile` was not enough: it stops the compiler from caching the
* value but gives no ordering, so a server thread could read 0 after the
* shutdown had already killed its child and keep using buffers that teardown
* frees. TSan reported the race as a write in mcp_shutdown against a read in
* server_thread_body; the accessors below make it visible and ordered.
*/
static int stopping;
static int
is_stopping(void)
{
return __atomic_load_n(&stopping, __ATOMIC_ACQUIRE);
}
static void
set_stopping(int v)
{
__atomic_store_n(&stopping, v, __ATOMIC_RELEASE);
}
static struct server sv[MAX_SERVERS];
static size_t nsv;
static struct sp_host *host;
/*
* The server threads are joinable. Shutdown has to know they are gone before
* it frees the buffers they read into and before the host they register tools
* in disappears; without the join a thread could call sp_host_add_tool() into
* a freed host. Bounded, because a thread stuck in connect() must not hang the
* shutdown forever.
*/
static pthread_mutex_t done_mu = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t done_cv = PTHREAD_COND_INITIALIZER;
/* A registered tool knows which server it belongs to and what it is called there. */
struct toolref {
size_t srv;
char name[];
};
/*
* Print a parsed JSON value back as text.
*
* libmcp parses but does not print. A tool's schema has to be handed to the
* model; it is taken from the tool's own entry in the parsed tools array, so a
* tool without one (or a description that mentions "inputSchema") can never
* hand its neighbour's schema over. Key order is kept; numbers are printed as
* integers when they are integral.
*/
static int
json_print(struct sp_buf *b, const mcp_json *v)
{
size_t i;
switch (v->t) {
case MCP_NULL:
return sp_buf_puts(b, "null");
case MCP_BOOL:
return sp_buf_puts(b, v->b ? "true" : "false");
case MCP_NUM:
if (v->n == (double)(long long)v->n &&
v->n > -9007199254740992.0 && v->n < 9007199254740992.0)
return sp_buf_printf(b, "%lld", (long long)v->n);
return sp_buf_printf(b, "%.17g", v->n);
case MCP_STR: {
const unsigned char *p = (const unsigned char *)
(v->s != NULL ? v->s : "");
if (sp_buf_puts(b, "\"") != 0)
return -1;
for (; *p != '\0'; p++) {
int rc;
if (*p == '"' || *p == '\\')
rc = sp_buf_printf(b, "\\%c", *p);
else if (*p == '\n')
rc = sp_buf_puts(b, "\\n");
else if (*p == '\r')
rc = sp_buf_puts(b, "\\r");
else if (*p == '\t')
rc = sp_buf_puts(b, "\\t");
else if (*p < 0x20)
rc = sp_buf_printf(b, "\\u%04x", *p);
else
rc = sp_buf_add(b, (const char *)p, 1);
if (rc != 0)
return -1;
}
return sp_buf_puts(b, "\"");
}
case MCP_ARR:
if (sp_buf_puts(b, "[") != 0)
return -1;
for (i = 0; i < v->count; i++)
if ((i > 0 && sp_buf_puts(b, ",") != 0) ||
json_print(b, v->items[i]) != 0)
return -1;
return sp_buf_puts(b, "]");
case MCP_OBJ:
if (sp_buf_puts(b, "{") != 0)
return -1;
for (i = 0; i < v->count; i++) {
mcp_json key;
memset(&key, 0, sizeof(key));
key.t = MCP_STR;
key.s = v->keys[i];
if ((i > 0 && sp_buf_puts(b, ",") != 0) ||
json_print(b, &key) != 0 ||
sp_buf_puts(b, ":") != 0 ||
json_print(b, v->items[i]) != 0)
return -1;
}
return sp_buf_puts(b, "}");
}
return -1;
}
/* ---- stdio transport ---- */
/*
* One line from the child, or 1/0/-1.
*
* 0 means the timeout passed, -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 server *s, struct sp_buf *line, int timeout_ms)
{
for (;;) {
char *nl = s->in.p != NULL ?
memchr(s->in.p, '\n', s->in.len) : NULL;
char chunk[65536];
ssize_t got;
struct pollfd pfd;
if (nl != NULL) {
size_t n = (size_t)(nl - s->in.p);
sp_buf_clear(line);
if (sp_buf_add(line, s->in.p, n) != 0)
return -1;
memmove(s->in.p, nl + 1, s->in.len - n - 1);
s->in.len -= n + 1;
s->in.p[s->in.len] = '\0';
return 1;
}
if (s->in.len > RPC_MAX_LINE)
return -1;
pfd.fd = s->from;
pfd.events = POLLIN;
if (poll(&pfd, 1, timeout_ms) <= 0)
return 0;
got = read(s->from, chunk, sizeof(chunk));
if (got < 0 && errno == EINTR)
continue;
if (got <= 0)
return -1;
if (sp_buf_add(&s->in, chunk, (size_t)got) != 0)
return -1;
}
}
/* ---- HTTP transport ---- */
/*
* Temp files carry the request body and the reply headers; $TMPDIR first, never
* a fixed path. The body holds tool arguments, which may be the operator's own
* data, so it is removed and wiped when the call is done.
*/
static int
tmp_path(char *buf, size_t len)
{
const char *dir = getenv("TMPDIR");
char tmpl[600];
int fd;
if (dir == NULL || *dir == '\0')
dir = "/tmp";
if ((size_t)snprintf(tmpl, sizeof(tmpl), "%s/splinter-mcp-XXXXXX",
dir) >= sizeof(tmpl))
return -1;
fd = mkstemp(tmpl);
if (fd < 0)
return -1;
snprintf(buf, len, "%s", tmpl);
return fd;
}
/* The session header the server handed out, if any: keep it for the next call. */
static void
take_session(struct server *s, const char *path)
{
FILE *f = fopen(path, "r");
char line[512];
if (f == NULL)
return;
while (fgets(line, sizeof(line), f) != NULL) {
char *colon = strchr(line, ':');
if (colon == NULL)
continue;
*colon = '\0';
if (strcasecmp(line, "mcp-session-id") == 0) {
char *v = colon + 1, *end;
while (*v == ' ' || *v == '\t')
v++;
end = v + strlen(v);
while (end > v && (end[-1] == '\n' || end[-1] == '\r' ||
end[-1] == ' '))
*--end = '\0';
snprintf(s->session, sizeof(s->session), "%s", v);
}
}
fclose(f);
}
/*
* Pick the reply that belongs to `id` out of an HTTP body.
*
* A server may answer a POST with one JSON object, or with an SSE stream:
* `event: message` / `data: {json}` lines. Both are looked at line by line, so
* a stream with notifications in front of the answer works too.
*/
static char *
pick_reply(const char *body, int id)
{
const char *p = body;
char *best = NULL;
while (*p != '\0') {
const char *eol = strchr(p, '\n');
size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p);
const char *s = p;
size_t l = len;
while (l > 0 && (s[l - 1] == '\r' || s[l - 1] == ' ' ||
s[l - 1] == '\t'))
l--;
if (l > 5 && strncmp(s, "data:", 5) == 0) {
s += 5;
l -= 5;
while (l > 0 && (*s == ' ' || *s == '\t')) {
s++;
l--;
}
}
if (l > 1 && *s == '{') {
char *line = malloc(l + 1);
mcp_json *v;
if (line == NULL)
break;
memcpy(line, s, l);
line[l] = '\0';
v = mcp_parse(line);
if (v != NULL) {
if (mcp_arg_int(v, "id", -1) == id) {
free(best);
best = line;
line = NULL;
}
mcp_json_free(v);
}
free(line);
}
if (eol == NULL)
break;
p = eol + 1;
}
return best;
}
static char *
http_rpc(struct server *s, const char *method, const char *params,
int id, struct sp_buf *err)
{
char body[600], hdr[600], tmo[] = HTTP_TIMEOUT_S, data[640];
char sess[200] = "";
const char *args[20];
const char *hdrs[3];
struct sp_buf req, out;
char *bodyp;
const char *hdrp = NULL;
pid_t pid;
int fd, n = 0, rc, status = 0;
ssize_t w;
char *reply = NULL;
if (sp_buf_init(&req) != 0 || sp_buf_init(&out) != 0)
return NULL;
if (params != NULL)
sp_buf_printf(&req, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":"
"\"%s\",\"params\":%s}", id, method, params);
else
sp_buf_printf(&req, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":"
"\"%s\"}", id, method);
fd = tmp_path(body, sizeof(body));
if (fd < 0) {
sp_buf_printf(err, "mcp: cannot create a temp file: %s",
strerror(errno));
sp_buf_free(&req);
sp_buf_free(&out);
return NULL;
}
w = write(fd, req.p, req.len);
close(fd);
if (w < 0 || (size_t)w != req.len) {
sp_buf_printf(err, "mcp: writing the request: %s",
strerror(errno));
(void)unlink(body);
sp_buf_free(&req);
sp_buf_free(&out);
return NULL;
}
fd = tmp_path(hdr, sizeof(hdr));
if (fd < 0) {
sp_buf_printf(err, "mcp: cannot create a temp file: %s",
strerror(errno));
(void)unlink(body);
sp_buf_free(&req);
sp_buf_free(&out);
return NULL;
}
close(fd);
hdrp = hdr;
snprintf(data, sizeof(data), "@%s", body);
args[n++] = "-sS";
args[n++] = "--connect-timeout";
args[n++] = "5";
args[n++] = "-m";
args[n++] = tmo;
args[n++] = "-X";
args[n++] = "POST";
args[n++] = "-H";
args[n++] = "Content-Type: application/json";
args[n++] = "-H";
args[n++] = "Accept: application/json, text/event-stream";
args[n++] = "--data-binary";
args[n++] = data;
args[n++] = "-D";
args[n++] = hdr;
args[n++] = "-w";
args[n++] = "\n%{http_code}";
args[n] = NULL;
/* the token travels in curl's stdin config, never in argv */
n = 0;
if (s->header[0] != '\0')
hdrs[n++] = s->header;
if (s->session[0] != '\0') {
snprintf(sess, sizeof(sess), "Mcp-Session-Id: %s", s->session);
hdrs[n++] = sess;
}
hdrs[n] = NULL;
if (is_stopping()) {
sp_buf_puts(err, "mcp: shutting down");
(void)unlink(body);
(void)unlink(hdr);
sp_buf_free(&req);
sp_buf_free(&out);
return NULL;
}
fd = sp_curl_start(args, s->url, hdrs, 1, &pid, err);
if (fd < 0) {
(void)unlink(body);
(void)unlink(hdr);
sp_buf_free(&req);
sp_buf_free(&out);
return NULL;
}
/* shutdown kills it: a server that is down must not hold the exit */
s->http_pid = pid;
{
char chunk[8192];
ssize_t got;
while ((got = read(fd, chunk, sizeof(chunk))) > 0) {
if (sp_buf_add(&out, chunk, (size_t)got) != 0)
break;
}
}
close(fd);
(void)waitpid(pid, &rc, 0);
s->http_pid = 0;
take_session(s, hdrp);
(void)unlink(body);
(void)unlink(hdr);
memset(req.p, 0, req.cap);
sp_buf_free(&req);
bodyp = out.p != NULL ? out.p : "";
/* curl's -w appends the status code on its own line */
{
char *nl = strrchr(bodyp, '\n');
if (nl != NULL) {
status = atoi(nl + 1);
((char *)bodyp)[nl - bodyp] = '\0';
}
}
if (status >= 400) {
sp_buf_printf(err, "mcp: %s: HTTP %d %s", method, status,
bodyp);
sp_buf_free(&out);
return NULL;
}
if (id > 0) {
reply = pick_reply(bodyp, id);
if (reply == NULL) {
sp_buf_printf(err, "mcp: %s: no reply with id %d in: %s",
method, id, bodyp);
}
}
sp_buf_free(&out);
return reply;
}
/* ---- one round trip, either transport ---- */
/* An error member is an error; a result is the result, whatever text it holds. */
static char *
accept_reply(char *line, const char *method, struct sp_buf *err)
{
mcp_json *v;
const mcp_json *e;
if (line == NULL)
return NULL;
v = mcp_parse(line);
if (v == NULL) {
sp_buf_printf(err, "mcp: %s: reply is not JSON", method);
free(line);
return NULL;
}
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);
mcp_json_free(v);
free(line);
return NULL;
}
mcp_json_free(v);
return line;
}
/*
* One JSON-RPC round trip. The result is the raw reply line; NULL means the
* server is gone or answered with an error, and 'err' says which.
*/
static char *rpc_locked(size_t which, const char *method, const char *params,
struct sp_buf *err);
static char *
rpc(size_t which, const char *method, const char *params, struct sp_buf *err)
{
char *r;
pthread_mutex_lock(&sv[which].lock);
r = rpc_locked(which, method, params, err);
pthread_mutex_unlock(&sv[which].lock);
return r;
}
static char *
rpc_locked(size_t which, const char *method, const char *params,
struct sp_buf *err)
{
struct server *s = &sv[which];
int id = ++s->next_id;
struct sp_buf line;
char *raw;
if (s->dead || (!s->http && (s->to == NULL || s->from <= 0))) {
sp_buf_puts(err, "mcp: server not connected (reconnecting)");
return NULL;
}
if (s->http)
return accept_reply(http_rpc(s, method, params, id, err), method,
err);
if (params != NULL)
fprintf(s->to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\","
"\"params\":%s}\n", id, method, params);
else
fprintf(s->to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\"}\n",
id, method);
fflush(s->to);
if (sp_buf_init(&line) != 0)
return NULL;
for (;;) {
mcp_json *v;
int rid, rc;
rc = read_line(s, &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) {
s->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 */
}
mcp_json_free(v);
raw = line.p; /* the caller frees it */
return accept_reply(raw, method, err);
}
}
/* A notification has no id and no answer; it still has to be sent. */
static void
notify(struct server *s, const char *method)
{
if (s->http) {
struct sp_buf err;
char body[600], hdr[600], data[640];
const char *args[24], *hdrs[3];
char sess[200];
struct sp_buf req;
pid_t pid;
int fd, n = 0;
ssize_t w;
if (sp_buf_init(&err) != 0 || sp_buf_init(&req) != 0)
return;
sp_buf_printf(&req, "{\"jsonrpc\":\"2.0\",\"method\":\"%s\"}",
method);
fd = tmp_path(body, sizeof(body));
if (fd >= 0) {
w = write(fd, req.p, req.len);
close(fd);
if (w >= 0 && (size_t)w == req.len) {
fd = tmp_path(hdr, sizeof(hdr));
if (fd >= 0) {
close(fd);
snprintf(data, sizeof(data), "@%s", body);
args[n++] = "-sS";
args[n++] = "--connect-timeout";
args[n++] = "5";
args[n++] = "-m";
args[n++] = HTTP_TIMEOUT_S;
args[n++] = "-X";
args[n++] = "POST";
args[n++] = "-H";
args[n++] = "Content-Type: application/json";
args[n++] = "-H";
args[n++] = "Accept: application/json, "
"text/event-stream";
args[n++] = "--data-binary";
args[n++] = data;
args[n++] = "-D";
args[n++] = hdr;
args[n] = NULL;
n = 0;
if (s->header[0] != '\0')
hdrs[n++] = s->header;
/* the session initialize handed out */
if (s->session[0] != '\0') {
snprintf(sess, sizeof(sess),
"Mcp-Session-Id: %s",
s->session);
hdrs[n++] = sess;
}
hdrs[n] = NULL;
fd = is_stopping() ? -1 :
sp_curl_start(args, s->url, hdrs,
1, &pid, &err);
if (fd >= 0) {
s->http_pid = pid;
(void)waitpid(pid, NULL, 0);
s->http_pid = 0;
close(fd);
take_session(s, hdr);
}
(void)unlink(hdr);
}
}
(void)unlink(body);
}
sp_buf_free(&req);
sp_buf_free(&err);
return;
}
if (s->to == NULL)
return;
fprintf(s->to, "{\"jsonrpc\":\"2.0\",\"method\":\"%s\"}\n", method);
fflush(s->to);
}
/* ---- starting servers ---- */
/* Start the child and keep both pipes. */
static int
spawn(struct server *s, struct sp_buf *err)
{
int to[2], from[2];
pid_t child;
if (s->cmd[0] == '\0') {
sp_buf_puts(err, "mcp: a stdio server needs a cmd");
return -1;
}
if (pipe(to) != 0) {
sp_buf_printf(err, "mcp: pipe: %s", strerror(errno));
return -1;
}
if (pipe(from) != 0) {
sp_buf_printf(err, "mcp: pipe: %s", strerror(errno));
close(to[0]);
close(to[1]);
return -1;
}
child = fork();
if (child < 0) {
sp_buf_printf(err, "mcp: fork: %s", strerror(errno));
close(to[0]);
close(to[1]);
close(from[0]);
close(from[1]);
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", s->cmd, (char *)NULL);
_exit(127);
}
close(to[0]);
close(from[1]);
s->pid = child;
s->to = fdopen(to[1], "w");
s->from = from[0];
if (s->to == NULL)
close(to[1]); /* teardown() closes the rest */
if (s->to == NULL || sp_buf_init(&s->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 struct toolref *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;
{
mcp_json nm;
/* the name came from the server: printed back escaped */
memset(&nm, 0, sizeof(nm));
nm.t = MCP_STR;
nm.s = (char *)tool->name;
sp_buf_puts(&params, "{\"name\":");
(void)json_print(&params, &nm);
sp_buf_printf(&params, ",\"arguments\":%s}",
args != NULL && args[0] == '{' ? args : "{}");
}
reply = rpc(tool->srv, "tools/call", params.p, &err);
sp_buf_free(&params);
if (reply == NULL) {
/* not an answer from the server: the link is gone, reconnect */
if (err.p == NULL || strstr(err.p, " failed: ") == NULL)
sv[tool->srv].dead = 1;
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;
size_t i, ntext = 0;
int is_error = res != NULL &&
mcp_arg_bool(res, "isError", 0);
/*
* Every text part, not only the first; a tool that failed says
* so in isError, and the observation has to say it too.
*/
if (is_error)
sp_buf_puts(out, "error: ");
for (i = 0; content != NULL && i < mcp_array_len(content); i++) {
const mcp_json *part = mcp_array_at(content, i);
const char *text = part != NULL ?
mcp_arg_string(part, "text") : NULL;
if (text == NULL)
continue;
sp_buf_printf(out, "%s%s", ntext > 0 ? "\n" : "", text);
ntext++;
}
if (ntext == 0)
sp_buf_printf(out, "%s", reply);
}
mcp_json_free(v);
free(reply);
return 0;
}
/* ---- registration ---- */
/*
* The registry copies the tool struct, not the strings. Everything that was
* allocated for this tool goes with it: the prefixed name, the description,
* the printed schema and the toolref the call needs. Without this the tools of
* an MCP server leaked when the registry was freed (ASAN found 40 KB across a
* single test).
*/
static void
mcp_tool_dispose(struct sp_tool *t)
{
free((char *)t->name);
free((char *)t->description);
free((char *)t->params);
free(t->ctx);
memset(t, 0, sizeof(*t));
}
static int
register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
{
char *reply;
mcp_json*v;
const mcp_json *result, *tools;
size_t i;
int added = 0;
reply = rpc(which, "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;
}
for (i = 0; ; i++) {
const mcp_json *t = mcp_array_at(tools, i);
const mcp_json *schema;
const char *name, *desc;
struct toolref *ref;
struct sp_tool tool;
size_t nlen;
if (t == NULL)
break;
name = mcp_arg_string(t, "name");
desc = mcp_arg_string(t, "description");
if (name == NULL)
continue;
/* this tool's own schema, from its own entry */
schema = mcp_arg(t, "inputSchema");
if (schema != NULL && schema->t != MCP_OBJ)
schema = NULL;
/* the tool's own name, plus "mcp_" and, with several servers, its id */
nlen = strlen(name) + 8 + (prefix ? strlen(s->id) + 1 : 0);
ref = malloc(sizeof(*ref) + nlen);
if (ref == NULL)
continue;
ref->srv = which;
/* the server knows the tool by its own name, never the prefix */
snprintf(ref->name, nlen, "%s", name);
memset(&tool, 0, sizeof(tool));
{
char *toolname = malloc(nlen + 4);
if (toolname == NULL) {
free(ref);
continue;
}
if (prefix)
snprintf(toolname, nlen + 4, "mcp_%s_%s", s->id,
name);
else
snprintf(toolname, nlen + 4, "mcp_%s", name);
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) {
free((char *)tool.name);
free(ref);
continue;
}
if (schema != NULL) {
struct sp_buf sb;
if (sp_buf_init(&sb) == 0) {
if (json_print(&sb, schema) == 0 && sb.p != NULL)
tool.params = sb.p; /* kept, like the copy */
else
sp_buf_free(&sb);
}
}
if (tool.params == NULL)
tool.params = strdup(
"{\"type\":\"object\",\"properties\":{}}");
if (tool.params == NULL) {
free((char *)tool.name);
free((char *)tool.description);
free(ref);
continue;
}
/* an MCP server can do anything; the class is the honest default */
tool.auth = SP_AUTH_MUTATE;
tool.run = call_tool;
tool.ctx = ref;
tool.dispose = mcp_tool_dispose;
if (sp_host_add_tool(host, &tool) == 0)
added++;
else
mcp_tool_dispose(&tool);
}
mcp_json_free(v);
free(reply);
return added;
}
/* ---- plugin entry points ---- */
/*
* The sidebar names every MCP server and whether it is connected, the way the
* editor does: "junction connected", "local disconnected". The old line
* counted tools, which said nothing about which server was gone.
*/
static int
mcp_widget_tick(struct sp_host *h, const char *name, void *ctx)
{
char line[1024];
size_t i, off = 0;
(void)ctx;
if (nsv == 0) {
(void)sp_host_widget_text(h, name,
"no server configured");
return 0;
}
for (i = 0; i < nsv && off < sizeof(line); i++) {
int n;
n = snprintf(line + off, sizeof(line) - off, "%s%s %s",
i > 0 ? "\n" : "", sv[i].id,
sv[i].up ? "connected" : "disconnected");
if (n < 0)
break;
off += (size_t)n;
}
(void)sp_host_widget_text(h, name, line);
return 0;
}
static const struct sp_widget widget = {
"mcp",
mcp_widget_tick,
NULL,
NULL,
2000
};
/* One server through the handshake; the tool list follows in register_tools. */
static int
handshake(size_t which, struct sp_buf *err)
{
struct sp_buf p;
char *reply;
if (sp_buf_init(&p) != 0)
return -1;
sp_buf_printf(&p, "{\"protocolVersion\":\"2025-06-18\","
"\"capabilities\":{},\"clientInfo\":{\"name\":\"splinter\","
"\"version\":\"" SP_VERSION "\"}}");
reply = rpc(which, "initialize", p.p, err);
sp_buf_free(&p);
if (reply == NULL)
return -1;
free(reply);
/* the handshake is not finished until the server is told so */
pthread_mutex_lock(&sv[which].lock);
if (!sv[which].dead)
notify(&sv[which], "notifications/initialized");
pthread_mutex_unlock(&sv[which].lock);
return 0;
}
/* Close a stdio child and its pipes, so the next connect starts clean. */
static void
teardown(struct server *s)
{
if (!s->http) {
if (s->pid > 0) {
(void)kill(s->pid, SIGTERM);
(void)waitpid(s->pid, NULL, 0);
s->pid = 0;
}
if (s->to != NULL) {
fclose(s->to);
s->to = NULL;
}
if (s->from > 0) {
close(s->from);
s->from = 0;
}
}
/* The HTTP transport fills the same line buffer while reading its SSE
* answer; it leaked because this was freed only for stdio. */
if (s->in.p != NULL)
sp_buf_free(&s->in);
s->session[0] = '\0';
s->up = 0;
/* until connect_server() has new pipes, a call fails cleanly */
s->dead = 1;
}
/* Everything one connect attempt needs: start, handshake, tools (once). */
static int
connect_server(size_t i, struct sp_buf *err)
{
struct server *s = &sv[i];
/* a tool call may be in rpc() now: the pipes change under the lock */
pthread_mutex_lock(&s->lock);
if (!s->http && spawn(s, err) != 0) {
pthread_mutex_unlock(&s->lock);
return -1;
}
s->dead = 0;
pthread_mutex_unlock(&s->lock);
if (handshake(i, err) != 0)
return -1;
if (!s->registered) {
int n = register_tools(s, i, nsv > 1, err);
if (n <= 0) {
if (err->p == NULL)
sp_buf_puts(err, "mcp: the server offered no tools");
return -1;
}
s->ntools = n;
s->registered = 1;
}
return 0;
}
/* Sleep RETRY_S seconds in small steps so shutdown is not kept waiting. */
static void
nap(void)
{
int k;
for (k = 0; k < RETRY_S * 10 && !is_stopping(); k++) {
struct timespec ts = { 0, 100000000L };
nanosleep(&ts, NULL);
}
}
static void
say(const char *id, const char *what, const char *more)
{
char line[200];
snprintf(line, sizeof(line), "mcp %.40s: %.60s%.80s", id, what,
more != NULL ? more : "");
(void)sp_host_status_msg(host, line);
}
/* A reply error from the server proves it is alive; anything else is a loss. */
static int
alive_after(const char *err)
{
return err != NULL && strstr(err, " failed: ") != NULL;
}
/*
* One thread per server: connect in the background (a host that is down must
* not delay the start), say what happened, ping every RETRY_S seconds and
* reconnect when the link is gone.
*/
static void *
server_thread_body(void *arg)
{
size_t i = (size_t)(uintptr_t)arg;
struct server *s = &sv[i];
int failed_said = 0, ever_up = 0;
while (!is_stopping()) {
struct sp_buf err;
if (sp_buf_init(&err) != 0)
return NULL;
if (!s->up) {
/* rpc() takes the lock itself, so connect runs without it */
if (connect_server(i, &err) == 0) {
s->up = 1;
{
char n[40];
snprintf(n, sizeof(n), " (%d tools)",
s->ntools);
say(s->id, ever_up ? "reconnected" :
"connected", n);
}
ever_up = 1;
failed_said = 0;
} else {
pthread_mutex_lock(&s->lock);
teardown(s);
pthread_mutex_unlock(&s->lock);
if (!failed_said) {
char why[120];
snprintf(why, sizeof(why), " -- %.100s",
err.p != NULL ? err.p : "no answer");
say(s->id, "not reachable, retrying every 10 s",
why);
failed_said = 1;
}
sp_buf_free(&err);
nap();
continue;
}
} else {
char *r;
nap();
if (is_stopping()) {
sp_buf_free(&err);
break;
}
r = s->dead ? NULL : rpc(i, "ping", NULL, &err);
if (r != NULL)
free(r);
else if (s->dead || !alive_after(err.p)) {
pthread_mutex_lock(&s->lock);
teardown(s);
pthread_mutex_unlock(&s->lock);
say(s->id, "connection lost, reconnecting", NULL);
failed_said = 1; /* stay quiet until it is back */
}
}
sp_buf_free(&err);
}
return NULL;
}
/*
* Every return of the body goes through here, so shutdown can tell when the
* thread is finished instead of guessing with a sleep.
*/
static void *
server_thread(void *arg)
{
size_t i = (size_t)(uintptr_t)arg;
void *rc = server_thread_body(arg);
pthread_mutex_lock(&done_mu);
sv[i].th_done = 1;
pthread_cond_broadcast(&done_cv);
pthread_mutex_unlock(&done_mu);
return rc;
}
static int
mcp_init(struct sp_host *h)
{
const struct sp_config *conf;
size_t i;
host = h;
nsv = 0;
set_stopping(0);
conf = sp_host_config(h);
if (conf != NULL) {
for (i = 0; i < conf->nmcp && nsv < MAX_SERVERS; i++) {
const struct sp_mcpserver *m = &conf->mcp[i];
if (!m->enabled)
continue;
memset(&sv[nsv], 0, sizeof(sv[nsv]));
snprintf(sv[nsv].id, sizeof(sv[nsv].id), "%s", m->id);
snprintf(sv[nsv].url, sizeof(sv[nsv].url), "%s", m->url);
snprintf(sv[nsv].header, sizeof(sv[nsv].header), "%s",
m->header);
snprintf(sv[nsv].cmd, sizeof(sv[nsv].cmd), "%s", m->cmd);
sv[nsv].http = m->url[0] != '\0';
nsv++;
}
}
if (nsv == 0) {
/* the one-server form that came before the config knew about MCP */
const char *cmd = getenv("SPLINTER_MCP_CMD");
if (cmd != NULL && *cmd != '\0') {
memset(&sv[0], 0, sizeof(sv[0]));
snprintf(sv[0].id, sizeof(sv[0].id), "stdio");
snprintf(sv[0].cmd, sizeof(sv[0].cmd), "%s", cmd);
nsv = 1;
}
}
if (nsv == 0) {
(void)sp_host_note(h, "mcp: no server configured");
return -1;
}
(void)sp_host_add_widget(h, &widget);
for (i = 0; i < nsv; i++) {
pthread_mutex_init(&sv[i].lock, NULL);
sv[i].th_done = 0;
say(sv[i].id, "connecting in the background", NULL);
if (pthread_create(&sv[i].th, NULL, server_thread,
(void *)(uintptr_t)i) == 0)
sv[i].th_started = 1;
else
sv[i].dead = 1;
}
return 0;
}
/*
* Wait (bounded) until every server thread has returned. A thread stuck in a
* connect must not hang the shutdown; such a thread is left running and its
* state is not freed.
*/
static void
stop_threads(void)
{
struct timespec deadline;
size_t i;
int pending;
clock_gettime(CLOCK_REALTIME, &deadline);
deadline.tv_sec += 5;
pthread_mutex_lock(&done_mu);
for (;;) {
pending = 0;
for (i = 0; i < nsv; i++)
if (sv[i].th_started && !sv[i].th_done)
pending++;
if (pending == 0)
break;
if (pthread_cond_timedwait(&done_cv, &done_mu, &deadline) != 0)
break;
}
pthread_mutex_unlock(&done_mu);
}
static void
mcp_shutdown(struct sp_host *h)
{
size_t i;
int done;
(void)h;
set_stopping(1);
for (i = 0; i < nsv; i++) {
/* a child is stopped without taking the lock a stuck call may hold */
if (!sv[i].http && sv[i].pid > 0) {
(void)kill(sv[i].pid, SIGTERM);
(void)waitpid(sv[i].pid, NULL, 0);
sv[i].pid = 0;
}
/* an HTTP round trip in flight: its curl goes, the thread sees EOF */
if (sv[i].http && sv[i].http_pid > 0)
(void)kill(sv[i].http_pid, SIGKILL);
sv[i].dead = 1;
}
/*
* Only a thread that has returned may have its buffers freed: the HTTP
* line buffer (up to RPC_MAX_LINE) and the tools it registers live there.
* Before the join, a late register_tools() could also write into a host
* that is being freed.
*/
stop_threads();
for (i = 0; i < nsv; i++) {
if (!sv[i].th_started)
continue;
pthread_mutex_lock(&done_mu);
done = sv[i].th_done;
pthread_mutex_unlock(&done_mu);
if (!done) {
fprintf(stderr, "mcp: %s did not stop within 5 s; its "
"buffers stay\n", sv[i].id);
continue;
}
(void)pthread_join(sv[i].th, NULL);
sv[i].th_started = 0;
teardown(&sv[i]);
pthread_mutex_destroy(&sv[i].lock);
}
}
static const struct sp_plugin plugin = {
SP_PLUGIN_ABI,
"mcp",
"1.1",
mcp_init,
NULL,
mcp_shutdown
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &plugin;
}