Files
splinter/tests/test_mcpclient.c
T
lotherkandClaude Opus 5.5 05c8d936e7 anthropic transport, provider usage APIs, endpoints as /v1 base
- kind = anthropic: the Messages API over curl, OAuth tokens (sk-ant-oat)
  as Bearer with the oauth beta, tool_use/tool_result blocks.
- --doctor spends no tokens: it asks /models and the provider's own usage
  route (ollama /api/balance, opencode go /v1/usage) instead of a tiny turn;
  cli providers are only checked for the program. /usage shows the same
  provider figures, cached for a minute.
- endpoint names the API base (https://host/v1); sp_endpoint_url() builds
  chat/completions (default), messages, models and usage from it. A full
  route is still accepted and cut back to the base.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:35:41 +00:00

346 lines
9.2 KiB
C

/*
* splinter -- the MCP client plugin against a server that talks big.
*
* The failures it guards against, as they were found: a reply longer than the
* client's 16 KiB line buffer was split into pieces that never parsed, a reply
* 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 <time.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;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
static const char *server_sh =
"#!/bin/sh\n"
"big() { head -c \"$1\" /dev/zero | tr '\\000' x; }\n"
"while IFS= read -r line; do\n"
" id=$(printf '%s' \"$line\" | sed -n 's/.*\"id\": *\\([0-9]*\\).*/\\1/p')\n"
" [ -n \"$id\" ] || continue\n"
" case \"$line\" in\n"
" *'\"initialize\"'*)\n"
" printf '{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\\n' \"$id\" ;;\n"
" *'\"tools/list\"'*)\n"
" d=$(big 40000)\n"
" printf '{\"jsonrpc\":\"2.0\",\"method\":\"notifications/x\"}\\n"
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[{\"name\":\"big\","
"\"description\":\"%s\",\"inputSchema\":{\"type\":\"object\","
"\"properties\":{}}}]}}\\n' \"$id\" \"$d\" ;;\n"
" *'\"tools/call\"'*)\n"
" t=$(big 100000)\n"
" printf '{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":"
"[{\"type\":\"text\",\"text\":\"the word \\\\\"error\\\\\" then %s\"}]}}\\n'"
" \"$id\" \"$t\" ;;\n"
" *) printf '{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\\n' \"$id\" ;;\n"
" 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;
}
}
/* the servers connect in the background: wait for a tool to appear */
static const struct sp_tool *
wait_tool(struct sp_registry *r, const char *name)
{
int k;
for (k = 0; k < 100; k++) {
const struct sp_tool *t = sp_registry_find(r, name);
struct timespec ts = { 0, 100000000L };
if (t != NULL)
return t;
nanosleep(&ts, NULL);
}
return NULL;
}
int
main(void)
{
char dir[] = "/var/tmp/splinter-mcpc-XXXXXX";
char path[600], cmd[700];
struct sp_registry reg;
struct sp_agent ag;
struct sp_host *host;
struct sp_buf err, out;
const struct sp_tool *t;
FILE *f;
CHECK(mkdtemp(dir) != NULL);
snprintf(path, sizeof(path), "%s/server.sh", dir);
f = fopen(path, "w");
CHECK(f != NULL);
if (f == NULL)
return 1;
fputs(server_sh, f);
fclose(f);
(void)chmod(path, 0755);
(void)setenv("SPLINTER_MCP_CMD", path, 1);
memset(&reg, 0, sizeof(reg));
memset(&ag, 0, sizeof(ag));
CHECK(sp_buf_init(&err) == 0);
CHECK(sp_buf_init(&out) == 0);
host = sp_host_new(&reg, &ag, NULL);
CHECK(host != NULL);
if (host == NULL)
return 1;
CHECK(sp_plugin_load(host, "plugins/mcp/mcp.so", &err) == 0);
if (err.len > 0)
fprintf(stderr, "load: %s\n", err.p);
/* a 40 KiB tools/list, behind a notification in the same write */
t = wait_tool(&reg, "mcp_big");
CHECK(t != NULL);
if (t != NULL) {
CHECK(strlen(t->description) == 40000);
/* a 100 KiB result that says "error" is a result, not an error */
CHECK(t->run("{}", &out, t->ctx) == 0);
CHECK(out.len > 100000);
CHECK(strstr(out.p, "the word \"error\" then xxx") != NULL);
CHECK(strncmp(out.p, "error:", 6) != 0);
}
sp_host_free(host);
sp_buf_free(&out);
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 = wait_tool(&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;
}