mcp: servers from the config, HTTP transport

The MCP client could only start one program and talk to it on a pipe; a server
behind an endpoint (junction at http://host:8090/mcp) had no way in. Now the
config names the servers and the plugin speaks whichever transport each one
offers:

- new `mcp NAME { url | cmd | header | enabled }` block (and the flat
  `mcp = NAME | url=...` form), parsed into struct sp_mcpserver; an entry
  without a url and without a cmd is refused with its line number
- streamable HTTP in plugins/mcp/mcp.c: one POST per JSON-RPC message, answered
  with one JSON object or an SSE stream of `data:` lines - both are read,
  Mcp-Session-Id is kept and echoed back, and the Authorization header travels
  through curl's stdin config so the token never appears in ps
- several servers register side by side; tools are mcp_<tool> for one server
  and mcp_<server>_<tool> for more, so two servers that both offer `search` do
  not overwrite each other. A server that fails its handshake is reported and
  skipped, the rest still load. SPLINTER_MCP_CMD stays as the one stdio server
- tests: the config and block parsers, and a socket server in test_mcpclient
  that refuses the tool list without the configured header and answers the call
  as an event stream
- README and docs/CONFIG.md describe both transports and where the token lives
This commit is contained in:
lotherk committed 2026-11-12 12:05:35 +00:00
1 parent bad1e4511f
commit 62a041a61b
9 files changed
+1041 -153

No files matched your search

+24 -5
View File
@@ -475,15 +475,34 @@ like a resume and was none.
## MCP
`plugins/mcp/mcp.so` speaks to an MCP server over stdio and registers its tools:
`plugins/mcp/mcp.so` speaks MCP to a server and registers its tools. The config
names the servers; two transports, one block each:
SPLINTER_MCP_CMD="npx -y @modelcontextprotocol/server-filesystem /home" \
splinter --plugin plugins/mcp/mcp.so
mcp junction {
url = http://172.25.206.16:8090/mcp
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
}
mcp files {
cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
}
`url` is the streamable-HTTP transport: one POST per JSON-RPC message, answered
with one JSON object or with an SSE stream of `data:` lines - both are read, and
the `Mcp-Session-Id` a server hands out is echoed back. `cmd` starts a program
whose stdin/stdout carry the same messages. A header travels to curl through its
stdin config, so the token is never in `ps`.
Each tool keeps the schema the server published, so the model sees its
parameters; the class is `mutate`, because a server can do anything and the
harness does not pretend to know better. Proven against a test server: the model
called `mcp_add(17, 25)` and answered 42.
harness does not pretend to know better. With one server the tools are
`mcp_<tool>`; with several, `mcp_<server>_<tool>`. Proven against both: a stdio
test server (the model called `mcp_add(17, 25)` and answered 42) and a socket
server that speaks HTTP and SSE.
The one-server form from before still works:
SPLINTER_MCP_CMD="npx -y @modelcontextprotocol/server-filesystem /home" \
splinter --plugin plugins/mcp/mcp.so
The other direction, splinter as the server, is `--mcp-server-listen IP`:
newline-delimited JSON-RPC over TCP, read tools only unless `--autonomous`.
+47
View File
@@ -201,6 +201,7 @@ lies about what it does.
| `limit`, `tokens` | allowance of the main provider, see Usage limits |
| `exit` | one way to reach a model for the exit ring, see below |
| `delegate` | another model the `delegate` tool can hand work to, see below |
| `mcp` | an MCP server whose tools become splinter's tools, see below |
Secrets never go into the file: every `*key_env` names a variable, and the
variable holds the key. Those variables are hidden from the `run` tool's shell.
@@ -271,6 +272,52 @@ task moves to the next delegate in its own slot while the others keep running,
unless that one is already at its `max_parallel`. Only when nothing else fits
does the job wait (`waiting_quota`) for the reset.
## MCP servers
An MCP server contributes tools. One line each, or a block, and it needs the
`plugins/mcp/mcp.so` plugin:
```
plugin = /home/lotherk/src/splinter/plugins/mcp/mcp.so
# streamable HTTP: one POST per message
mcp junction {
url = http://172.25.206.16:8090/mcp
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
}
# or a program that speaks MCP on its stdin/stdout
mcp files {
cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
}
# a server that exists but should not be asked
mcp old { url = http://127.0.0.1:9000/mcp enabled = false }
```
| field | meaning |
|-------|---------|
| `url` | the endpoint, streamable-HTTP transport (`.../mcp`) |
| `cmd` | a program started with `/bin/sh -c`, spoken to over stdin/stdout |
| `header` | one header line, usually the token: `Authorization: Bearer ...` |
| `enabled` | `0`/`false` keeps the entry but does not load it (default on) |
The token belongs in the environment: `"${JUNCTION_TOKEN}"` is expanded when
the file is read, and the header travels to curl through its stdin config, so
it is never in `ps`. A literal token in the file is a secret in the file:
`chmod 600`.
Tool names: with one server they are `mcp_<tool>`; with several they are
`mcp_<server>_<tool>`, so two servers that both offer `search` stay apart. They
are all in the `mutate` class - a server can do anything, and the harness does
not pretend to know better. The sidebar widget shows how many tools came back
and says so when a server stops answering.
The handshake is `initialize` + `notifications/initialized` + `tools/list`; a
server that fails it is reported and skipped, and the others still load. The
single-server environment variable from before still works:
`SPLINTER_MCP_CMD="npx -y ..."` is one stdio server.
## Example: local model
```
+601 -145
View File
@@ -6,7 +6,16 @@
*
* An MCP server holds tools; this makes them the harness's tools.
*
* Configure one server per plugin instance:
* 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"
*
@@ -15,38 +24,60 @@
* 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.
* 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 <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 {
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;
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;
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;
};
static struct server srv;
static struct server sv[MAX_SERVERS];
static size_t nsv;
static struct sp_host *host;
static int ntools;
/* 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.
@@ -58,42 +89,44 @@ static int ntools;
static const char *
slice_object(const char *at, size_t *lenp)
{
const char *start;
int depth = 0, in_str = 0, esc = 0;
const char *p = strchr(at, '{');
const char *start;
int depth = 0, instr = 0, escape = 0;
start = strchr(at, '{');
if (start == NULL)
if (p == 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;
start = p;
for (; *p != '\0'; p++) {
if (escape) {
escape = 0;
continue;
}
if (*at == '"')
in_str = 1;
else if (*at == '{')
if (instr) {
if (*p == '\\')
escape = 1;
else if (*p == '"')
instr = 0;
continue;
}
if (*p == '"')
instr = 1;
else if (*p == '{')
depth++;
else if (*at == '}') {
depth--;
if (depth == 0) {
*lenp = (size_t)(at - start) + 1;
return start;
}
else if (*p == '}' && --depth == 0) {
*lenp = (size_t)(p - start + 1);
return start;
}
}
return NULL;
}
#define RPC_MAX_LINE (16u * 1024 * 1024)
/* ---- stdio transport ---- */
/*
* 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.
* 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
@@ -103,75 +136,360 @@ slice_object(const char *at, size_t *lenp)
* buffered here, where poll() and the buffer agree.
*/
static int
read_line(struct sp_buf *line, int timeout_ms)
read_line(struct server *s, struct sp_buf *line, int timeout_ms)
{
for (;;) {
char *nl = srv.in.p != NULL ?
memchr(srv.in.p, '\n', srv.in.len) : NULL;
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 - srv.in.p);
size_t n = (size_t)(nl - s->in.p);
sp_buf_clear(line);
if (sp_buf_add(line, srv.in.p, n) != 0)
if (sp_buf_add(line, s->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';
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 (srv.in.len > RPC_MAX_LINE)
if (s->in.len > RPC_MAX_LINE)
return -1;
pfd.fd = srv.from;
pfd.fd = s->from;
pfd.events = POLLIN;
if (poll(&pfd, 1, timeout_ms) <= 0)
return 0;
got = read(srv.from, chunk, sizeof(chunk));
got = read(s->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)
if (sp_buf_add(&s->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;
/* ---- HTTP transport ---- */
if (srv.dead)
/*
* 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)
fprintf(srv.to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\","
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++] = "-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;
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;
}
{
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);
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(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)
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(srv.to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\"}\n",
fprintf(s->to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\"}\n",
id, method);
fflush(srv.to);
fflush(s->to);
if (sp_buf_init(&line) != 0)
return NULL;
for (;;) {
mcp_json *v;
const mcp_json *e;
int rid;
char *res;
int rid, rc;
rc = read_line(&line, RPC_TIMEOUT_MS);
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) {
srv.dead = 1;
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);
@@ -190,36 +508,83 @@ rpc(const char *method, const char *params, struct sp_buf *err)
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;
raw = line.p; /* the caller frees it */
return accept_reply(raw, method, err);
}
}
/* Start the server and keep both pipes. */
/* 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++] = "-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 = sp_curl_start(args, s->url, hdrs,
1, &pid, &err);
if (fd >= 0) {
(void)waitpid(pid, NULL, 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 sp_buf *err)
spawn(struct server *s, struct sp_buf *err)
{
int to[2], from[2];
pid_t child;
const char *cmd = getenv("SPLINTER_MCP_CMD");
pid_t child;
if (cmd == NULL || *cmd == '\0') {
sp_buf_puts(err, "mcp: SPLINTER_MCP_CMD is not set");
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) {
@@ -238,15 +603,15 @@ spawn(struct sp_buf *err)
close(to[1]);
close(from[0]);
close(from[1]);
execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
execl("/bin/sh", "sh", "-c", s->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) {
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;
}
@@ -258,16 +623,16 @@ spawn(struct sp_buf *err)
static int
call_tool(const char *args, struct sp_buf *out, void *ctx)
{
const char *tool = 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,
sp_buf_printf(&params, "{\"name\":\"%s\",\"arguments\":%s}", tool->name,
args != NULL && args[0] == '{' ? args : "{}");
reply = rpc("tools/call", params.p, &err);
reply = rpc(tool->srv, "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");
@@ -302,7 +667,7 @@ call_tool(const char *args, struct sp_buf *out, void *ctx)
/* ---- registration ---- */
static int
register_tools(struct sp_buf *err)
register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
{
char *reply;
const char *schema_at;
@@ -311,7 +676,7 @@ register_tools(struct sp_buf *err)
size_t i;
int added = 0;
reply = rpc("tools/list", "{}", err);
reply = rpc(which, "tools/list", "{}", err);
if (reply == NULL)
return -1;
v = mcp_parse(reply);
@@ -334,8 +699,9 @@ register_tools(struct sp_buf *err)
const char *name, *desc;
const char *slice;
size_t len = 0;
char *toolname;
struct toolref *ref;
struct sp_tool tool;
size_t nlen;
if (t == NULL)
break;
@@ -349,12 +715,28 @@ register_tools(struct sp_buf *err)
if (slice != NULL)
schema_at = slice;
toolname = malloc(strlen(name) + 8);
if (toolname == 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;
snprintf(toolname, strlen(name) + 8, "mcp_%s", name);
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));
tool.name = toolname;
{
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
@@ -362,8 +744,11 @@ register_tools(struct sp_buf *err)
* the model never saw a usable tool.
*/
tool.description = strdup(desc != NULL ? desc : "MCP tool");
if (tool.description == NULL)
if (tool.description == NULL) {
free((char *)tool.name);
free(ref);
continue;
}
if (slice != NULL) {
char *copy = malloc(len + 1);
@@ -378,7 +763,7 @@ register_tools(struct sp_buf *err)
/* 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;
tool.ctx = ref;
if (sp_host_add_tool(host, &tool) == 0)
added++;
}
@@ -389,17 +774,24 @@ register_tools(struct sp_buf *err)
/* ---- plugin entry points ---- */
/* The sidebar says how many tools the server offered; a silent zero is a bug. */
/* 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];
char line[96];
size_t i;
int alive = 0, total = 0;
(void)ctx;
if (srv.dead)
snprintf(line, sizeof(line), "%d tools, server gone", ntools);
for (i = 0; i < nsv; i++) {
total += sv[i].ntools;
if (!sv[i].dead)
alive++;
}
if (nsv > 0 && alive == 0)
snprintf(line, sizeof(line), "%d tools, server gone", total);
else
snprintf(line, sizeof(line), "%d tools", ntools);
snprintf(line, sizeof(line), "%d tools", total);
(void)sp_host_widget_text(h, name, line);
return 0;
}
@@ -412,49 +804,107 @@ static const struct sp_widget widget = {
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;
}
static int
mcp_init(struct sp_host *h)
{
struct sp_buf err, p;
char *reply;
int n;
const struct sp_config *conf;
struct sp_buf err;
size_t i;
int total = 0;
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);
nsv = 0;
conf = sp_host_config(h);
n = register_tools(&err);
if (n <= 0) {
(void)sp_host_note(h, err.p != NULL ? err.p :
"mcp: the server offered no tools");
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");
sp_buf_free(&err);
return -1;
}
for (i = 0; i < nsv; i++) {
int n;
if (!sv[i].http && spawn(&sv[i], &err) != 0) {
(void)sp_host_note(h, err.p != NULL ? err.p :
"mcp: cannot start the server");
sv[i].dead = 1;
sp_buf_clear(&err);
continue;
}
if (handshake(i, &err) != 0) {
(void)sp_host_note(h, err.p != NULL ? err.p :
"mcp: handshake failed");
sv[i].dead = 1;
sp_buf_clear(&err);
continue;
}
n = register_tools(&sv[i], i, nsv > 1, &err);
if (n <= 0) {
(void)sp_host_note(h, err.p != NULL ? err.p :
"mcp: the server offered no tools");
sv[i].dead = 1;
sp_buf_clear(&err);
continue;
}
sv[i].ntools = n;
total += n;
}
if (total <= 0) {
sp_buf_free(&err);
return -1;
}
ntools = n;
(void)sp_host_add_widget(h, &widget);
sp_buf_free(&err);
return 0;
@@ -463,18 +913,24 @@ mcp_init(struct sp_host *h)
static void
mcp_shutdown(struct sp_host *h)
{
size_t i;
(void)h;
if (srv.dead || srv.pid <= 0)
return;
(void)kill(srv.pid, SIGTERM);
(void)waitpid(srv.pid, NULL, 0);
srv.dead = 1;
for (i = 0; i < nsv; i++) {
if (!sv[i].http && !sv[i].dead && sv[i].pid > 0) {
(void)kill(sv[i].pid, SIGTERM);
(void)waitpid(sv[i].pid, NULL, 0);
}
sv[i].dead = 1;
if (sv[i].in.p != NULL)
sp_buf_free(&sv[i].in);
}
}
static const struct sp_plugin plugin = {
SP_PLUGIN_ABI,
"mcp",
"1.0",
"1.1",
mcp_init,
NULL,
mcp_shutdown
+34 -2
View File
@@ -415,6 +415,35 @@ do_pool(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
members);
}
static void
do_mcp(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
{
struct sp_buf l;
size_t i;
if (sp_buf_init(&l) != 0)
return;
sp_buf_printf(&l, "mcp = %s", name);
for (i = 0; i < n; i++) {
const char *s = one(c, &e[i]);
if (s == NULL || !clean(c, &e[i], s))
goto done;
if (!strcmp(e[i].key, "url") || !strcmp(e[i].key, "cmd") ||
!strcmp(e[i].key, "header"))
sp_buf_printf(&l, " | %s=%s", e[i].key, s);
else if (!strcmp(e[i].key, "enabled"))
sp_buf_printf(&l, " | enabled=%d", boolean(s));
else {
fail(c, e[i].line, "unknown mcp field '%s'", e[i].key);
goto done;
}
}
emit(c, line, "%s", l.p);
done:
sp_buf_free(&l);
}
static void
do_exit(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
{
@@ -654,7 +683,8 @@ sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
n = body(&c, e, &closed);
if (!c.failed && closed) {
int needs_name = !strcmp(kind, "provider") ||
!strcmp(kind, "pool") || !strcmp(kind, "exit");
!strcmp(kind, "pool") || !strcmp(kind, "exit") ||
!strcmp(kind, "mcp");
if (needs_name && name[0] == '\0')
fail(&c, line, "%s needs a name: %s NAME { ... }",
@@ -682,9 +712,11 @@ sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
do_pool(&c, name, line, e, n);
else if (!strcmp(kind, "exit"))
do_exit(&c, name, line, e, n);
else if (!strcmp(kind, "mcp"))
do_mcp(&c, name, line, e, n);
else
fail(&c, line, "unknown block '%s' (core, telegram, "
"provider, pool, exit)", kind);
"provider, pool, exit, mcp)", kind);
}
ents_free(e, n);
if (c.failed)
+59
View File
@@ -397,6 +397,54 @@ sp_config_load(struct sp_config *c, const char *path, struct sp_buf *err)
}
/* mcp = id | url=... | cmd=... | header=... | enabled=0 */
static int
parse_mcp(struct sp_mcpserver *m, const char *val, struct sp_buf *err,
const char *path, unsigned lineno)
{
char *copy, *field, *save = NULL;
int first = 1;
memset(m, 0, sizeof(*m));
m->enabled = 1;
copy = strdup(val);
if (copy == NULL)
return -1;
for (field = strtok_r(copy, "|", &save); field != NULL;
field = strtok_r(NULL, "|", &save)) {
char *s = trim(field);
if (*s == '\0')
continue;
if (first && strchr(s, '=') == NULL) {
snprintf(m->id, sizeof(m->id), "%s", s);
first = 0;
} else if (!strncmp(s, "url=", 4))
snprintf(m->url, sizeof(m->url), "%s", s + 4);
else if (!strncmp(s, "cmd=", 4))
snprintf(m->cmd, sizeof(m->cmd), "%s", s + 4);
else if (!strncmp(s, "header=", 7))
snprintf(m->header, sizeof(m->header), "%s", s + 7);
else if (!strncmp(s, "enabled=", 8))
m->enabled = strcmp(s + 8, "0") != 0 &&
strcmp(s + 8, "false") != 0 &&
strcmp(s + 8, "no") != 0;
else {
sp_buf_printf(err, "config: %s:%u: unknown mcp field "
"'%s'", path, lineno, s);
free(copy);
return -1;
}
}
free(copy);
if (m->id[0] == '\0' || (m->url[0] == '\0' && m->cmd[0] == '\0')) {
sp_buf_printf(err, "config: %s:%u: an mcp server needs a name "
"and a url or a cmd", path, lineno);
return -1;
}
return 0;
}
/* pool = id | strategy=failover|balance | members=a,b,c */
static int
parse_pool(struct sp_pool *p, const char *val, struct sp_buf *err,
@@ -712,6 +760,17 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
return -1;
}
set_str(c->plugins[c->nplugins++], 512, val);
}
else if (!strcmp(key, "mcp")) {
if (c->nmcp == SP_CONFIG_MAX_MCP) {
sp_buf_printf(err, "config: %s:%u: more than %d "
"mcp servers", path, lineno, SP_CONFIG_MAX_MCP);
return -1;
}
if (parse_mcp(&c->mcp[c->nmcp], val, err, path,
lineno) != 0)
return -1;
c->nmcp++;
} else {
sp_buf_printf(err, "config: %s:%u: unknown key '%s'",
path, lineno, key);
+21
View File
@@ -85,6 +85,25 @@ struct sp_pool {
size_t nmembers;
};
/*
* An MCP server: tools splinter may use. Two ways to reach one, and the config
* says which: a program that speaks MCP on stdin/stdout (`cmd`), or an endpoint
* that speaks it over HTTP (`url`, the streamable-HTTP transport). A header is
* kept here rather than in the command line, because it is where the token is.
*/
#define SP_CONFIG_MAX_MCP 8
#define SP_CONFIG_MCP_URL 512
#define SP_CONFIG_MCP_HEADER 512
#define SP_CONFIG_MCP_CMD 512
struct sp_mcpserver {
char id[32];
char url[SP_CONFIG_MCP_URL]; /* set: HTTP, else stdio */
char cmd[SP_CONFIG_MCP_CMD]; /* started for stdio */
char header[SP_CONFIG_MCP_HEADER]; /* one line, e.g. Authorization */
int enabled; /* 1 by default */
};
struct sp_config {
struct sp_pool pool[SP_CONFIG_MAX_POOLS];
size_t npools;
@@ -114,6 +133,8 @@ struct sp_config {
char locale[32]; /* language code, exported as SPLINTER_LOCALE */
char plugins[SP_CONFIG_MAX_PLUGINS][512];
size_t nplugins;
struct sp_mcpserver mcp[SP_CONFIG_MAX_MCP];
size_t nmcp;
size_t steps; /* 0: not set */
size_t max_bytes; /* 0: not set */
long http_timeout; /* seconds for HTTP/SSE requests, 0: default */
+24 -1
View File
@@ -73,7 +73,15 @@ main(void)
" env { CLAUDE_CODE_OAUTH_TOKEN = \"${CB_TOKEN}\" OTHER = \"${CB_UNSET}\" }\n"
"}\n"
"provider hidden { endpoint = http://x/v1 model = z delegate = false }\n"
"pool claude { members = [claude-a, local] strategy = balance }\n",
"pool claude { members = [claude-a, local] strategy = balance }\n"
"mcp junction {\n"
" url = http://127.0.0.1:8090/mcp\n"
" header = \"Authorization: Bearer ${CB_TOKEN}\"\n"
"}\n"
"mcp files {\n"
" cmd = \"npx -y server-filesystem /home\"\n"
" enabled = false\n"
"}\n",
c, &err) == 0);
if (err.len > 0) fprintf(stderr, "err: %s\n", err.p);
CHECK(strcmp(c->theme, "Delphinium") == 0);
@@ -93,6 +101,21 @@ main(void)
CHECK(strcmp(c->delegate[1].kind, "cli") == 0);
CHECK(c->npools == 1 && c->pool[0].nmembers == 2);
CHECK(strcmp(c->pool[0].strategy, "balance") == 0);
CHECK(c->nmcp == 2);
CHECK(strcmp(c->mcp[0].id, "junction") == 0);
CHECK(strcmp(c->mcp[0].url, "http://127.0.0.1:8090/mcp") == 0);
CHECK(strstr(c->mcp[0].header, "Bearer sekrit") != NULL);
CHECK(c->mcp[0].enabled == 1);
CHECK(strcmp(c->mcp[1].id, "files") == 0);
CHECK(strcmp(c->mcp[1].cmd, "npx -y server-filesystem /home") == 0);
CHECK(c->mcp[1].enabled == 0);
CHECK(c->mcp[1].url[0] == '\0');
sp_buf_clear(&err);
CHECK(load("mcp noendpoint { header = \"x: y\" }\n", c, &err) != 0);
CHECK(strstr(err.p, "url or a cmd") != NULL);
sp_buf_clear(&err);
CHECK(load("mcp { url = http://h/mcp }\n", c, &err) != 0);
/* errors name the line that was written */
sp_buf_clear(&err);
+11
View File
@@ -64,6 +64,9 @@ main(void)
"plugin = plugins/cps/cps.so\n"
"cli_cmd = claude -p\n"
"cli_env = CLAUDE_CODE_OAUTH_TOKEN=tok=with=eq\n"
"mcp = junction | url=http://127.0.0.1:8090/mcp | "
"header=Authorization: Bearer abc | enabled=0\n"
"mcp = files | cmd=npx -y server-filesystem /home\n"
"delegate = c2 | zweites Konto | kind=cli | cmd=claude -p | "
"env=CLAUDE_CODE_OAUTH_TOKEN=abc | env=FOO=bar baz\n"
"system_prompt = sei knapp\n");
@@ -83,6 +86,14 @@ main(void)
CHECK(strcmp(c.cli_cmd, "claude -p") == 0);
CHECK(c.ncli_env == 1);
CHECK(strcmp(c.cli_env[0], "CLAUDE_CODE_OAUTH_TOKEN=tok=with=eq") == 0);
CHECK(c.nmcp == 2);
CHECK(strcmp(c.mcp[0].id, "junction") == 0);
CHECK(strcmp(c.mcp[0].url, "http://127.0.0.1:8090/mcp") == 0);
CHECK(strcmp(c.mcp[0].header, "Authorization: Bearer abc") == 0);
CHECK(c.mcp[0].enabled == 0);
CHECK(strcmp(c.mcp[1].id, "files") == 0);
CHECK(strcmp(c.mcp[1].cmd, "npx -y server-filesystem /home") == 0);
CHECK(c.mcp[1].enabled == 1); /* on unless said otherwise */
CHECK(c.ndelegates == 1);
CHECK(c.delegate[0].nenv == 2);
CHECK(strcmp(c.delegate[0].env[0], "CLAUDE_CODE_OAUTH_TOKEN=abc") == 0);
+220
View File
@@ -6,15 +6,26 @@
* that arrived in the same write as a notification sat unseen in stdio's
* buffer until the timeout, and a result that merely contained the text
* "error" was reported as a failed call.
*
* The second half runs the same plugin against a server that speaks the
* streamable-HTTP transport on a socket: the config names a url, the tool comes
* back, the call answers, and the Authorization header the config wrote really
* arrived - the fake server refuses the tool list without it.
*/
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "config.h"
static int failures;
@@ -49,6 +60,159 @@ static const char *server_sh =
" esac\n"
"done\n";
/* ---- a fake MCP server on a socket, speaking streamable HTTP ---- */
static int
send_all(int fd, const char *p, size_t n)
{
while (n > 0) {
ssize_t w = write(fd, p, n);
if (w <= 0)
return -1;
p += w;
n -= (size_t)w;
}
return 0;
}
static int
send_reply(int fd, const char *extra, const char *type, const char *body)
{
char head[512];
size_t n;
n = (size_t)snprintf(head, sizeof(head), "HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\nContent-Length: %zu\r\n%s\r\n", type,
strlen(body), extra);
if (send_all(fd, head, n) != 0)
return -1;
return send_all(fd, body, strlen(body));
}
/* Headers and body of one request, until Content-Length bytes are there. */
static int
read_http(int fd, char *buf, size_t len)
{
size_t off = 0;
for (;;) {
ssize_t got;
char *end, *cl, *body;
long clen = 0;
if (off + 1 >= len)
return -1;
got = read(fd, buf + off, len - off - 1);
if (got <= 0)
return -1;
off += (size_t)got;
buf[off] = '\0';
end = strstr(buf, "\r\n\r\n");
if (end == NULL)
continue;
body = end + 4;
cl = strstr(buf, "Content-Length:");
if (cl != NULL)
clen = atol(cl + 15);
if (off >= (size_t)(body - buf) + (size_t)clen)
return 0;
}
}
static void
serve_one(int fd)
{
char req[262144], reply[2048];
char *body;
const char *p;
int id = -1;
if (read_http(fd, req, sizeof(req)) != 0)
return;
body = strstr(req, "\r\n\r\n");
body = body != NULL ? body + 4 : req;
/* the config's header has to arrive: without it, no tools */
if (strstr(req, "Authorization: Bearer test") == NULL) {
(void)send_reply(fd, "", "application/json",
"{\"error\":\"no token\"}");
return;
}
p = strstr(body, "\"id\":");
if (p != NULL)
id = atoi(p + 5);
if (id < 0) {
(void)send_reply(fd, "", "application/json", "");
return;
}
if (strstr(body, "initialize") != NULL) {
snprintf(reply, sizeof(reply), "{\"jsonrpc\":\"2.0\",\"id\":%d,"
"\"result\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":"
"{\"tools\":{}},\"serverInfo\":{\"name\":\"fake\",\"version\":\"1\"}}}",
id);
(void)send_reply(fd, "Mcp-Session-Id: sess-1\r\n",
"application/json", reply);
} else if (strstr(body, "tools/list") != NULL) {
snprintf(reply, sizeof(reply), "{\"jsonrpc\":\"2.0\",\"id\":%d,"
"\"result\":{\"tools\":[{\"name\":\"http_tool\",\"description\":"
"\"over http\",\"inputSchema\":{\"type\":\"object\","
"\"properties\":{}}}]}}", id);
(void)send_reply(fd, "", "application/json", reply);
} else if (strstr(body, "tools/call") != NULL) {
char ev[2048];
/* the answer arrives as an SSE stream, as the transport allows */
snprintf(ev, sizeof(ev), "event: message\ndata: {\"jsonrpc\":"
"\"2.0\",\"id\":%d,\"result\":{\"content\":[{\"type\":"
"\"text\",\"text\":\"over http\"}]}}\n\n", id);
(void)send_reply(fd, "", "text/event-stream", ev);
} else {
snprintf(reply, sizeof(reply),
"{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{}}", id);
(void)send_reply(fd, "", "application/json", reply);
}
}
static pid_t
start_http_server(int *port)
{
int ls, one = 1;
struct sockaddr_in a;
socklen_t alen = sizeof(a);
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls < 0)
return -1;
(void)setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
memset(&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.sin_port = 0;
if (bind(ls, (struct sockaddr *)&a, sizeof(a)) != 0 ||
listen(ls, 8) != 0 ||
getsockname(ls, (struct sockaddr *)&a, &alen) != 0) {
close(ls);
return -1;
}
*port = (int)ntohs(a.sin_port);
{
pid_t pid = fork();
if (pid == 0) {
for (;;) {
int c = accept(ls, NULL, NULL);
if (c < 0)
_exit(0);
serve_one(c);
close(c);
}
}
close(ls);
return pid;
}
}
int
main(void)
{
@@ -101,6 +265,62 @@ main(void)
sp_buf_free(&err);
snprintf(cmd, sizeof(cmd), "rm -rf '%s'", dir);
(void)system(cmd);
/* ---- the same plugin against a server reached over HTTP ---- */
{
struct sp_config conf;
struct sp_registry reg2;
struct sp_agent ag2;
struct sp_host *host2;
struct sp_buf err2;
int port = 0;
pid_t pid;
unsetenv("SPLINTER_MCP_CMD");
pid = start_http_server(&port);
CHECK(pid > 0 && port > 0);
if (pid > 0) {
memset(&reg2, 0, sizeof(reg2));
memset(&ag2, 0, sizeof(ag2));
sp_config_init(&conf);
conf.nmcp = 1;
snprintf(conf.mcp[0].id, sizeof(conf.mcp[0].id),
"junction");
snprintf(conf.mcp[0].url, sizeof(conf.mcp[0].url),
"http://127.0.0.1:%d/mcp", port);
snprintf(conf.mcp[0].header,
sizeof(conf.mcp[0].header),
"Authorization: Bearer test");
conf.mcp[0].enabled = 1;
CHECK(sp_buf_init(&err2) == 0);
host2 = sp_host_new(&reg2, &ag2, NULL);
CHECK(host2 != NULL);
if (host2 != NULL) {
sp_host_set_config(host2, &conf);
CHECK(sp_plugin_load(host2, "plugins/mcp/mcp.so",
&err2) == 0);
if (err2.len > 0)
fprintf(stderr, "http load: %s\n", err2.p);
t = sp_registry_find(&reg2, "mcp_http_tool");
CHECK(t != NULL);
if (t != NULL) {
struct sp_buf out2;
CHECK(sp_buf_init(&out2) == 0);
CHECK(t->run("{}", &out2, t->ctx) == 0);
CHECK(out2.p != NULL &&
strcmp(out2.p, "over http") == 0);
sp_buf_free(&out2);
}
sp_host_free(host2);
}
sp_buf_free(&err2);
(void)kill(pid, SIGTERM);
(void)waitpid(pid, NULL, 0);
}
}
if (failures == 0)
printf("test_mcpclient: ok\n");
return failures == 0 ? 0 : 1;