Files
splinter/plugins/mcp/mcp.c
T
lotherkandClaude Opus 5.5 bddba6423b anthropic 400 on repeated user turns, exit in under a second, /quit
- anthropic: two messages of the same role in a row (a failed turn asked
  again) put the second one's blocks after the closed message object; the
  API answered 400 "messages.1.role: Field required". The message now stays
  open until the role changes.
- exit took 20+ s: the mcp plugin's HTTP round trip to a server that is down
  had curl -m 60 and nothing killed it; shutdown now kills the curl in
  flight, and connects time out after 5 s. Widget threads slept a whole
  interval before seeing the stop flag; they sleep in 100 ms steps.
- /quit (/exit, /q) leaves the chat.
- the prompt mark has its space again: the catalogue trims trailing blanks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 20:31:51 +00:00

1115 lines
26 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;
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 */
};
#define RETRY_S 10
static volatile int stopping;
static struct server sv[MAX_SERVERS];
static size_t nsv;
static struct sp_host *host;
/* A registered tool knows which server it belongs to and what it is called there. */
struct toolref {
size_t srv;
char name[];
};
/*
* 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 *p = strchr(at, '{');
const char *start;
int depth = 0, instr = 0, escape = 0;
if (p == NULL)
return NULL;
start = p;
for (; *p != '\0'; p++) {
if (escape) {
escape = 0;
continue;
}
if (instr) {
if (*p == '\\')
escape = 1;
else if (*p == '"')
instr = 0;
continue;
}
if (*p == '"')
instr = 1;
else if (*p == '{')
depth++;
else if (*p == '}' && --depth == 0) {
*lenp = (size_t)(p - start + 1);
return start;
}
}
return NULL;
}
/* ---- 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 (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) {
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[20], *hdrs[3];
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++] = "--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;
hdrs[n] = NULL;
fd = 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;
}
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 || 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", 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 || 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;
sp_buf_printf(&params, "{\"name\":\"%s\",\"arguments\":%s}", tool->name,
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;
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 server *s, size_t which, int prefix, 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(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;
}
/* 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;
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;
slice = strstr(schema_at, "inputSchema");
if (slice != NULL)
slice = slice_object(slice, &len);
if (slice != NULL)
schema_at = slice;
/* 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;
if (prefix)
snprintf(ref->name, nlen, "%s_%s", s->id, name);
else
snprintf(ref->name, nlen, "%s", name);
memset(&tool, 0, sizeof(tool));
{
char *toolname = malloc(nlen + 4);
if (toolname == NULL) {
free(ref);
continue;
}
snprintf(toolname, nlen + 4, "mcp_%s", ref->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 (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 = ref;
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 servers offered and whether they are gone. */
static int
mcp_widget_tick(struct sp_host *h, const char *name, void *ctx)
{
char line[96];
size_t i;
int alive = 0, total = 0;
(void)ctx;
for (i = 0; i < nsv; i++) {
total += sv[i].up ? sv[i].ntools : 0;
if (sv[i].up)
alive++;
}
if (nsv > 0 && alive == 0)
snprintf(line, sizeof(line), "%d tools, offline", total);
else
snprintf(line, sizeof(line), "%d tools", total);
(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 */
notify(&sv[which], "notifications/initialized");
return 0;
}
/* Close a stdio child and its pipes, so the next connect starts clean. */
static void
teardown(struct server *s)
{
if (!s->http && 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;
if (s->in.p != NULL)
sp_buf_free(&s->in);
}
s->session[0] = '\0';
s->up = 0;
}
/* 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];
s->dead = 0;
if (!s->http && spawn(s, err) != 0)
return -1;
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 && !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(void *arg)
{
size_t i = (size_t)(uintptr_t)arg;
struct server *s = &sv[i];
int failed_said = 0, ever_up = 0;
while (!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 {
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 (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;
}
static int
mcp_init(struct sp_host *h)
{
const struct sp_config *conf;
size_t i;
host = h;
nsv = 0;
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_t t;
pthread_mutex_init(&sv[i].lock, NULL);
say(sv[i].id, "connecting in the background", NULL);
if (pthread_create(&t, NULL, server_thread,
(void *)(uintptr_t)i) == 0)
pthread_detach(t);
else
sv[i].dead = 1;
}
return 0;
}
static void
mcp_shutdown(struct sp_host *h)
{
size_t i;
(void)h;
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;
}
}
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;
}