splinter: conversation, OpenAI adapter, end-to-end over HTTP

Splinter can now talk to a real endpoint: --endpoint plus --model shapes the
whole conversation into one chat/completions request and parses the reply back.

The seam changed from a raw string to the conversation, because a provider
adapter cannot invent history and the loop must not depend on vendor JSON:

- sp_conv: owned messages (role, name, call_id, content, raw tool_calls),
  geometric growth, trim from the front. Copy on push, so a compaction step
  must produce a new array - which is what makes it reviewable.
- sp_openai_request(): conversation + tool table -> JSON body.
- sp_openai_reply(): choices[0].message -> content + calls, and it keeps the
  provider's raw tool_calls array to hand back verbatim next round.
- provider error objects, empty choice lists, non-JSON bodies and empty bodies
  each produce a distinct, quoted error instead of a silent empty answer.
- transport_openai: curl, body through a temp file, status from curl's -w, key
  from the environment only.
- libmcp's JSON parser is vendored and instantiated exactly once (src/json.c);
  two instantiations would be a link error rather than a silent duplicate.

Proven end to end against a local stub speaking the real wire format:
request 1 (1 message, 2 tools, 448 bytes) -> tool_call for echo; splinter ran
the tool, request 2 (3 messages, 682 bytes) -> final text; the session log
holds user, observation, assistant.

Nine test binaries green, including test_openai (request shape, tool_call
parsing, raw array kept, four failing reply shapes) and test_conv.
This commit is contained in:
Konrad committed 2026-11-07 13:34:26 +00:00
1 parent 424209141b
commit 15581139d5
20 files changed
+2091 -351

No files matched your search

+15 -7
View File
@@ -11,7 +11,7 @@
CC ?= cc
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror -D_POSIX_C_SOURCE=200809L \
-fPIC -Iinclude -Isrc -Ivendor/netbsd-curses/libcurses
-fPIC -Iinclude -Isrc -Ivendor/libmcp -Ivendor/netbsd-curses/libcurses
LDFLAGS ?=
LIBS ?= -lpthread
PREFIX ?= /usr/local
@@ -21,14 +21,15 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
$(CURSES_DIR)/libterminfo/libterminfo.a
LIB = libsplinter.so
LIBOBJ = src/buf.o src/tool.o src/session.o src/transport.o \
src/transport_curl.o src/builtin.o src/agent.o src/theme.o \
src/palettes.o src/plugin.o
LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \
src/json.o src/openai.o src/transport_openai.o src/builtin.o \
src/agent.o src/theme.o src/palettes.o src/plugin.o
BIN = splinter
BINOBJ = src/main.o src/ui.o
PLUGIN = plugins/clock/clock.so
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_transport \
tests/test_agent tests/test_theme tests/test_plugin
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \
tests/test_transport tests/test_agent tests/test_openai \
tests/test_theme tests/test_plugin
RPATH = -Wl,-rpath,'$$ORIGIN'
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
@@ -65,7 +66,10 @@ src/buf.o: include/splinter.h
src/tool.o: include/splinter.h
src/session.o: include/splinter.h
src/transport.o: include/splinter.h
src/transport_curl.o: include/splinter.h
src/conv.o: include/splinter.h
src/json.o: vendor/libmcp/mcp.h
src/openai.o: include/splinter.h vendor/libmcp/mcp.h
src/transport_openai.o: include/splinter.h
src/builtin.o: include/splinter.h
src/theme.o: src/theme.h src/palettes.h include/splinter.h
src/palettes.o: src/palettes.h
@@ -83,6 +87,10 @@ tests/test_transport: tests/test_transport.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_transport.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_agent: tests/test_agent.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_agent.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_conv: tests/test_conv.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_conv.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_openai: tests/test_openai.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_openai.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_theme: tests/test_theme.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_theme.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN)
+19
View File
@@ -42,6 +42,10 @@ transport replays replies.
include/splinter.h the core interface
include/splinter_plugin.h plugin ABI and host API
src/plugin.c dlopen loader, widget registry, worker threads
src/conv.c the conversation (owned messages, no sharing)
src/openai.c request shaping + reply parsing, pure functions
src/transport_openai.c HTTP to /v1/chat/completions via curl(1)
src/json.c libmcp's JSON, instantiated once
src/ui.c curses UI: chat 3/4, sidebar 1/4, status bar
src/theme.c CDE palettes -> terminal colours
src/palettes.c generated from CDE's *.dp files
@@ -74,6 +78,21 @@ files. Roles are derived from the eight colour sets — darkest is the
background, lightest the foreground, the most saturated the accent. Default is
Delphinium. `--list-themes` prints the names, `--theme NAME` picks one.
## Talking to a model
```sh
./splinter -p "say hi" --endpoint http://127.0.0.1:8080/v1/chat/completions \
--model qwen2.5-coder-7b --api-key-env SPLINTER_API_KEY
```
The adapter shapes the whole conversation into one `chat/completions` request,
including the tool table, and parses `content` and `tool_calls` back. The
provider's raw `tool_calls` array is stored verbatim in the conversation and
sent back unchanged on the next round: re-encoding it would be a silently
different JSON. `content: null` is an empty answer, not an error; a reply
without choices, or a provider `error` object, is an error that quotes the
provider's own message.
## Limits, stated
- Tool arguments reach the tool as one string; each tool validates its own.
+50 -10
View File
@@ -76,24 +76,59 @@ const struct sp_tool *sp_registry_find(const struct sp_registry *,
size_t sp_registry_count(const struct sp_registry *);
void sp_registry_free(struct sp_registry *);
/* ---------------------------------------------------------- conversation */
struct sp_msg {
char *role; /* system | user | assistant | tool */
char *name; /* tool name when role is "tool" */
char *call_id; /* tool_call id, when role is "tool" */
char *content;
char *calls; /* raw tool_calls JSON of an assistant turn */
};
struct sp_conv {
struct sp_msg *v;
size_t n;
size_t cap;
};
void sp_conv_init(struct sp_conv *);
void sp_conv_free(struct sp_conv *);
int sp_conv_add(struct sp_conv *, const struct sp_msg *);
int sp_conv_push(struct sp_conv *, const char *role, const char *name,
const char *content);
size_t sp_conv_bytes(const struct sp_conv *);
int sp_conv_trim(struct sp_conv *, size_t keep_last);
/* ------------------------------------------------------------- transport */
struct sp_toolcall {
char *id;
char *name;
char *args; /* the arguments as a JSON text */
};
struct sp_reply {
long status;
char *body; /* malloc'd, NUL-terminated, may be "" */
long status;
char *content; /* assistant text, may be "" */
struct sp_toolcall *calls;
char *calls_json; /* the provider's own tool_calls array */
size_t ncalls;
};
/*
* A transport sends one request body and returns one reply. It never parses
* JSON or SSE: that keeps a mock, a curl adapter and any future provider on
* the same seam.
* A transport turns a whole conversation into one request and one reply. The
* seam is the conversation, not a raw string: a provider adapter cannot invent
* history, and the loop cannot depend on a vendor's JSON.
*/
struct sp_transport {
int (*send)(void *ctx, const char *req, struct sp_reply *out,
int (*send)(void *ctx, const struct sp_conv *, struct sp_reply *out,
struct sp_buf *err);
void *ctx;
};
void sp_reply_free(struct sp_reply *);
/* A deterministic in-process transport: replies are queued FIFO. */
struct sp_mock {
struct sp_reply *queue;
@@ -146,6 +181,7 @@ struct sp_agent {
struct sp_transport tr;
const struct sp_agent_config *cfg;
struct sp_session_info *sess;
struct sp_conv *conv; /* optional: history lives here */
struct sp_agent_stats stats;
};
@@ -155,10 +191,14 @@ int sp_agent_run(struct sp_agent *, const char *user_text,
/* builtin.c */
int sp_builtin_register(struct sp_registry *);
/* transport_curl.c */
struct sp_transport sp_curl_transport(const char *url, long timeout_s);
/* transport_openai.c -- OpenAI-compatible chat completions, via curl(1) */
struct sp_transport sp_openai_transport(const char *url, const char *model,
const char *api_key, const struct sp_registry *, long timeout_s);
/* transport.c */
void sp_reply_free(struct sp_reply *);
/* openai.c -- pure JSON shaping, testable without a network */
int sp_openai_request(const struct sp_conv *, const char *model,
const struct sp_registry *, struct sp_buf *out);
int sp_openai_reply(const char *json, struct sp_reply *out,
struct sp_buf *err);
#endif /* SPLINTER_H */
BIN
View File
Binary file not shown.
+101 -107
View File
@@ -4,21 +4,17 @@
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Wire protocol between harness and transport (deliberately tiny, so it can be
* tested with no network and no JSON parser; a provider adapter translates
* OpenAI's shape into this one and back):
* One turn: append the user message, ask the transport, run the tools it asks
* for, repeat until it answers or the step limit is hit. The conversation
* lives in sp_conv and survives the turn, so splinter is not an amnesiac
* one-shot.
*
* request "user <text>\n" first round of a turn
* "observe <tool> <output>\n" after a tool ran
* reply "answer <text>" the turn is done
* "tool <name> <arguments>" run this tool, then continue
*
* Invariants the loop enforces, in this order, before any tool runs:
* 1. the request fits the configured budget, otherwise the turn fails and
* Invariants, in this order, before any tool runs:
* 1. the conversation fits the byte budget, otherwise the turn fails and
* nothing is sent (never rely on the endpoint to truncate);
* 2. the tool exists in the registry, otherwise the model is told so;
* 3. the tool's authorization class is honoured; a denied tool is reported
* back as the observation, not silently skipped.
* 3. the tool's authorization class is honoured; a denial is reported back
* as the observation, not silently skipped.
*/
#include <stdio.h>
#include <stdlib.h>
@@ -26,18 +22,6 @@
#include "splinter.h"
static int
starts_with(const char *s, const char *prefix)
{
return strncmp(s, prefix, strlen(prefix)) == 0;
}
static const char *
after_prefix(const char *s, const char *prefix)
{
return s + strlen(prefix);
}
static int
ask_operator(struct sp_agent *a, const struct sp_tool *t, const char *args)
{
@@ -55,12 +39,37 @@ ask_operator(struct sp_agent *a, const struct sp_tool *t, const char *args)
return (line[0] == 'y' || line[0] == 'Y');
}
/* The observation is always written: an error is an observation too. */
static void
run_one_call(struct sp_agent *a, const struct sp_toolcall *call,
struct sp_buf *obs)
{
const struct sp_tool *t;
a->stats.tool_calls++;
t = sp_registry_find(a->reg, call->name);
if (t == NULL) {
sp_buf_printf(obs, "error: unknown tool '%s'", call->name);
return;
}
if (t->auth != SP_AUTH_READ && !a->cfg->autonomous &&
!ask_operator(a, t, call->args)) {
a->stats.denied++;
sp_buf_puts(obs, "error: denied by operator");
return;
}
if (t->run(call->args, obs, t->ctx) != 0)
sp_buf_printf(obs, "error: tool '%s' failed", call->name);
}
int
sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
struct sp_buf *err)
{
struct sp_buf payload, obs;
size_t step;
struct sp_conv local;
struct sp_conv *conv;
struct sp_buf obs;
size_t step, i;
int rc = -1;
if (a == NULL || a->reg == NULL || a->cfg == NULL)
@@ -68,124 +77,108 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
if (a->cfg->max_steps == 0)
return -1;
if (a->conv != NULL) {
conv = a->conv;
} else {
sp_conv_init(&local);
conv = &local;
}
sp_buf_clear(answer);
if (sp_buf_init(&payload) != 0 || sp_buf_init(&obs) != 0) {
if (sp_buf_init(&obs) != 0) {
sp_buf_puts(err, "agent: out of memory");
sp_buf_free(&payload);
if (conv == &local)
sp_conv_free(&local);
return -1;
}
if (sp_buf_puts(&payload, "user ") != 0 ||
sp_buf_puts(&payload, user_text != NULL ? user_text : "") != 0 ||
sp_buf_puts(&payload, "\n") != 0)
goto oom;
if (sp_conv_push(conv, "user", NULL, user_text) != 0) {
sp_buf_puts(err, "agent: out of memory");
goto out;
}
if (a->sess != NULL &&
sp_session_append(a->sess, "user", user_text, err) != 0)
goto out;
for (step = 0; step < a->cfg->max_steps; step++) {
struct sp_reply reply = { 0, NULL };
const char *rest, *sp;
const struct sp_tool *t;
char name[128];
const char *args;
size_t nlen;
struct sp_reply reply;
size_t sent;
if (a->cfg->max_bytes > 0 && payload.len > a->cfg->max_bytes) {
sp_buf_printf(err, "agent: request budget exceeded "
"(%zu > %zu bytes); nothing sent", payload.len,
memset(&reply, 0, sizeof(reply));
sent = sp_conv_bytes(conv);
if (a->cfg->max_bytes > 0 && sent > a->cfg->max_bytes) {
sp_buf_printf(err, "agent: conversation budget exceeded "
"(~%zu > %zu bytes); nothing sent", sent,
a->cfg->max_bytes);
goto out;
}
a->stats.bytes_sent += payload.len;
a->stats.bytes_sent += sent;
a->stats.steps++;
if (a->tr.send(a->tr.ctx, payload.p, &reply, err) != 0) {
free(reply.body);
if (a->tr.send(a->tr.ctx, conv, &reply, err) != 0) {
sp_reply_free(&reply);
goto out;
}
if (reply.status < 200 || reply.status > 299) {
sp_buf_printf(err, "agent: transport status %ld",
reply.status);
free(reply.body);
goto out;
}
if (reply.body == NULL) {
sp_buf_puts(err, "agent: empty reply");
sp_reply_free(&reply);
goto out;
}
if (starts_with(reply.body, "answer ")) {
rest = after_prefix(reply.body, "answer ");
if (sp_buf_puts(answer, rest) != 0) {
free(reply.body);
if (reply.ncalls == 0) {
const char *text = reply.content != NULL ?
reply.content : "";
if (sp_buf_puts(answer, text) != 0 ||
sp_conv_push(conv, "assistant", NULL, text) != 0) {
sp_reply_free(&reply);
goto oom;
}
if (a->sess != NULL &&
sp_session_append(a->sess, "assistant", rest,
sp_session_append(a->sess, "assistant", text,
err) != 0) {
free(reply.body);
sp_reply_free(&reply);
goto out;
}
free(reply.body);
sp_reply_free(&reply);
rc = 0;
goto out;
}
if (!starts_with(reply.body, "tool ")) {
sp_buf_puts(err, "agent: reply is neither answer nor "
"tool");
free(reply.body);
goto out;
}
rest = after_prefix(reply.body, "tool ");
sp = strchr(rest, ' ');
if (sp == NULL) {
nlen = strlen(rest);
args = "";
} else {
nlen = (size_t)(sp - rest);
args = sp + 1;
}
if (nlen >= sizeof(name)) {
sp_buf_puts(err, "agent: tool name too long");
free(reply.body);
goto out;
}
memcpy(name, rest, nlen);
name[nlen] = '\0';
{
struct sp_msg am;
a->stats.tool_calls++;
t = sp_registry_find(a->reg, name);
sp_buf_clear(&obs);
if (t == NULL) {
if (sp_buf_printf(&obs, "error: unknown tool '%s'",
name) != 0) {
free(reply.body);
goto oom;
}
} else if (t->auth != SP_AUTH_READ && !a->cfg->autonomous &&
!ask_operator(a, t, args)) {
a->stats.denied++;
if (sp_buf_puts(&obs, "error: denied by operator") != 0) {
free(reply.body);
goto oom;
}
} else if (t->run(args, &obs, t->ctx) != 0) {
if (sp_buf_printf(&obs, "error: tool '%s' failed",
name) != 0) {
free(reply.body);
memset(&am, 0, sizeof(am));
am.role = "assistant";
am.content = reply.content;
am.calls = reply.calls_json;
if (sp_conv_add(conv, &am) != 0) {
sp_reply_free(&reply);
goto oom;
}
}
free(reply.body);
for (i = 0; i < reply.ncalls; i++) {
struct sp_msg tm;
if (a->sess != NULL &&
sp_session_append(a->sess, "observation", obs.p, err) != 0)
goto out;
sp_buf_clear(&payload);
if (sp_buf_printf(&payload, "observe %s %s\n", name, obs.p) != 0)
goto oom;
sp_buf_clear(&obs);
run_one_call(a, &reply.calls[i], &obs);
memset(&tm, 0, sizeof(tm));
tm.role = "tool";
tm.name = reply.calls[i].name;
tm.call_id = reply.calls[i].id;
tm.content = obs.p;
if (sp_conv_add(conv, &tm) != 0) {
sp_reply_free(&reply);
goto oom;
}
if (a->sess != NULL &&
sp_session_append(a->sess, "observation", obs.p,
err) != 0) {
sp_reply_free(&reply);
goto out;
}
}
sp_reply_free(&reply);
}
sp_buf_printf(err, "agent: step limit (%zu) reached without an answer",
@@ -195,7 +188,8 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
oom:
sp_buf_puts(err, "agent: out of memory");
out:
sp_buf_free(&payload);
sp_buf_free(&obs);
if (conv == &local)
sp_conv_free(&local);
return rc;
}
+132
View File
@@ -0,0 +1,132 @@
/*
* splinter -- the conversation.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The conversation is the harness's memory inside one turn and across turns.
* It is a plain array of owned messages: no sharing, no copy-on-write, no
* pointers into other messages. A compaction step therefore has to produce a
* new array, which is exactly what makes it reviewable.
*/
#include <stdlib.h>
#include <string.h>
#include "splinter.h"
void
sp_conv_init(struct sp_conv *c)
{
memset(c, 0, sizeof(*c));
}
void
sp_conv_free(struct sp_conv *c)
{
size_t i;
if (c == NULL)
return;
for (i = 0; i < c->n; i++) {
free(c->v[i].role);
free(c->v[i].name);
free(c->v[i].call_id);
free(c->v[i].content);
free(c->v[i].calls);
}
free(c->v);
memset(c, 0, sizeof(*c));
}
static char *
dup_or_empty(const char *s)
{
if (s == NULL)
s = "";
return strdup(s);
}
int
sp_conv_add(struct sp_conv *c, const struct sp_msg *in)
{
struct sp_msg *m;
if (c == NULL || in == NULL || in->role == NULL)
return -1;
if (c->n == c->cap) {
size_t ncap = c->cap == 0 ? 8 : c->cap * 2;
struct sp_msg *nv = realloc(c->v, ncap * sizeof(*nv));
if (nv == NULL)
return -1;
c->v = nv;
c->cap = ncap;
}
m = &c->v[c->n];
m->role = dup_or_empty(in->role);
m->name = in->name != NULL ? dup_or_empty(in->name) : NULL;
m->call_id = in->call_id != NULL ? dup_or_empty(in->call_id) : NULL;
m->content = dup_or_empty(in->content);
m->calls = in->calls != NULL ? dup_or_empty(in->calls) : NULL;
if (m->role == NULL || m->content == NULL ||
(in->name != NULL && m->name == NULL) ||
(in->call_id != NULL && m->call_id == NULL) ||
(in->calls != NULL && m->calls == NULL)) {
free(m->role);
free(m->name);
free(m->call_id);
free(m->content);
free(m->calls);
return -1;
}
c->n++;
return 0;
}
int
sp_conv_push(struct sp_conv *c, const char *role, const char *name,
const char *content)
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = (char *)role;
m.name = (char *)name;
m.content = (char *)content;
return sp_conv_add(c, &m);
}
size_t
sp_conv_bytes(const struct sp_conv *c)
{
size_t i, total = 0;
for (i = 0; i < c->n; i++) {
total += c->v[i].role != NULL ? strlen(c->v[i].role) : 0;
total += c->v[i].name != NULL ? strlen(c->v[i].name) : 0;
total += c->v[i].content != NULL ? strlen(c->v[i].content) : 0;
total += c->v[i].calls != NULL ? strlen(c->v[i].calls) : 0;
total += 16; /* JSON scaffolding, estimated */
}
return total;
}
int
sp_conv_trim(struct sp_conv *c, size_t keep_last)
{
size_t drop, i;
if (c == NULL || keep_last >= c->n)
return 0;
drop = c->n - keep_last;
for (i = 0; i < drop; i++) {
free(c->v[i].role);
free(c->v[i].name);
free(c->v[i].call_id);
free(c->v[i].content);
free(c->v[i].calls);
}
memmove(c->v, c->v + drop, (c->n - drop) * sizeof(*c->v));
c->n -= drop;
return 0;
}
+12
View File
@@ -0,0 +1,12 @@
/*
* splinter -- the JSON implementation, instantiated once.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* libmcp's parser is header-only: exactly one translation unit defines
* MCP_IMPLEMENTATION, every other one only sees the declarations. Doing it
* twice is a link error, not a subtle bug, which is the point.
*/
#define MCP_IMPLEMENTATION
#include "mcp.h"
+70 -31
View File
@@ -25,7 +25,10 @@ usage(FILE *f)
fprintf(f,
"usage: splinter [options]\n\n"
" -p, --prompt TEXT run one turn with TEXT and exit\n"
" --endpoint URL transport: POST the line protocol to URL\n"
" --endpoint URL transport: OpenAI-compatible chat endpoint\n"
" --model NAME model name for --endpoint (required)\n"
" --api-key-env VAR read the API key from VAR (default\n"
" SPLINTER_API_KEY; missing means no auth)\n"
" --script FILE transport: replay replies from FILE, one\n"
" per line (no network; for tests and demos)\n"
" --plugin PATH load a plugin (.so) before the first turn\n"
@@ -53,30 +56,33 @@ need_value(int argc, int i, const char *flag)
return 1;
}
struct script_ctx {
FILE *f;
int empty;
};
/*
* A script file is one reply per line, in the mock transport's own protocol
* ("answer ...", "tool <name> <args>"). Loading it up front means the whole
* turn is deterministic and re-runnable, with no network anywhere.
*/
static int
script_send(void *ctx, const char *req, struct sp_reply *out, struct sp_buf *err)
load_script(struct sp_mock *m, const char *path, struct sp_buf *err)
{
struct script_ctx *s = ctx;
char line[8192];
FILE *f;
char line[8192];
(void)req;
if (fgets(line, sizeof(line), s->f) == NULL) {
s->empty = 1;
sp_buf_puts(err, "script: no reply left");
f = fopen(path, "r");
if (f == NULL) {
sp_buf_printf(err, "%s: %s", path, strerror(errno));
return -1;
}
line[strcspn(line, "\n")] = '\0';
out->status = 200;
out->body = strdup(line);
if (out->body == NULL) {
sp_buf_puts(err, "script: out of memory");
return -1;
while (fgets(line, sizeof(line), f) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (line[0] == '\0' || line[0] == '#')
continue;
if (sp_mock_push(m, 200, line) != 0) {
fclose(f);
sp_buf_puts(err, "script: out of memory");
return -1;
}
}
fclose(f);
return 0;
}
@@ -90,9 +96,11 @@ main(int argc, char **argv)
struct sp_buf answer = { 0 }, err = { 0 };
const char *prompt = NULL, *endpoint = NULL, *script = NULL;
const char *sessdir = NULL, *sessid = NULL, *theme = NULL;
const char *model = NULL, *key_env = "SPLINTER_API_KEY";
int list_themes = 0;
char default_id[64];
struct script_ctx sctx = { NULL, 0 };
struct sp_mock mock;
int have_mock = 0;
int i, rc, chatmode = 0;
const char *plugins[16];
size_t nplugins = 0;
@@ -120,6 +128,14 @@ main(int argc, char **argv)
if (!need_value(argc, i, argv[i]))
return 2;
endpoint = argv[++i];
} else if (!strcmp(argv[i], "--model")) {
if (!need_value(argc, i, argv[i]))
return 2;
model = argv[++i];
} else if (!strcmp(argv[i], "--api-key-env")) {
if (!need_value(argc, i, argv[i]))
return 2;
key_env = argv[++i];
} else if (!strcmp(argv[i], "--script")) {
if (!need_value(argc, i, argv[i]))
return 2;
@@ -217,16 +233,39 @@ main(int argc, char **argv)
ag.sess = &sess;
if (script != NULL) {
sctx.f = fopen(script, "r");
if (sctx.f == NULL) {
fprintf(stderr, "splinter: %s: %s\n", script,
strerror(errno));
if (sp_mock_init(&mock) != 0) {
fprintf(stderr, "splinter: out of memory\n");
return 3;
}
ag.tr.send = script_send;
ag.tr.ctx = &sctx;
have_mock = 1;
if (load_script(&mock, script, &err) != 0) {
fprintf(stderr, "splinter: %s\n",
err.p != NULL ? err.p : "script");
return 3;
}
ag.tr = sp_mock_transport(&mock);
} else {
ag.tr = sp_curl_transport(endpoint, 120);
const char *key = NULL;
if (model == NULL) {
fprintf(stderr, "splinter: --endpoint needs --model\n");
return 2;
}
if (getenv(key_env) != NULL)
key = getenv(key_env);
ag.tr = sp_openai_transport(endpoint, model, key, &reg, 180);
}
{
static struct sp_conv conv;
sp_conv_init(&conv);
if (cfg.system_prompt != NULL &&
sp_conv_push(&conv, "system", NULL, cfg.system_prompt) != 0) {
fprintf(stderr, "splinter: out of memory\n");
return 3;
}
ag.conv = &conv;
}
cfg.approval_in = stdin;
@@ -260,8 +299,8 @@ main(int argc, char **argv)
if (chatmode) {
rc = sp_ui_run(&ag, endpoint, theme, host);
if (sctx.f != NULL)
fclose(sctx.f);
if (have_mock)
sp_mock_free(&mock);
sp_host_free(host);
sp_buf_free(&answer);
sp_buf_free(&err);
@@ -275,8 +314,8 @@ main(int argc, char **argv)
} else {
fprintf(stderr, "splinter: %s\n", err.p ? err.p : "turn failed");
}
if (sctx.f != NULL)
fclose(sctx.f);
if (have_mock)
sp_mock_free(&mock);
sp_host_free(host);
sp_buf_free(&answer);
sp_buf_free(&err);
+234
View File
@@ -0,0 +1,234 @@
/*
* splinter -- OpenAI-compatible request/reply shaping.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Two pure functions, so both directions can be tested without a network:
*
* sp_openai_request() conversation + tool table -> the JSON body
* sp_openai_reply() the endpoint's JSON -> sp_reply
*
* What is deliberately not done here: no retries, no streaming, no guessing.
* A reply without a usable choice is an error with the provider's own message
* in it, because "the model said nothing" and "the endpoint is broken" are
* different facts and the caller has to be able to tell them apart.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "splinter.h"
#include "mcp.h"
static int
put_field(struct sp_buf *b, const char *key, const char *value)
{
if (sp_buf_printf(b, "\"%s\":", key) != 0 ||
sp_buf_puts(b, "\"") != 0 ||
sp_json_escape(b, value != NULL ? value : "") != 0 ||
sp_buf_puts(b, "\"") != 0)
return -1;
return 0;
}
int
sp_openai_request(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, struct sp_buf *out)
{
size_t i;
sp_buf_clear(out);
if (sp_buf_puts(out, "{\"model\":") != 0 || sp_buf_puts(out, "\"") != 0 ||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
sp_buf_puts(out, "\",\"stream\":false,\"messages\":[") != 0)
return -1;
for (i = 0; i < conv->n; i++) {
const struct sp_msg *m = &conv->v[i];
if (i > 0 && sp_buf_puts(out, ",") != 0)
return -1;
if (sp_buf_puts(out, "{") != 0 ||
put_field(out, "role", m->role) != 0)
return -1;
if (m->call_id != NULL) {
if (sp_buf_puts(out, ",") != 0 ||
put_field(out, "tool_call_id", m->call_id) != 0)
return -1;
}
if (m->name != NULL && m->call_id == NULL) {
if (sp_buf_puts(out, ",") != 0 ||
put_field(out, "name", m->name) != 0)
return -1;
}
if (m->content != NULL) {
if (sp_buf_puts(out, ",") != 0 ||
put_field(out, "content", m->content) != 0)
return -1;
}
if (m->calls != NULL && *m->calls != '\0') {
if (sp_buf_printf(out, ",\"tool_calls\":%s", m->calls) != 0)
return -1;
}
if (sp_buf_puts(out, "}") != 0)
return -1;
}
/* tools: name, description and an open parameter object */
if (sp_buf_puts(out, "],\"tools\":[") != 0)
return -1;
for (i = 0; i < reg->len; i++) {
const struct sp_tool *t = &reg->tools[i];
if (i > 0 && sp_buf_puts(out, ",") != 0)
return -1;
if (sp_buf_puts(out, "{\"type\":\"function\",\"function\":{") != 0 ||
put_field(out, "name", t->name) != 0 ||
sp_buf_puts(out, ",") != 0 ||
put_field(out, "description", t->description) != 0 ||
sp_buf_puts(out, ",\"parameters\":{\"type\":\"object\","
"\"properties\":{},\"additionalProperties\":true}}}") != 0)
return -1;
}
return sp_buf_puts(out, "]}");
}
/*
* Extract the raw tool_calls array as text, so a later request can hand the
* provider back exactly what it sent: re-encoding parsed calls would be a
* second, silently different JSON.
*/
static char *
raw_calls(const char *json, const char *key)
{
const char *p = strstr(json, key);
const char *start;
int depth = 0, in_str = 0, esc = 0;
size_t len;
if (p == NULL)
return NULL;
start = strchr(p + strlen(key), '[');
if (start == NULL)
return NULL;
for (p = start; *p != '\0'; p++) {
if (esc) {
esc = 0;
continue;
}
if (*p == '\\') {
esc = 1;
continue;
}
if (*p == '"') {
in_str = !in_str;
continue;
}
if (in_str)
continue;
if (*p == '[')
depth++;
else if (*p == ']') {
depth--;
if (depth == 0) {
len = (size_t)(p - start) + 1;
return strndup(start, len);
}
}
}
return NULL;
}
static const char *
jstr(const mcp_json *v)
{
return v != NULL ? mcp_json_string(v) : NULL;
}
int
sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
{
mcp_json *v;
const mcp_json *choices, *choice, *message, *calls, *content;
const mcp_json *error;
const char *text;
memset(out, 0, sizeof(*out));
out->status = 200;
if (json == NULL || *json == '\0') {
sp_buf_puts(err, "openai: empty body");
return -1;
}
v = mcp_parse(json);
if (v == NULL) {
sp_buf_printf(err, "openai: reply is not JSON: %.120s", json);
return -1;
}
error = mcp_arg(v, "error");
if (error != NULL) {
text = mcp_arg_string(error, "message");
sp_buf_printf(err, "openai: provider error: %s",
text != NULL ? text : "(no message)");
mcp_json_free(v);
return -1;
}
choices = mcp_arg(v, "choices");
if (choices == NULL || mcp_array_len(choices) == 0) {
sp_buf_printf(err, "openai: no choices in reply: %.160s", json);
mcp_json_free(v);
return -1;
}
choice = mcp_array_at(choices, 0);
message = choice != NULL ? mcp_arg(choice, "message") : NULL;
if (message == NULL) {
sp_buf_puts(err, "openai: choice without a message");
mcp_json_free(v);
return -1;
}
content = mcp_arg(message, "content");
out->content = strdup(jstr(content) != NULL ? jstr(content) : "");
if (out->content == NULL) {
mcp_json_free(v);
return -1;
}
calls = mcp_arg(message, "tool_calls");
if (calls != NULL && mcp_array_len(calls) > 0) {
size_t i, n = mcp_array_len(calls);
out->calls = calloc(n, sizeof(*out->calls));
if (out->calls == NULL) {
sp_reply_free(out);
mcp_json_free(v);
return -1;
}
for (i = 0; i < n; i++) {
const mcp_json *c = mcp_array_at(calls, i);
const mcp_json *fn = mcp_arg(c, "function");
out->calls[i].id = strdup(jstr(mcp_arg(c, "id")) != NULL ?
jstr(mcp_arg(c, "id")) : "");
out->calls[i].name = strdup(jstr(mcp_arg(fn, "name")) !=
NULL ? jstr(mcp_arg(fn, "name")) : "");
out->calls[i].args = strdup(jstr(mcp_arg(fn, "arguments")) !=
NULL ? jstr(mcp_arg(fn, "arguments")) : "");
if (out->calls[i].id == NULL || out->calls[i].name == NULL ||
out->calls[i].args == NULL) {
out->ncalls = i + 1;
sp_reply_free(out);
mcp_json_free(v);
return -1;
}
}
out->ncalls = n;
out->calls_json = raw_calls(json, "\"tool_calls\"");
}
mcp_json_free(v);
return 0;
}
+138 -60
View File
@@ -1,14 +1,21 @@
/*
* splinter -- deterministic in-process transport.
* splinter -- the deterministic mock transport.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The mock is what makes the loop testable without a network, a key or a paid
* endpoint. Replies are queued FIFO and handed out in order; the last request
* is kept so a test can assert on what the harness actually sent.
* Replies are queued and handed out in order; the last request stays readable
* so a test can assert what the loop actually sent. The wire form is the
* harness's own line protocol:
*
* user <text> the conversation's last message is a user turn
* observe <tool> <text> the last message is a tool observation
* answer <text> reply: the turn is done
* tool <name> <args> reply: run this tool, then continue
*
* That form exists for exactly one reason: a test can express a whole turn in
* a text file -- no network, no key, no model.
*/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
@@ -17,6 +24,8 @@
int
sp_mock_init(struct sp_mock *m)
{
if (m == NULL)
return -1;
memset(m, 0, sizeof(*m));
return sp_buf_init(&m->last_request);
}
@@ -24,57 +33,149 @@ sp_mock_init(struct sp_mock *m)
int
sp_mock_push(struct sp_mock *m, long status, const char *body)
{
size_t ncap;
void *np;
char *copy;
struct sp_reply *r;
if (m == NULL)
return -1;
if (m->len == m->cap) {
ncap = m->cap ? m->cap * 2 : 4;
np = realloc(m->queue, ncap * sizeof(*m->queue));
if (np == NULL)
size_t ncap = m->cap == 0 ? 4 : m->cap * 2;
struct sp_reply *nq = realloc(m->queue, ncap * sizeof(*nq));
if (nq == NULL)
return -1;
m->queue = np;
m->queue = nq;
m->cap = ncap;
}
copy = strdup(body != NULL ? body : "");
if (copy == NULL)
r = &m->queue[m->len];
memset(r, 0, sizeof(*r));
r->status = status;
r->content = strdup(body != NULL ? body : "");
if (r->content == NULL)
return -1;
m->queue[m->len].status = status;
m->queue[m->len].body = copy;
m->len++;
return 0;
}
static int
mock_send(void *ctx, const char *req, struct sp_reply *out, struct sp_buf *err)
void
sp_reply_free(struct sp_reply *r)
{
struct sp_mock *m = ctx;
size_t i;
sp_buf_clear(&m->last_request);
if (sp_buf_puts(&m->last_request, req) != 0) {
sp_buf_puts(err, "mock: out of memory");
return -1;
if (r == NULL)
return;
free(r->content);
for (i = 0; i < r->ncalls; i++) {
free(r->calls[i].id);
free(r->calls[i].name);
free(r->calls[i].args);
}
m->requests++;
if (m->head >= m->len) {
out->status = 0;
out->body = strdup("");
if (out->body == NULL) {
sp_buf_puts(err, "mock: out of memory");
free(r->calls);
memset(r, 0, sizeof(*r));
}
void
sp_mock_free(struct sp_mock *m)
{
size_t i;
if (m == NULL)
return;
for (i = m->head; i < m->len; i++) {
free(m->queue[i].content);
free(m->queue[i].calls);
}
free(m->queue);
sp_buf_free(&m->last_request);
memset(m, 0, sizeof(*m));
}
/*
* "answer ..." is text, "tool ..." is one call. Anything else is an error: a
* transport that guesses is a transport that hides a broken endpoint.
*/
static int
parse_line(char *line, struct sp_reply *out, struct sp_buf *err)
{
line[strcspn(line, "\r\n")] = '\0';
if (strncmp(line, "answer ", 7) == 0) {
out->content = strdup(line + 7);
return out->content != NULL ? 0 : -1;
}
if (strncmp(line, "tool ", 5) == 0) {
char *rest = line + 5;
char *sp = strchr(rest, ' ');
struct sp_toolcall *c = calloc(1, sizeof(*c));
if (sp != NULL)
*sp++ = '\0';
if (c == NULL)
return -1;
c->id = strdup("call-0");
c->name = strdup(rest);
c->args = strdup(sp != NULL ? sp : "");
if (c->id == NULL || c->name == NULL || c->args == NULL) {
free(c->id);
free(c->name);
free(c->args);
free(c);
return -1;
}
sp_buf_printf(err, "mock: no queued reply for request %zu",
m->requests);
out->calls = c;
out->ncalls = 1;
out->content = strdup("");
return out->content != NULL ? 0 : -1;
}
sp_buf_printf(err, "mock: reply is neither answer nor tool: %s", line);
return -1;
}
static int
mock_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
struct sp_buf *err)
{
struct sp_mock *m = ctx;
const struct sp_msg *last;
if (m == NULL || conv == NULL || out == NULL)
return -1;
m->requests++;
if (m->head >= m->len) {
sp_buf_puts(err, "mock: no queued reply left");
return -1;
}
last = conv->n > 0 ? &conv->v[conv->n - 1] : NULL;
sp_buf_clear(&m->last_request);
if (last != NULL && strcmp(last->role, "tool") == 0)
sp_buf_printf(&m->last_request, "observe %s %s\n",
last->name != NULL ? last->name : "?",
last->content != NULL ? last->content : "");
else if (last != NULL)
sp_buf_printf(&m->last_request, "user %s\n",
last->content != NULL ? last->content : "");
else
sp_buf_puts(&m->last_request, "user \n");
out->status = m->queue[m->head].status;
out->body = strdup(m->queue[m->head].body);
if (out->body == NULL) {
sp_buf_puts(err, "mock: out of memory");
return -1;
if (out->status < 200 || out->status > 299) {
out->content = strdup(m->queue[m->head].content);
m->head++;
return out->content != NULL ? 0 : -1;
}
{
char *body = strdup(m->queue[m->head].content);
m->head++;
if (body == NULL)
return -1;
{
int rc = parse_line(body, out, err);
free(body);
return rc;
}
}
m->head++;
return 0;
}
struct sp_transport
@@ -86,26 +187,3 @@ sp_mock_transport(struct sp_mock *m)
t.ctx = m;
return t;
}
void
sp_mock_free(struct sp_mock *m)
{
size_t i;
for (i = 0; i < m->len; i++)
free(m->queue[i].body);
free(m->queue);
sp_buf_free(&m->last_request);
memset(m, 0, sizeof(*m));
}
void
sp_reply_free(struct sp_reply *r);
void
sp_reply_free(struct sp_reply *r)
{
free(r->body);
r->body = NULL;
r->status = 0;
}
-122
View File
@@ -1,122 +0,0 @@
/*
* splinter -- HTTP transport through the curl binary.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* C99/POSIX gives no portable HTTPS client. Rather than link a TLS stack into
* the harness, this adapter runs curl(1) and speaks the same line protocol as
* the mock. Consequences, stated rather than discovered later:
* - the request body travels through a temp file, never through the shell
* command line, so quoting cannot corrupt it;
* - the HTTP status is taken from curl's own -w output;
* - a failed transfer is an error, never an empty success.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "splinter.h"
struct curl_ctx {
char url[512];
long timeout_s;
};
static int
read_all(FILE *f, struct sp_buf *out)
{
char chunk[4096];
size_t got;
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) {
if (sp_buf_add(out, chunk, got) != 0)
return -1;
}
return ferror(f) ? -1 : 0;
}
static int
curl_send(void *ctx, const char *req, struct sp_reply *out, struct sp_buf *err)
{
struct curl_ctx *c = ctx;
struct sp_buf cmd, raw;
char path[] = "/tmp/splinter-req-XXXXXX";
int fd, rc = -1;
FILE *p;
ssize_t w;
size_t n;
char *nl;
long status;
fd = mkstemp(path);
if (fd < 0) {
sp_buf_printf(err, "curl: mkstemp: %s", strerror(errno));
return -1;
}
n = strlen(req);
w = write(fd, req, n);
close(fd);
if (w < 0 || (size_t)w != n) {
sp_buf_printf(err, "curl: short write: %s", strerror(errno));
unlink(path);
return -1;
}
if (sp_buf_init(&cmd) != 0 || sp_buf_init(&raw) != 0) {
sp_buf_puts(err, "curl: out of memory");
unlink(path);
return -1;
}
sp_buf_printf(&cmd, "curl -sS -m %ld -X POST -H 'Content-Type: "
"text/plain' --data-binary @%s -w '\\n%%{http_code}' '%s'",
c->timeout_s, path, c->url);
p = popen(cmd.p, "r");
if (p == NULL) {
sp_buf_printf(err, "curl: popen: %s", strerror(errno));
goto out;
}
if (read_all(p, &raw) != 0) {
sp_buf_puts(err, "curl: read failed");
pclose(p);
goto out;
}
if (pclose(p) != 0) {
sp_buf_printf(err, "curl: transfer failed for %s", c->url);
goto out;
}
if (raw.len < 2 || (nl = strrchr(raw.p, '\n')) == NULL) {
sp_buf_puts(err, "curl: unparseable reply (no status line)");
goto out;
}
status = strtol(nl + 1, NULL, 10);
*nl = '\0';
out->status = status;
out->body = strdup(raw.p);
if (out->body == NULL) {
sp_buf_puts(err, "curl: out of memory");
goto out;
}
rc = 0;
out:
sp_buf_free(&cmd);
sp_buf_free(&raw);
unlink(path);
return rc;
}
struct sp_transport
sp_curl_transport(const char *url, long timeout_s)
{
static struct curl_ctx ctx;
struct sp_transport t;
snprintf(ctx.url, sizeof(ctx.url), "%s", url);
ctx.timeout_s = timeout_s > 0 ? timeout_s : 120;
t.send = curl_send;
t.ctx = &ctx;
return t;
}
+151
View File
@@ -0,0 +1,151 @@
/*
* splinter -- HTTP transport for OpenAI-compatible endpoints.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* C99/POSIX bundles no TLS client, so this runs curl(1). Consequences, stated
* rather than discovered later:
* - the JSON body travels through a temp file, never through the shell
* command line, so no quoting can corrupt a prompt;
* - the API key travels as a header built from the environment, and the
* command string that carries it is never logged by this code;
* - the HTTP status comes from curl's own -w output, so a 429 is a 429 and
* not an empty success.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "splinter.h"
struct openai_ctx {
char url[512];
char model[128];
char key[256];
const struct sp_registry *reg;
long timeout_s;
};
static int
read_all(FILE *f, struct sp_buf *out)
{
char chunk[4096];
size_t got;
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) {
if (sp_buf_add(out, chunk, got) != 0)
return -1;
}
return ferror(f) ? -1 : 0;
}
static int
openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
struct sp_buf *err)
{
struct openai_ctx *c = ctx;
struct sp_buf body, cmd, raw;
char path[] = "/tmp/splinter-openai-XXXXXX";
int fd, rc = -1;
FILE *p;
ssize_t w;
size_t n;
char *nl;
long status;
if (c == NULL)
return -1;
if (sp_buf_init(&body) != 0 || sp_buf_init(&cmd) != 0 ||
sp_buf_init(&raw) != 0) {
sp_buf_puts(err, "openai: out of memory");
return -1;
}
if (sp_openai_request(conv, c->model, c->reg, &body) != 0) {
sp_buf_puts(err, "openai: cannot build the request");
goto out;
}
fd = mkstemp(path);
if (fd < 0) {
sp_buf_printf(err, "openai: mkstemp: %s", strerror(errno));
goto out;
}
n = body.len;
w = write(fd, body.p, n);
close(fd);
if (w < 0 || (size_t)w != n) {
sp_buf_printf(err, "openai: short write: %s", strerror(errno));
unlink(path);
goto out;
}
sp_buf_printf(&cmd, "curl -sS -m %ld -X POST -H 'Content-Type: "
"application/json'", c->timeout_s);
if (c->key[0] != '\0')
sp_buf_printf(&cmd, " -H 'Authorization: Bearer %s'", c->key);
sp_buf_printf(&cmd, " --data-binary @%s -w '\\n%%{http_code}' '%s'",
path, c->url);
p = popen(cmd.p, "r");
if (p == NULL) {
sp_buf_printf(err, "openai: popen: %s", strerror(errno));
unlink(path);
goto out;
}
if (read_all(p, &raw) != 0) {
sp_buf_puts(err, "openai: read failed");
pclose(p);
unlink(path);
goto out;
}
if (pclose(p) != 0) {
sp_buf_printf(err, "openai: transfer failed for %s", c->url);
unlink(path);
goto out;
}
unlink(path);
if (raw.len < 2 || (nl = strrchr(raw.p, '\n')) == NULL) {
sp_buf_puts(err, "openai: unparseable response (no status)");
goto out;
}
status = strtol(nl + 1, NULL, 10);
*nl = '\0';
if (status < 200 || status > 299) {
out->status = status;
out->content = strdup(raw.p);
rc = out->content != NULL ? 0 : -1;
goto out;
}
if (sp_openai_reply(raw.p, out, err) != 0)
goto out;
out->status = status;
rc = 0;
out:
sp_buf_free(&body);
sp_buf_free(&cmd);
sp_buf_free(&raw);
return rc;
}
struct sp_transport
sp_openai_transport(const char *url, const char *model, const char *api_key,
const struct sp_registry *reg, long timeout_s)
{
static struct openai_ctx ctx;
struct sp_transport t;
memset(&ctx, 0, sizeof(ctx));
snprintf(ctx.url, sizeof(ctx.url), "%s", url != NULL ? url : "");
snprintf(ctx.model, sizeof(ctx.model), "%s", model != NULL ? model : "");
snprintf(ctx.key, sizeof(ctx.key), "%s", api_key != NULL ? api_key : "");
ctx.reg = reg;
ctx.timeout_s = timeout_s > 0 ? timeout_s : 180;
t.send = openai_send;
t.ctx = &ctx;
return t;
}
BIN
View File
Binary file not shown.
+88
View File
@@ -0,0 +1,88 @@
/* splinter -- conversation tests. */
#include <stdio.h>
#include <string.h>
#include "splinter.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
int
main(void)
{
struct sp_conv c;
struct sp_msg m;
sp_conv_init(&c);
CHECK(c.n == 0);
CHECK(sp_conv_bytes(&c) == 0);
CHECK(sp_conv_push(&c, "user", NULL, "hallo") == 0);
CHECK(sp_conv_push(&c, "assistant", NULL, "hi") == 0);
CHECK(c.n == 2);
CHECK(strcmp(c.v[0].role, "user") == 0);
CHECK(strcmp(c.v[0].content, "hallo") == 0);
CHECK(c.v[0].name == NULL);
CHECK(c.v[0].call_id == NULL);
/* a tool message carries name and call id */
memset(&m, 0, sizeof(m));
m.role = "tool";
m.name = "echo";
m.call_id = "call-7";
m.content = "pong";
CHECK(sp_conv_add(&c, &m) == 0);
CHECK(c.n == 3);
CHECK(strcmp(c.v[2].name, "echo") == 0);
CHECK(strcmp(c.v[2].call_id, "call-7") == 0);
/* an assistant turn that asked for tools keeps the provider's raw array */
memset(&m, 0, sizeof(m));
m.role = "assistant";
m.content = "";
m.calls = "[{\"id\":\"call-7\",\"type\":\"function\",\"function\":"
"{\"name\":\"echo\",\"arguments\":\"x\"}}]";
CHECK(sp_conv_add(&c, &m) == 0);
CHECK(c.v[3].calls != NULL);
/* the copy is a copy: changing the source must not change the record */
{
char buf[16];
snprintf(buf, sizeof(buf), "hallo");
buf[0] = 'H';
CHECK(strcmp(c.v[0].content, "hallo") == 0);
}
/* a message without a role is refused */
memset(&m, 0, sizeof(m));
m.content = "x";
CHECK(sp_conv_add(&c, &m) == -1);
CHECK(c.n == 4);
/* trimming drops from the front and keeps the tail */
CHECK(sp_conv_trim(&c, 2) == 0);
CHECK(c.n == 2);
/* the last two of user, assistant, tool, assistant-with-calls: tool first */
CHECK(strcmp(c.v[0].role, "tool") == 0);
CHECK(strcmp(c.v[1].role, "assistant") == 0);
CHECK(sp_conv_trim(&c, 10) == 0);
CHECK(c.n == 2);
/* bytes grow with the content */
CHECK(sp_conv_bytes(&c) > 0);
sp_conv_free(&c);
CHECK(c.n == 0);
CHECK(c.v == NULL);
if (failures == 0)
printf("test_conv: ok\n");
return failures == 0 ? 0 : 1;
}
BIN
View File
Binary file not shown.
+144
View File
@@ -0,0 +1,144 @@
/*
* splinter -- OpenAI request/reply shaping, without a network.
*
* The request is checked by looking for the fields a provider needs; the reply
* parser is fed real-shaped bodies, including the failing shapes. Nothing here
* touches a socket, so a red test means the JSON is wrong, not the endpoint.
*/
#include <stdio.h>
#include <string.h>
#include "splinter.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
static int
echo_tool(const char *args, struct sp_buf *out, void *ctx)
{
(void)ctx;
return sp_buf_puts(out, args);
}
int
main(void)
{
struct sp_conv conv;
struct sp_registry reg;
struct sp_buf req, err;
struct sp_reply rep;
struct sp_tool t;
sp_conv_init(&conv);
memset(&reg, 0, sizeof(reg));
memset(&t, 0, sizeof(t));
t.name = "echo";
t.description = "echo the argument";
t.auth = SP_AUTH_READ;
t.run = echo_tool;
(void)sp_registry_add(&reg, &t);
if (sp_buf_init(&req) != 0 || sp_buf_init(&err) != 0)
return 1;
/* ---- request ---- */
CHECK(sp_conv_push(&conv, "system", NULL, "be brief") == 0);
CHECK(sp_conv_push(&conv, "user", NULL, "say \"hi\"") == 0);
CHECK(sp_openai_request(&conv, "m1", &reg, &req) == 0);
CHECK(strstr(req.p, "\"model\":\"m1\"") != NULL);
CHECK(strstr(req.p, "\"role\":\"system\"") != NULL);
CHECK(strstr(req.p, "\"content\":\"say \\\"hi\\\"\"") != NULL);
CHECK(strstr(req.p, "\"tools\":[") != NULL);
CHECK(strstr(req.p, "\"name\":\"echo\"") != NULL);
CHECK(strstr(req.p, "\"stream\":false") != NULL);
/* tool messages carry the call id, and nothing else claims to */
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "tool";
m.name = "echo";
m.call_id = "call-1";
m.content = "pong";
CHECK(sp_conv_add(&conv, &m) == 0);
CHECK(sp_openai_request(&conv, "m1", &reg, &req) == 0);
CHECK(strstr(req.p, "\"tool_call_id\":\"call-1\"") != NULL);
}
/* an assistant message that asked for tools hands them back verbatim */
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "assistant";
m.content = "";
m.calls = "[{\"id\":\"call-1\",\"type\":\"function\","
"\"function\":{\"name\":\"echo\",\"arguments\":\"{}\"}}]";
CHECK(sp_conv_add(&conv, &m) == 0);
CHECK(sp_openai_request(&conv, "m1", &reg, &req) == 0);
CHECK(strstr(req.p, "\"tool_calls\":[{\"id\":\"call-1\"") != NULL);
}
/* ---- reply: plain answer ---- */
CHECK(sp_openai_reply("{\"choices\":[{\"message\":{\"role\":\"assistant\","
"\"content\":\"fertig\"}}]}", &rep, &err) == 0);
CHECK(strcmp(rep.content, "fertig") == 0);
CHECK(rep.ncalls == 0);
CHECK(rep.calls_json == NULL);
sp_reply_free(&rep);
/* ---- reply: a tool call ---- */
CHECK(sp_openai_reply("{\"choices\":[{\"message\":{\"role\":\"assistant\","
"\"content\":null,\"tool_calls\":[{\"id\":\"call-9\",\"type\":"
"\"function\",\"function\":{\"name\":\"echo\",\"arguments\":"
"\"{\\\"text\\\":\\\"x\\\"}\"}}]}}]}", &rep, &err) == 0);
CHECK(rep.ncalls == 1);
CHECK(strcmp(rep.calls[0].id, "call-9") == 0);
CHECK(strcmp(rep.calls[0].name, "echo") == 0);
CHECK(strstr(rep.calls[0].args, "text") != NULL);
CHECK(rep.calls_json != NULL);
CHECK(strstr(rep.calls_json, "\"call-9\"") != NULL);
sp_reply_free(&rep);
/* ---- reply: content null but no calls is still an answer, empty ---- */
CHECK(sp_openai_reply("{\"choices\":[{\"message\":{\"content\":null}}]}",
&rep, &err) == 0);
CHECK(rep.content != NULL);
CHECK(strcmp(rep.content, "") == 0);
CHECK(rep.ncalls == 0);
sp_reply_free(&rep);
/* ---- the failing shapes say what failed ---- */
sp_buf_clear(&err);
CHECK(sp_openai_reply("{\"error\":{\"message\":\"model not found\"}}",
&rep, &err) == -1);
CHECK(strstr(err.p, "model not found") != NULL);
sp_buf_clear(&err);
CHECK(sp_openai_reply("{\"choices\":[]}", &rep, &err) == -1);
CHECK(strstr(err.p, "no choices") != NULL);
sp_buf_clear(&err);
CHECK(sp_openai_reply("not json at all", &rep, &err) == -1);
CHECK(strstr(err.p, "not JSON") != NULL);
sp_buf_clear(&err);
CHECK(sp_openai_reply("", &rep, &err) == -1);
CHECK(strstr(err.p, "empty body") != NULL);
sp_buf_free(&req);
sp_buf_free(&err);
sp_conv_free(&conv);
sp_registry_free(&reg);
if (failures == 0)
printf("test_openai: ok\n");
return failures == 0 ? 0 : 1;
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+39 -14
View File
@@ -1,4 +1,4 @@
/* splinter -- mock transport tests. */
/* splinter -- mock transport tests (conversation based). */
#include <stdio.h>
#include <string.h>
@@ -20,45 +20,70 @@ main(void)
struct sp_transport t;
struct sp_reply r;
struct sp_buf err;
struct sp_conv conv;
CHECK(sp_mock_init(&m) == 0);
if (sp_mock_init(&m) != 0)
return 1;
if (sp_buf_init(&err) != 0)
return 1;
sp_conv_init(&conv);
t = sp_mock_transport(&m);
CHECK(sp_conv_push(&conv, "user", NULL, "hi") == 0);
/* an empty queue is an error, never an empty success */
memset(&r, 0, sizeof(r));
CHECK(t.send(t.ctx, "user hi\n", &r, &err) != 0);
CHECK(t.send(t.ctx, &conv, &r, &err) != 0);
CHECK(err.len > 0);
sp_buf_clear(&err);
sp_reply_free(&r);
/* a plain answer */
CHECK(sp_mock_push(&m, 200, "answer first") == 0);
CHECK(sp_mock_push(&m, 200, "answer second") == 0);
memset(&r, 0, sizeof(r));
CHECK(t.send(t.ctx, "user one\n", &r, &err) == 0);
CHECK(t.send(t.ctx, &conv, &r, &err) == 0);
CHECK(r.status == 200);
CHECK(r.body != NULL && strcmp(r.body, "answer first") == 0);
CHECK(strcmp(m.last_request.p, "user one\n") == 0);
CHECK(r.content != NULL && strcmp(r.content, "first") == 0);
CHECK(r.ncalls == 0);
CHECK(strcmp(m.last_request.p, "user hi\n") == 0);
sp_reply_free(&r);
/* after a tool ran, the request says which tool and what came back */
CHECK(sp_conv_push(&conv, "tool", "echo", "ping") == 0);
CHECK(sp_mock_push(&m, 200, "answer second") == 0);
memset(&r, 0, sizeof(r));
CHECK(t.send(t.ctx, "user two\n", &r, &err) == 0);
CHECK(r.body != NULL && strcmp(r.body, "answer second") == 0);
CHECK(strcmp(m.last_request.p, "user two\n") == 0);
CHECK(t.send(t.ctx, &conv, &r, &err) == 0);
CHECK(strcmp(r.content, "second") == 0);
CHECK(strcmp(m.last_request.p, "observe echo ping\n") == 0);
sp_reply_free(&r);
CHECK(m.requests == 3);
/* a tool call comes back as one call with its arguments */
CHECK(sp_mock_push(&m, 200, "tool echo a b c") == 0);
memset(&r, 0, sizeof(r));
CHECK(t.send(t.ctx, &conv, &r, &err) == 0);
CHECK(r.ncalls == 1);
CHECK(strcmp(r.calls[0].name, "echo") == 0);
CHECK(strcmp(r.calls[0].args, "a b c") == 0);
CHECK(r.calls[0].id != NULL);
sp_reply_free(&r);
/* a non-2xx status is passed through untouched */
/* a non-2xx status is passed through with its body untouched */
CHECK(sp_mock_push(&m, 429, "slow down") == 0);
memset(&r, 0, sizeof(r));
CHECK(t.send(t.ctx, "user three\n", &r, &err) == 0);
CHECK(t.send(t.ctx, &conv, &r, &err) == 0);
CHECK(r.status == 429);
CHECK(strcmp(r.content, "slow down") == 0);
sp_reply_free(&r);
/* a reply in neither form is an error that says what it saw */
CHECK(sp_mock_push(&m, 200, "gibberish") == 0);
sp_buf_clear(&err);
memset(&r, 0, sizeof(r));
CHECK(t.send(t.ctx, &conv, &r, &err) != 0);
CHECK(strstr(err.p, "neither answer nor tool") != NULL);
sp_reply_free(&r);
sp_buf_free(&err);
sp_conv_free(&conv);
sp_mock_free(&m);
CHECK(m.queue == NULL);
+898
View File
@@ -0,0 +1,898 @@
/*
* libmcp - a minimal Model Context Protocol server in C99 + POSIX.
*
* Single file on purpose: copy mcp.h into a project, add one .c that does
*
* #define MCP_IMPLEMENTATION
* #include "mcp.h"
*
* and the whole server is there. No dependencies beyond libc.
*
* What it implements: newline-delimited JSON-RPC 2.0 on stdin/stdout,
* `initialize`, `tools/list`, `tools/call`, `ping`, and the rule that a
* message without an `id` is a notification and gets no answer.
*
* You supply a table of tools; each tool gets its arguments as a read-only
* JSON view and calls exactly one reply function.
*
* static void tool_echo(mcp_conn *c, const mcp_json *args, void *user)
* {
* const char *s = mcp_arg_string(args, "text");
* mcp_reply_text(c, s ? s : "");
* }
*
* static const mcp_tool tools[] = {
* { "echo", "Echo text back.", MCP_SCHEMA_ECHO, tool_echo },
* };
*
* int main(void)
* {
* mcp_server srv = { "echo-server", "1.0.0", tools, 1, NULL };
* return mcp_serve_stdio(&srv);
* }
*
* A tool that does not reply gets an error reply from the library, so a
* forgotten branch cannot make a client hang.
*/
#ifndef MCP_H
#define MCP_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ---------------------------------------------------------------- json view */
enum mcp_jtype { MCP_NULL, MCP_BOOL, MCP_NUM, MCP_STR, MCP_ARR, MCP_OBJ };
typedef struct mcp_json mcp_json;
struct mcp_json {
enum mcp_jtype t;
int b;
double n;
char *s;
mcp_json **items;
char **keys;
size_t count;
};
/* ---------------------------------------------------------------- server */
typedef struct mcp_conn mcp_conn;
typedef void (*mcp_handler)(mcp_conn *c, const mcp_json *args, void *user);
typedef struct {
const char *name;
const char *description;
const char *schema; /* JSON object text for inputSchema */
mcp_handler handler;
} mcp_tool;
typedef struct {
const char *name;
const char *version;
const mcp_tool *tools;
size_t ntools;
void *user;
} mcp_server;
/* Serve on stdin/stdout until EOF. Returns 0. */
int mcp_serve_stdio(mcp_server *srv);
/* ---------------------------------------------------------------- replies */
/* Reply with a single text content block (the usual tool answer). */
void mcp_reply_text(mcp_conn *c, const char *text);
/* Reply with text that happens to be JSON (pretty for the model, still text). */
void mcp_reply_json(mcp_conn *c, const char *json);
/* Reply with a raw result object, exactly as given. */
void mcp_reply_raw(mcp_conn *c, const char *json);
/* Reply with a tool error: {"content":[...],"isError":true}. */
void mcp_reply_error(mcp_conn *c, const char *message);
/* JSON-RPC level error (bad params, unknown method). */
void mcp_reply_rpc_error(mcp_conn *c, int code, const char *message);
/* ---------------------------------------------------------------- arguments */
const mcp_json *mcp_arg(const mcp_json *args, const char *key);
const char *mcp_arg_string(const mcp_json *args, const char *key);
int mcp_arg_int(const mcp_json *args, const char *key, int dflt);
double mcp_arg_num(const mcp_json *args, const char *key, double dflt);
int mcp_arg_bool(const mcp_json *args, const char *key, int dflt);
const char *mcp_json_string(const mcp_json *v);
size_t mcp_array_len(const mcp_json *v);
const mcp_json *mcp_array_at(const mcp_json *v, size_t i);
/* Growable string. Use it to build a reply, then mcp_reply_text/json it. */
typedef struct {
char *p;
size_t len;
size_t cap;
} mcp_buf;
void mcp_buf_init(mcp_buf *b);
void mcp_buf_add(mcp_buf *b, const char *s, size_t n);
void mcp_buf_puts(mcp_buf *b, const char *s);
void mcp_buf_printf(mcp_buf *b, const char *fmt, ...);
void mcp_buf_free(mcp_buf *b);
/* Escape a string into a JSON string body (no surrounding quotes). */
void mcp_json_escape(mcp_buf *b, const char *s);
/* Parse a complete JSON document. Returns NULL on error. Free with
* mcp_json_free(). A backend that stores its own state as JSON needs this. */
mcp_json *mcp_parse(const char *text);
void mcp_json_free(mcp_json *v);
/* Handle one JSON-RPC line and return the reply as a malloc'd string, or NULL
* when the message was a notification. Free with free(). This is what a HTTP
* transport needs: same envelope, no stdin/stdout. */
char *mcp_handle(mcp_server *srv, const char *line);
#ifdef __cplusplus
}
#endif
#endif /* MCP_H */
/* ===========================================================================
* implementation
* =========================================================================== */
#ifdef MCP_IMPLEMENTATION
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MCP_MAX_TOOLS
#define MCP_MAX_TOOLS 128
#endif
struct mcp_conn {
FILE *out;
mcp_buf outbuf; /* when to_buf, replies accumulate here */
int to_buf;
char *id_json; /* the request id, already serialized */
int replied;
};
/* ------------------------------------------------------------------ buffer */
void mcp_buf_init(mcp_buf *b)
{
b->p = NULL;
b->len = 0;
b->cap = 0;
}
void mcp_buf_add(mcp_buf *b, const char *s, size_t n)
{
if (b->len + n + 1 > b->cap) {
size_t want = b->cap ? b->cap : 256;
while (want < b->len + n + 1)
want *= 2;
b->p = realloc(b->p, want);
if (b->p == NULL) {
fprintf(stderr, "libmcp: out of memory\n");
exit(1);
}
b->cap = want;
}
memcpy(b->p + b->len, s, n);
b->len += n;
b->p[b->len] = '\0';
}
void mcp_buf_puts(mcp_buf *b, const char *s)
{
mcp_buf_add(b, s, strlen(s));
}
void mcp_buf_printf(mcp_buf *b, const char *fmt, ...)
{
char tmp[512];
va_list ap;
int n;
va_start(ap, fmt);
n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
va_end(ap);
if (n < 0)
return;
if ((size_t)n < sizeof(tmp)) {
mcp_buf_add(b, tmp, (size_t)n);
return;
}
{
char *big = malloc((size_t)n + 1);
if (big == NULL)
return;
va_start(ap, fmt);
vsnprintf(big, (size_t)n + 1, fmt, ap);
va_end(ap);
mcp_buf_add(b, big, (size_t)n);
free(big);
}
}
void mcp_buf_free(mcp_buf *b)
{
free(b->p);
mcp_buf_init(b);
}
void mcp_json_escape(mcp_buf *b, const char *s)
{
if (s == NULL)
return;
for (; *s; s++) {
unsigned char c = (unsigned char)*s;
switch (c) {
case '"': mcp_buf_puts(b, "\\\""); break;
case '\\': mcp_buf_puts(b, "\\\\"); break;
case '\n': mcp_buf_puts(b, "\\n"); break;
case '\r': mcp_buf_puts(b, "\\r"); break;
case '\t': mcp_buf_puts(b, "\\t"); break;
default:
if (c < 0x20) {
char tmp[8];
snprintf(tmp, sizeof(tmp), "\\u%04x", c);
mcp_buf_puts(b, tmp);
} else {
mcp_buf_add(b, (const char *)&c, 1);
}
}
}
}
/* ------------------------------------------------------------------ parser */
static mcp_json *jnew(enum mcp_jtype t)
{
mcp_json *v = calloc(1, sizeof(*v));
if (v == NULL) {
fprintf(stderr, "libmcp: out of memory\n");
exit(1);
}
v->t = t;
return v;
}
static void jfree(mcp_json *v)
{
size_t i;
if (v == NULL)
return;
if (v->t == MCP_STR)
free(v->s);
for (i = 0; i < v->count; i++) {
if (v->keys != NULL)
free(v->keys[i]);
jfree(v->items[i]);
}
free(v->items);
free(v->keys);
free(v);
}
static const char *skip_ws(const char *p)
{
while (*p && isspace((unsigned char)*p))
p++;
return p;
}
static const char *jparse(const char *p, mcp_json **out);
static char *parse_string(const char **pp)
{
const char *p = *pp;
mcp_buf b;
if (*p != '"')
return NULL;
p++;
mcp_buf_init(&b);
while (*p && *p != '"') {
if (*p == '\\') {
p++;
switch (*p) {
case '"': mcp_buf_add(&b, "\"", 1); break;
case '\\': mcp_buf_add(&b, "\\", 1); break;
case '/': mcp_buf_add(&b, "/", 1); break;
case 'b': mcp_buf_add(&b, "\b", 1); break;
case 'f': mcp_buf_add(&b, "\f", 1); break;
case 'n': mcp_buf_add(&b, "\n", 1); break;
case 'r': mcp_buf_add(&b, "\r", 1); break;
case 't': mcp_buf_add(&b, "\t", 1); break;
case 'u':
if (p[1] && p[2] && p[3] && p[4]) {
char hex[5];
unsigned long cp;
char utf8[4];
size_t len = 0;
memcpy(hex, p + 1, 4);
hex[4] = '\0';
cp = strtoul(hex, NULL, 16);
if (cp < 0x80) {
utf8[len++] = (char)cp;
} else if (cp < 0x800) {
utf8[len++] = (char)(0xc0 | (cp >> 6));
utf8[len++] = (char)(0x80 | (cp & 0x3f));
} else {
utf8[len++] = (char)(0xe0 | (cp >> 12));
utf8[len++] = (char)(0x80 | ((cp >> 6) & 0x3f));
utf8[len++] = (char)(0x80 | (cp & 0x3f));
}
mcp_buf_add(&b, utf8, len);
p += 4;
}
break;
default: mcp_buf_add(&b, p, 1); break;
}
p++;
continue;
}
mcp_buf_add(&b, p, 1);
p++;
}
if (*p == '"')
p++;
*pp = p;
if (b.p == NULL)
mcp_buf_add(&b, "", 0);
return b.p;
}
static const char *jparse_array(const char *p, mcp_json **out)
{
mcp_json *v = jnew(MCP_ARR);
p = skip_ws(p + 1);
if (*p == ']') {
*out = v;
return p + 1;
}
for (;;) {
mcp_json *item = NULL;
p = jparse(p, &item);
if (p == NULL) {
jfree(v);
return NULL;
}
v->items = realloc(v->items, (v->count + 1) * sizeof(*v->items));
if (v->items == NULL) {
jfree(v);
return NULL;
}
v->items[v->count++] = item;
p = skip_ws(p);
if (*p == ',') {
p = skip_ws(p + 1);
continue;
}
if (*p == ']') {
*out = v;
return p + 1;
}
jfree(v);
return NULL;
}
}
static const char *jparse_object(const char *p, mcp_json **out)
{
mcp_json *v = jnew(MCP_OBJ);
p = skip_ws(p + 1);
if (*p == '}') {
*out = v;
return p + 1;
}
for (;;) {
char *key = NULL;
mcp_json *val = NULL;
p = skip_ws(p);
key = parse_string(&p);
if (key == NULL) {
jfree(v);
return NULL;
}
p = skip_ws(p);
if (*p != ':') {
free(key);
jfree(v);
return NULL;
}
p = jparse(skip_ws(p + 1), &val);
if (p == NULL) {
free(key);
jfree(v);
return NULL;
}
v->items = realloc(v->items, (v->count + 1) * sizeof(*v->items));
v->keys = realloc(v->keys, (v->count + 1) * sizeof(*v->keys));
if (v->items == NULL || v->keys == NULL) {
free(key);
jfree(val);
jfree(v);
return NULL;
}
v->keys[v->count] = key;
v->items[v->count] = val;
v->count++;
p = skip_ws(p);
if (*p == ',') {
p++;
continue;
}
if (*p == '}') {
*out = v;
return p + 1;
}
jfree(v);
return NULL;
}
}
static const char *jparse(const char *p, mcp_json **out)
{
p = skip_ws(p);
switch (*p) {
case '{':
return jparse_object(p, out);
case '[':
return jparse_array(p, out);
case '"': {
mcp_json *v = jnew(MCP_STR);
v->s = parse_string(&p);
if (v->s == NULL) {
jfree(v);
return NULL;
}
*out = v;
return p;
}
case 't':
if (strncmp(p, "true", 4) == 0) {
mcp_json *v = jnew(MCP_BOOL);
v->b = 1;
*out = v;
return p + 4;
}
return NULL;
case 'f':
if (strncmp(p, "false", 5) == 0) {
mcp_json *v = jnew(MCP_BOOL);
v->b = 0;
*out = v;
return p + 5;
}
return NULL;
case 'n':
if (strncmp(p, "null", 4) == 0) {
*out = jnew(MCP_NULL);
return p + 4;
}
return NULL;
default: {
char *end = NULL;
double d = strtod(p, &end);
mcp_json *v;
if (end == p)
return NULL;
v = jnew(MCP_NUM);
v->n = d;
*out = v;
return end;
}
}
}
/* ------------------------------------------------------------------ reading */
const mcp_json *mcp_arg(const mcp_json *args, const char *key)
{
size_t i;
if (args == NULL || args->t != MCP_OBJ || key == NULL)
return NULL;
for (i = 0; i < args->count; i++)
if (strcmp(args->keys[i], key) == 0)
return args->items[i];
return NULL;
}
const char *mcp_json_string(const mcp_json *v)
{
return (v != NULL && v->t == MCP_STR) ? v->s : NULL;
}
const char *mcp_arg_string(const mcp_json *args, const char *key)
{
return mcp_json_string(mcp_arg(args, key));
}
int mcp_arg_int(const mcp_json *args, const char *key, int dflt)
{
const mcp_json *v = mcp_arg(args, key);
return (v != NULL && v->t == MCP_NUM) ? (int)v->n : dflt;
}
double mcp_arg_num(const mcp_json *args, const char *key, double dflt)
{
const mcp_json *v = mcp_arg(args, key);
return (v != NULL && v->t == MCP_NUM) ? v->n : dflt;
}
int mcp_arg_bool(const mcp_json *args, const char *key, int dflt)
{
const mcp_json *v = mcp_arg(args, key);
return (v != NULL && v->t == MCP_BOOL) ? v->b : dflt;
}
size_t mcp_array_len(const mcp_json *v)
{
return (v != NULL && v->t == MCP_ARR) ? v->count : 0;
}
const mcp_json *mcp_array_at(const mcp_json *v, size_t i)
{
if (v == NULL || v->t != MCP_ARR || i >= v->count)
return NULL;
return v->items[i];
}
/* ------------------------------------------------------------------ writing */
static void send_line(mcp_conn *c, const char *body, size_t len)
{
if (c->to_buf) {
mcp_buf_add(&c->outbuf, body, len);
return;
}
fwrite(body, 1, len, c->out);
fputc('\n', c->out);
fflush(c->out);
}
static void emit_result(mcp_conn *c, const char *result_json)
{
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
mcp_buf_puts(&b, c->id_json ? c->id_json : "null");
mcp_buf_puts(&b, ",\"result\":");
mcp_buf_puts(&b, result_json);
mcp_buf_puts(&b, "}");
send_line(c, b.p, b.len);
mcp_buf_free(&b);
c->replied = 1;
}
void mcp_reply_rpc_error(mcp_conn *c, int code, const char *message)
{
mcp_buf b;
if (c->replied)
return;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
mcp_buf_puts(&b, c->id_json ? c->id_json : "null");
mcp_buf_printf(&b, ",\"error\":{\"code\":%d,\"message\":\"", code);
mcp_json_escape(&b, message);
mcp_buf_puts(&b, "\"}}");
send_line(c, b.p, b.len);
mcp_buf_free(&b);
c->replied = 1;
}
void mcp_reply_raw(mcp_conn *c, const char *json)
{
if (c->replied)
return;
emit_result(c, json ? json : "{}");
}
static void emit_content(mcp_conn *c, const char *text, int is_error)
{
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":\"");
mcp_json_escape(&b, text ? text : "");
mcp_buf_puts(&b, "\"}]");
if (is_error)
mcp_buf_puts(&b, ",\"isError\":true");
mcp_buf_puts(&b, "}");
emit_result(c, b.p);
mcp_buf_free(&b);
}
void mcp_reply_text(mcp_conn *c, const char *text)
{
if (c->replied)
return;
emit_content(c, text, 0);
}
void mcp_reply_json(mcp_conn *c, const char *json)
{
if (c->replied)
return;
emit_content(c, json, 0);
}
void mcp_reply_error(mcp_conn *c, const char *message)
{
if (c->replied)
return;
emit_content(c, message, 1);
}
/* ------------------------------------------------------------------ parse api */
mcp_json *mcp_parse(const char *text)
{
mcp_json *v = NULL;
if (text == NULL)
return NULL;
if (jparse(text, &v) == NULL) {
jfree(v);
return NULL;
}
return v;
}
void mcp_json_free(mcp_json *v)
{
jfree(v);
}
/* ------------------------------------------------------------------ server */
static void tools_list(mcp_conn *c, const mcp_server *srv)
{
mcp_buf b;
size_t i;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"tools\":[");
for (i = 0; i < srv->ntools; i++) {
const mcp_tool *t = &srv->tools[i];
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"name\":\"");
mcp_json_escape(&b, t->name);
mcp_buf_puts(&b, "\",\"description\":\"");
mcp_json_escape(&b, t->description ? t->description : "");
mcp_buf_puts(&b, "\",\"inputSchema\":");
mcp_buf_puts(&b, (t->schema && *t->schema) ? t->schema
: "{\"type\":\"object\",\"properties\":{}}");
mcp_buf_puts(&b, "}");
}
mcp_buf_puts(&b, "]}");
emit_result(c, b.p);
mcp_buf_free(&b);
}
static void tools_call(mcp_conn *c, const mcp_server *srv, const mcp_json *params)
{
const char *name = mcp_arg_string(params, "name");
const mcp_json *args = mcp_arg(params, "arguments");
size_t i;
if (name == NULL) {
mcp_reply_rpc_error(c, -32602, "missing tool name");
return;
}
for (i = 0; i < srv->ntools; i++) {
if (strcmp(srv->tools[i].name, name) != 0)
continue;
c->replied = 0;
if (srv->tools[i].handler != NULL)
srv->tools[i].handler(c, args, srv->user);
if (!c->replied) {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "tool '%s' produced no reply", name);
emit_content(c, b.p, 1);
mcp_buf_free(&b);
}
return;
}
{
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "unknown tool: %s", name);
mcp_reply_rpc_error(c, -32601, b.p);
mcp_buf_free(&b);
}
}
static char *id_to_json(const mcp_json *id)
{
mcp_buf b;
if (id == NULL)
return NULL;
mcp_buf_init(&b);
if (id->t == MCP_STR) {
mcp_buf_puts(&b, "\"");
mcp_json_escape(&b, id->s);
mcp_buf_puts(&b, "\"");
} else if (id->t == MCP_NUM) {
mcp_buf_printf(&b, "%.0f", id->n);
} else if (id->t == MCP_BOOL) {
mcp_buf_puts(&b, id->b ? "true" : "false");
} else {
mcp_buf_puts(&b, "null");
}
return b.p;
}
static void handle_line(mcp_server *srv, const char *line, mcp_conn *c)
{
mcp_json *msg = NULL;
mcp_json *id;
const char *method;
if (jparse(line, &msg) == NULL || msg == NULL || msg->t != MCP_OBJ) {
jfree(msg);
c->id_json = NULL;
c->replied = 0;
mcp_reply_rpc_error(c, -32700, "parse error");
return;
}
id = NULL;
{
size_t i;
for (i = 0; i < msg->count; i++)
if (strcmp(msg->keys[i], "id") == 0)
id = msg->items[i];
}
method = mcp_arg_string(msg, "method");
c->replied = 0;
free(c->id_json);
c->id_json = id_to_json(id);
/* no id -> notification -> no answer, whatever the method is */
if (id == NULL) {
if (method != NULL && strcmp(method, "tools/call") == 0) {
const mcp_json *args = mcp_arg(mcp_arg(msg, "params"), "arguments");
(void)args;
}
jfree(msg);
return;
}
if (method == NULL) {
mcp_reply_rpc_error(c, -32600, "invalid request: no method");
jfree(msg);
return;
}
if (strcmp(method, "initialize") == 0) {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}");
mcp_buf_puts(&b, ",\"serverInfo\":{\"name\":\"");
mcp_json_escape(&b, srv->name ? srv->name : "libmcp");
mcp_buf_puts(&b, "\",\"version\":\"");
mcp_json_escape(&b, srv->version ? srv->version : "1.0.0");
mcp_buf_puts(&b, "\"}}");
emit_result(c, b.p);
mcp_buf_free(&b);
} else if (strcmp(method, "tools/list") == 0) {
tools_list(c, srv);
} else if (strcmp(method, "tools/call") == 0) {
tools_call(c, srv, mcp_arg(msg, "params"));
} else if (strcmp(method, "ping") == 0) {
emit_result(c, "{}");
} else {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "unknown method: %s", method);
mcp_reply_rpc_error(c, -32601, b.p);
mcp_buf_free(&b);
}
jfree(msg);
}
/* Plain C99 line reader: no getline, no ssize_t, so this header compiles on
* every libc without a feature-test macro. */
static int read_line(FILE *f, mcp_buf *b)
{
int ch;
b->len = 0;
if (b->p != NULL)
b->p[0] = '\0';
while ((ch = fgetc(f)) != EOF && ch != '\n') {
char c = (char)ch;
mcp_buf_add(b, &c, 1);
}
if (ch == EOF && b->len == 0)
return 0;
while (b->len > 0 && b->p[b->len - 1] == '\r')
b->p[--b->len] = '\0';
return 1;
}
char *mcp_handle(mcp_server *srv, const char *line)
{
mcp_conn c;
char *out = NULL;
if (srv == NULL || line == NULL)
return NULL;
memset(&c, 0, sizeof(c));
c.out = stdout;
c.to_buf = 1;
mcp_buf_init(&c.outbuf);
handle_line(srv, line, &c);
if (c.outbuf.len > 0) {
out = malloc(c.outbuf.len + 1);
if (out != NULL)
memcpy(out, c.outbuf.p, c.outbuf.len + 1);
}
mcp_buf_free(&c.outbuf);
free(c.id_json);
return out;
}
int mcp_serve_stdio(mcp_server *srv)
{
mcp_conn c;
mcp_buf line;
memset(&c, 0, sizeof(c));
c.out = stdout;
mcp_buf_init(&line);
while (read_line(stdin, &line)) {
if (line.len == 0)
continue;
handle_line(srv, line.p, &c);
}
mcp_buf_free(&line);
free(c.id_json);
return 0;
}
#endif /* MCP_IMPLEMENTATION */