Files
splinter/src/backend/mcpserver.c
T
lotherk 36a66ab4f0 self monitor, MCP session tools, junction serving endpoint
- plugins/self: what the session costs the machine - RSS, CPU, threads, fds
  and io of the process itself from /proc/self/*, and the same (count, RSS,
  CPU) for every process whose parent chain reaches it: run calls, MCP
  children, delegates. Widget, /self and the session_usage tool; interval in
  the plugin block (default 2 s).
- MCP server: the session tools. splinter_sessions, splinter_state,
  splinter_models, splinter_agents, splinter_history, splinter_say,
  splinter_open, splinter_model, splinter_agent, splinter_steer,
  splinter_cancel, splinter_approve. Say starts a real turn and returns the
  answer; a turn parked on an approval returns the question instead of
  failing. Mutating tools obey --autonomous. `--daemon --mcp-server-listen`
  runs the MCP server on a thread beside the Telegram daemon.
- the MCP server asks the engine for its registry on every call (a session
  switch replaces it) and copies the tool name out of the parsed JSON before
  freeing it (the first version compared a dangling pointer and answered
  every session call with empty text).
- junction: "serving <endpoint>" - streaming answers carry no
  X-Junction-Endpoint, so the plugin compares the route targets' ok counters
  from /status between samples and names the one that grew, with its
  last_ms. The header is still used when present (non-streaming). The
  X-Junction-Endpoint of the plugin's own /v1/models probe remains a probe
  fact in /junction only.
- transport: X-Junction-Endpoint is parsed from the response headers in both
  the streaming and the non-streaming path and published through
  sp_host_served_by(); sp_reply carries served_by.
- the curl rate guard (--speed-limit/--speed-time) is gone: it cut slow
  router streams with "Less than 1 bytes/sec" even while keepalives arrived.
  The overall -m timeout stays.
- focus: the sidebar shows "recap N, every M turns", and an applied recap
  writes "recap applied (turn N, every M turns)" into the transcript (host
  status messages are now drained during a turn; protocol clients get them
  as entry events too). The initial goal announcement says so as well.
- tests: test_self, test_mcpsession.sh (real socket), test_focus status
  messages, test_junction serving placeholder.

make check: all tests passed.
2026-11-17 19:13:59 +00:00

488 lines
12 KiB
C

/*
* splinter -- the MCP server.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The other direction of plugins/mcp: here splinter *is* the server, so another
* agent can use its tools over MCP.
*
* splinter --mcp-server-listen 127.0.0.1 --mcp-listen-port 8098
* SPLINTER_MCP_TOKEN=... splinter --mcp-server-listen 0.0.0.0 ...
*
* Speaks newline-delimited JSON-RPC over TCP - the same framing MCP uses on
* stdio, just on a socket. Handles initialize, tools/list and tools/call, plus
* the notifications a client sends.
*
* Authorization is the point: a read tool is served, a mutating or destructive
* one is refused unless the server was started with --autonomous. A remote agent
* does not get to run shell commands on this machine because it asked nicely. *
* Who may connect at all is the step before that. 'read' alone hands out every
* file this user can open, so an address other than loopback needs a token:
* SPLINTER_MCP_TOKEN, and every connection starts with the line
*
* AUTH <token>
*
* before any JSON-RPC; anything else closes it. Without a token the server
* refuses to listen beyond 127.0.0.0/8. There is no TLS - put it behind ssh or
* a tunnel when the network is not yours.
*/
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "mcp.h"
#include "mcpserver.h"
#include "mcpsession.h"
static volatile int mcp_stop;
/*
* What a connection works on. With an engine the registry is asked from it on
* every call (a session switch replaces the engine and with it the registry);
* without one the server serves the registry it was handed.
*/
struct srv {
struct sp_engine **eng;
const struct sp_engine_opts *opts;
const struct sp_registry *reg;
};
static const struct sp_registry *
srv_reg(const struct srv *s)
{
if (s->eng != NULL && *s->eng != NULL)
return sp_engine_registry(*s->eng);
return s->reg;
}
static void
on_signal(int sig)
{
(void)sig;
mcp_stop = 1;
}
/* The object that follows "arguments" in the raw line, braces balanced. */
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;
}
static void
write_all(int fd, const char *buf, size_t len)
{
while (len > 0) {
ssize_t n = write(fd, buf, len);
if (n <= 0) {
if (errno == EINTR)
continue;
return;
}
buf += n;
len -= (size_t)n;
}
}
static void
reply_ok(int fd, int id, const char *result)
{
struct sp_buf b;
if (sp_buf_init(&b) != 0)
return;
sp_buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":%s}\n",
id, result);
write_all(fd, b.p, b.len);
sp_buf_free(&b);
}
static void
reply_error(int fd, int id, int code, const char *message)
{
struct sp_buf b;
if (sp_buf_init(&b) != 0)
return;
sp_buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"error\":"
"{\"code\":%d,\"message\":\"", id, code);
(void)sp_json_escape(&b, message);
sp_buf_puts(&b, "\"}}\n");
write_all(fd, b.p, b.len);
sp_buf_free(&b);
}
static void
reply_tools(int fd, int id, const struct srv *s)
{
struct sp_buf b;
size_t i, ntv = 0;
const struct sp_tool *tv = NULL;
int first = 1;
if (sp_buf_init(&b) != 0)
return;
sp_buf_puts(&b, "{\"tools\":[");
if (srv_reg(s) != NULL)
tv = sp_registry_tools(srv_reg(s), &ntv);
for (i = 0; i < ntv; i++) {
const struct sp_tool *t = &tv[i];
if (!first)
sp_buf_puts(&b, ",");
first = 0;
sp_buf_puts(&b, "{\"name\":\"");
(void)sp_json_escape(&b, t->name);
sp_buf_puts(&b, "\",\"description\":\"");
(void)sp_json_escape(&b, t->description != NULL ? t->description :
"");
sp_buf_puts(&b, "\",\"inputSchema\":");
sp_buf_puts(&b, t->params != NULL ? t->params :
"{\"type\":\"object\",\"properties\":{}}");
sp_buf_puts(&b, "}");
}
sp_mcpsession_tools(&b, &first);
sp_buf_puts(&b, "]}");
reply_ok(fd, id, b.p);
sp_buf_free(&b);
}
static void
call_tool(int fd, int id, const struct srv *s, const char *line,
int allow_mutate)
{
const struct sp_tool *t;
const char *name, *argstart = NULL;
char namebuf[128];
struct sp_buf raw, out;
mcp_json *v;
size_t arglen = 0;
int mine;
v = mcp_parse(line);
if (v == NULL) {
reply_error(fd, id, -32700, "parse error");
return;
}
name = NULL;
{
const mcp_json *params = mcp_arg(v, "params");
const mcp_json *args;
if (params != NULL) {
name = mcp_arg_string(params, "name");
args = mcp_arg(params, "arguments");
(void)args;
}
}
if (name == NULL) {
mcp_json_free(v);
reply_error(fd, id, -32602, "params.name is required");
return;
}
/* the name lives in the parsed JSON: copy it before freeing that */
snprintf(namebuf, sizeof(namebuf), "%s", name);
name = namebuf;
mine = sp_mcpsession_has(name);
/* the arguments object, as text - tools parse their own arguments */
{
const char *p = strstr(line, "\"arguments\"");
if (p != NULL) {
const char *slice = slice_object(p, &arglen);
argstart = slice;
}
}
mcp_json_free(v);
if (sp_buf_init(&raw) != 0)
return;
if (argstart != NULL)
(void)sp_buf_add(&raw, argstart, arglen);
else
(void)sp_buf_puts(&raw, "{}");
if (sp_buf_init(&out) != 0) {
sp_buf_free(&raw);
return;
}
if (mine) {
if (sp_mcpsession_auth(name) != SP_AUTH_READ && !allow_mutate) {
sp_buf_free(&raw);
sp_buf_free(&out);
reply_error(fd, id, -32000, "tool needs authorization; "
"start the server with --autonomous to allow "
"mutating calls");
return;
}
(void)sp_mcpsession_call(name, raw.p, &out);
} else {
t = srv_reg(s) != NULL ? sp_registry_find(srv_reg(s), name) : NULL;
if (t == NULL) {
sp_buf_free(&raw);
sp_buf_free(&out);
reply_error(fd, id, -32601, "unknown tool");
return;
}
if (t->auth != SP_AUTH_READ && !allow_mutate) {
sp_buf_free(&raw);
sp_buf_free(&out);
reply_error(fd, id, -32000, "tool needs authorization; "
"start the server with --autonomous to allow "
"mutating calls");
return;
}
if (t->run(raw.p, &out, t->ctx) != 0)
sp_buf_puts(&out, "error: tool failed");
}
{
struct sp_buf res;
if (sp_buf_init(&res) == 0) {
sp_buf_puts(&res, "{\"content\":[{\"type\":\"text\",\"text\":\"");
(void)sp_json_escape(&res, out.p != NULL ? out.p : "");
sp_buf_puts(&res, "\"}]}");
reply_ok(fd, id, res.p);
sp_buf_free(&res);
}
}
sp_buf_free(&raw);
sp_buf_free(&out);
}
static void
handle_line(int fd, const struct srv *s, const char *line, int allow_mutate)
{
mcp_json *v;
const char *method;
int id = -1;
v = mcp_parse(line);
if (v == NULL) {
reply_error(fd, 0, -32700, "parse error");
return;
}
method = mcp_arg_string(v, "method");
id = mcp_arg_int(v, "id", -1);
if (method == NULL) {
mcp_json_free(v);
return;
}
if (strcmp(method, "initialize") == 0) {
char res[512];
snprintf(res, sizeof(res),
"{\"protocolVersion\":\"2024-11-05\",\"capabilities\":"
"{\"tools\":{}},\"serverInfo\":{\"name\":\"splinter\","
"\"version\":\"%s\"}}", SP_VERSION);
mcp_json_free(v);
reply_ok(fd, id, res);
return;
}
if (strcmp(method, "tools/list") == 0) {
mcp_json_free(v);
reply_tools(fd, id, s);
return;
}
if (strcmp(method, "tools/call") == 0) {
mcp_json_free(v);
call_tool(fd, id, s, line, allow_mutate);
return;
}
mcp_json_free(v);
if (id >= 0)
reply_error(fd, id, -32601, "unknown method");
/* a notification has no id and gets no answer */
}
/* compare without stopping at the first difference: no timing hint */
static int
token_equal(const char *a, const char *b)
{
size_t la = strlen(a), lb = strlen(b), i;
unsigned char d = la != lb;
for (i = 0; i < la; i++)
d |= (unsigned char)(a[i] ^ b[i % (lb > 0 ? lb : 1)]);
return d == 0;
}
static void
serve_conn(int fd, const struct srv *s, int allow_mutate, const char *token)
{
char line[16384];
size_t used = 0;
int authed = token == NULL;
for (;;) {
ssize_t got = read(fd, line + used, sizeof(line) - used - 1);
if (got <= 0) {
if (got < 0 && errno == EINTR)
continue;
return;
}
used += (size_t)got;
line[used] = '\0';
for (;;) {
char *nl = strchr(line, '\n');
size_t len;
if (nl == NULL)
break;
*nl = '\0';
if (!authed) {
size_t l = strlen(line);
if (l > 0 && line[l - 1] == '\r')
line[l - 1] = '\0';
if (strncmp(line, "AUTH ", 5) != 0 ||
!token_equal(line + 5, token)) {
reply_error(fd, 0, -32001,
"authentication required");
return;
}
authed = 1;
} else if (line[0] == '{')
handle_line(fd, s, line, allow_mutate);
len = (size_t)(nl - line) + 1;
memmove(line, line + len, used - len + 1);
used -= len;
}
if (used >= sizeof(line) - 1)
used = 0; /* a line we cannot hold */
}
}
int
sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts,
const struct sp_registry *reg, const char *ip, int port,
int allow_mutate, int own_signals, struct sp_buf *err)
{
struct srv srv;
int s, one = 1;
struct sockaddr_in addr;
const char *token = getenv("SPLINTER_MCP_TOKEN");
size_t ntools = reg != NULL ? reg->len : 0;
memset(&srv, 0, sizeof(srv));
srv.eng = eng;
srv.opts = opts;
srv.reg = reg;
sp_mcpsession_bind(eng, opts);
if (eng != NULL && *eng != NULL && srv_reg(&srv) != NULL)
ntools = srv_reg(&srv)->len;
if (ip == NULL || *ip == '\0')
ip = "127.0.0.1";
if (token != NULL && *token == '\0')
token = NULL;
if (token == NULL && strncmp(ip, "127.", 4) != 0) {
sp_buf_printf(err, "mcp: refusing to serve on %s without "
"SPLINTER_MCP_TOKEN: 'read' alone would give the network "
"every file of this user", ip);
return -1;
}
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
sp_buf_printf(err, "mcp: socket: %s", strerror(errno));
return -1;
}
(void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons((unsigned short)port);
if (inet_pton(AF_INET, ip, &addr.sin_addr) != 1) {
sp_buf_printf(err, "mcp: '%s' is not an address", ip);
close(s);
return -1;
}
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
sp_buf_printf(err, "mcp: bind %s:%d: %s", ip, port,
strerror(errno));
close(s);
return -1;
}
if (listen(s, 8) != 0) {
sp_buf_printf(err, "mcp: listen: %s", strerror(errno));
close(s);
return -1;
}
if (own_signals) {
(void)signal(SIGINT, on_signal);
(void)signal(SIGTERM, on_signal);
}
/* a client that hangs up mid-reply is a closed connection, not our death */
(void)signal(SIGPIPE, SIG_IGN);
fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools + %d "
"session tools, %s, %s)\n", ip, port, ntools, 12,
allow_mutate ? "mutating allowed" : "read only",
token != NULL ? "token required" : "loopback, no token");
while (!mcp_stop) {
int c = accept(s, NULL, NULL);
if (c < 0) {
if (errno == EINTR)
continue;
break;
}
{
/*
* One connection at a time, so an idle one must not hold
* the server forever: five quiet minutes and it is closed.
*/
struct timeval tv = { 300, 0 };
(void)setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv));
}
serve_conn(c, &srv, allow_mutate, token);
close(c);
}
close(s);
fprintf(stderr, "splinter: MCP server stopped\n");
return 0;
}