Refresh the vendored header to libmcp 6d2fcb4. A client in the OpenAI
function-call shape sends "arguments":"{\"key\":1}" - a string, not an object.
tools_call handed that straight to the handler, so mcp_arg() returned NULL for
every key and a handler that filters on an argument saw "no filter" and acted
on everything.
A value that is neither absent, an object, nor a string holding an object is
now refused with an isError answer instead of silently becoming "no
arguments". Built and tested here: make test green.
1211 lines
28 KiB
C
1211 lines
28 KiB
C
#ifndef MCP_H
|
|
#define MCP_H
|
|
|
|
/*
|
|
* 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.
|
|
*/
|
|
|
|
#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);
|
|
|
|
/* Serve the same tools over HTTP (Streamable HTTP, JSON-RPC 2.0 on POST).
|
|
* host may be NULL for "0.0.0.0". Returns 0 if the socket could not be opened;
|
|
* otherwise it never returns — it accepts connections until the process ends.
|
|
*
|
|
* One process per connection via fork(): without that, every finished child
|
|
* stays a zombie and a long-running server grows a process table full of them. */
|
|
int mcp_serve_http(mcp_server *srv, const char *host, int port);
|
|
|
|
/* "--http 8781", "--http :8781" and "--http 0.0.0.0:8781" all mean the same.
|
|
* Returns -1 (and prints why) for anything that is not a usable port. */
|
|
int mcp_parse_port(const char *s);
|
|
|
|
/* ---------------------------------------------------------------- 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
|
|
|
|
|
|
/* ===========================================================================
|
|
* implementation
|
|
* =========================================================================== */
|
|
#ifdef MCP_IMPLEMENTATION
|
|
|
|
#ifndef MCP_MAX_BODY
|
|
#define MCP_MAX_BODY (8u * 1024u * 1024u)
|
|
#endif
|
|
|
|
#include <ctype.h>
|
|
#include <stdarg.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <errno.h>
|
|
#include <time.h>
|
|
#include <netinet/in.h>
|
|
#include <signal.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
#include <arpa/inet.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);
|
|
}
|
|
|
|
/*
|
|
* The arguments of a tools/call, always as an object or NULL.
|
|
*
|
|
* Some clients send arguments as a JSON *string* instead of an object: the
|
|
* OpenAI/Anthropic function-call shape has "arguments":"{\"key\":1}", and a
|
|
* proxy that forwards that shape unchanged produces exactly such a request.
|
|
* Passing the string straight to the handler made mcp_arg() return NULL for
|
|
* every key, so a handler that filters on an argument silently saw "no
|
|
* filter" and acted on everything - task_next(scope="splinter") handed out a
|
|
* makronix task because scope was invisible to it. So: a string is parsed,
|
|
* and anything that does not yield an object is an error, never "no
|
|
* arguments".
|
|
*
|
|
* Returns 0 and sets *outp, or -1 when the value is neither absent, an object,
|
|
* nor a string holding an object. *owned says who owns the object: when it is
|
|
* 0 the object is part of the request and must NOT be freed; when it is 1 the
|
|
* caller frees it with mcp_json_free.
|
|
*/
|
|
static int call_arguments(const mcp_json *params, mcp_json **outp, int *owned)
|
|
{
|
|
const mcp_json *args = params != NULL ? mcp_arg(params, "arguments") : NULL;
|
|
|
|
*outp = NULL;
|
|
*owned = 0;
|
|
if (args == NULL || args->t == MCP_NULL)
|
|
return 0;
|
|
if (args->t == MCP_OBJ) {
|
|
*outp = (mcp_json *)args;
|
|
return 0;
|
|
}
|
|
if (args->t == MCP_STR) {
|
|
mcp_json *v = mcp_parse(args->s);
|
|
|
|
if (v == NULL || v->t != MCP_OBJ) {
|
|
mcp_json_free(v);
|
|
return -1;
|
|
}
|
|
*outp = v;
|
|
*owned = 1;
|
|
return 0;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
static void tools_call(mcp_conn *c, const mcp_server *srv, const mcp_json *params)
|
|
{
|
|
const char *name = mcp_arg_string(params, "name");
|
|
mcp_json *parsed = NULL;
|
|
const mcp_json *args;
|
|
int owned = 0;
|
|
size_t i;
|
|
|
|
if (name == NULL) {
|
|
mcp_reply_rpc_error(c, -32602, "missing tool name");
|
|
return;
|
|
}
|
|
if (call_arguments(params, &parsed, &owned) != 0) {
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "the arguments of '%s' are not a JSON object", name);
|
|
emit_content(c, b.p, 1);
|
|
mcp_buf_free(&b);
|
|
return;
|
|
}
|
|
args = parsed;
|
|
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 (owned)
|
|
mcp_json_free(parsed);
|
|
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;
|
|
|
|
if (owned)
|
|
mcp_json_free(parsed);
|
|
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;
|
|
}
|
|
|
|
/* strcasestr is a GNU extension, not POSIX: do it here. */
|
|
static char *mcp_ci_strstr(const char *hay, const char *needle)
|
|
{
|
|
size_t nl = strlen(needle);
|
|
const char *p;
|
|
|
|
if (nl == 0)
|
|
return (char *)hay;
|
|
for (p = hay; *p; p++) {
|
|
size_t i;
|
|
|
|
for (i = 0; i < nl; i++) {
|
|
if (p[i] == '\0' ||
|
|
tolower((unsigned char)p[i]) != tolower((unsigned char)needle[i]))
|
|
break;
|
|
}
|
|
if (i == nl)
|
|
return (char *)p;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
static void mcp_http_reply(int fd, int code, const char *ctype, const char *body,
|
|
const char *session)
|
|
{
|
|
mcp_buf out;
|
|
size_t len = body != NULL ? strlen(body) : 0;
|
|
size_t sent = 0;
|
|
|
|
mcp_buf_init(&out);
|
|
mcp_buf_printf(&out, "HTTP/1.1 %d %s\r\n", code,
|
|
code == 200 ? "OK" : (code == 202 ? "Accepted" : "Method Not Allowed"));
|
|
if (ctype != NULL)
|
|
mcp_buf_printf(&out, "Content-Type: %s\r\n", ctype);
|
|
if (session != NULL)
|
|
mcp_buf_printf(&out, "Mcp-Session-Id: %s\r\n", session);
|
|
mcp_buf_printf(&out, "Content-Length: %lu\r\n", (unsigned long)len);
|
|
mcp_buf_puts(&out, "Connection: close\r\n\r\n");
|
|
if (len > 0)
|
|
mcp_buf_add(&out, body, len);
|
|
while (sent < out.len) {
|
|
ssize_t w = write(fd, out.p + sent, out.len - sent);
|
|
|
|
if (w <= 0)
|
|
break;
|
|
sent += (size_t)w;
|
|
}
|
|
mcp_buf_free(&out);
|
|
}
|
|
|
|
static void mcp_http_serve_one(int fd, mcp_server *srv, const char *session)
|
|
{
|
|
char buf[8192];
|
|
mcp_buf head;
|
|
int header_done = 0;
|
|
long content_length = 0;
|
|
char *body = NULL;
|
|
char *reply;
|
|
|
|
mcp_buf_init(&head);
|
|
for (;;) {
|
|
ssize_t r = read(fd, buf, sizeof(buf));
|
|
|
|
if (r <= 0)
|
|
break;
|
|
mcp_buf_add(&head, buf, (size_t)r);
|
|
{
|
|
char *sep = strstr(head.p, "\r\n\r\n");
|
|
|
|
if (sep != NULL) {
|
|
char *cl = mcp_ci_strstr(head.p, "Content-Length:");
|
|
size_t header_len = (size_t)(sep + 4 - head.p);
|
|
size_t have = head.len > header_len ? head.len - header_len : 0;
|
|
|
|
header_done = 1;
|
|
if (cl != NULL)
|
|
content_length = strtol(cl + 15, NULL, 10);
|
|
if (content_length < 0 || content_length > MCP_MAX_BODY) {
|
|
mcp_http_reply(fd, 405, "text/plain", "body too large\n", NULL);
|
|
mcp_buf_free(&head);
|
|
close(fd);
|
|
return;
|
|
}
|
|
body = calloc((size_t)content_length + 1, 1);
|
|
if (body == NULL) {
|
|
mcp_buf_free(&head);
|
|
close(fd);
|
|
return;
|
|
}
|
|
if (have > (size_t)content_length)
|
|
have = (size_t)content_length;
|
|
memcpy(body, head.p + header_len, have);
|
|
while (have < (size_t)content_length) {
|
|
ssize_t r2 = read(fd, body + have, (size_t)content_length - have);
|
|
|
|
if (r2 <= 0)
|
|
break;
|
|
have += (size_t)r2;
|
|
}
|
|
body[have] = '\0';
|
|
break;
|
|
}
|
|
}
|
|
if (head.len > MCP_MAX_BODY)
|
|
break;
|
|
}
|
|
|
|
if (!header_done) {
|
|
mcp_http_reply(fd, 405, "text/plain", "want POST /mcp\n", NULL);
|
|
mcp_buf_free(&head);
|
|
close(fd);
|
|
return;
|
|
}
|
|
if (strncmp(head.p, "GET ", 4) == 0 || strncmp(head.p, "DELETE ", 7) == 0) {
|
|
/* the SSE stream is not offered: this server answers per request */
|
|
mcp_http_reply(fd, 202, NULL, "", session);
|
|
free(body);
|
|
mcp_buf_free(&head);
|
|
close(fd);
|
|
return;
|
|
}
|
|
if (strncmp(head.p, "POST ", 5) != 0) {
|
|
mcp_http_reply(fd, 405, "text/plain", "only POST\n", NULL);
|
|
free(body);
|
|
mcp_buf_free(&head);
|
|
close(fd);
|
|
return;
|
|
}
|
|
|
|
reply = mcp_handle(srv, body != NULL ? body : "{}");
|
|
free(body);
|
|
if (reply == NULL) {
|
|
mcp_http_reply(fd, 202, NULL, "", session); /* notification: nothing to say */
|
|
} else {
|
|
mcp_http_reply(fd, 200, "application/json", reply, session);
|
|
free(reply);
|
|
}
|
|
mcp_buf_free(&head);
|
|
close(fd);
|
|
}
|
|
|
|
int mcp_serve_http(mcp_server *srv, const char *host, int port)
|
|
{
|
|
int ls;
|
|
struct sockaddr_in addr;
|
|
int one = 1;
|
|
char session[40];
|
|
|
|
snprintf(session, sizeof(session), "%08x-%08x",
|
|
(unsigned)time(NULL), (unsigned)getpid());
|
|
ls = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (ls < 0) {
|
|
perror("socket");
|
|
return 1;
|
|
}
|
|
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
|
memset(&addr, 0, sizeof(addr));
|
|
addr.sin_family = AF_INET;
|
|
if (inet_pton(AF_INET, host ? host : "0.0.0.0", &addr.sin_addr) != 1)
|
|
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
|
addr.sin_port = htons((unsigned short)port);
|
|
if (bind(ls, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
|
|
perror("bind");
|
|
close(ls);
|
|
return 1;
|
|
}
|
|
if (listen(ls, 64) != 0) {
|
|
perror("listen");
|
|
close(ls);
|
|
return 1;
|
|
}
|
|
/* Ein Prozess je Verbindung. Dabei NICHT SIGCHLD auf SIG_IGN setzen: das
|
|
* lässt den Kernel alle Kinder selbst einsammeln, und dann scheitert jedes
|
|
* pclose() im Programm mit ECHILD — popen sieht einen Fehler, obwohl das
|
|
* Kommando lief. Genau so scheiterten in skilld alle git-Aufrufe still.
|
|
* Stattdessen doppelt forken: das Zwischenkind beendet sich sofort, der
|
|
* Enkel gehört init und wird von dort eingesammelt. */
|
|
|
|
fprintf(stderr, "%s: http mcp on %s:%d (session %s)\n",
|
|
srv->name ? srv->name : "mcp", host ? host : "0.0.0.0", port, session);
|
|
for (;;) {
|
|
int fd = accept(ls, NULL, NULL);
|
|
pid_t pid;
|
|
|
|
if (fd < 0)
|
|
continue;
|
|
pid = fork();
|
|
if (pid == 0) {
|
|
pid_t grand = fork();
|
|
|
|
if (grand == 0) {
|
|
close(ls);
|
|
mcp_http_serve_one(fd, srv, session);
|
|
_exit(0);
|
|
}
|
|
_exit(0); /* Zwischenkind: sofort weg, kein Zombie */
|
|
}
|
|
if (pid > 0) {
|
|
int wstatus;
|
|
|
|
close(fd);
|
|
while (waitpid(pid, &wstatus, 0) < 0 && errno == EINTR)
|
|
;
|
|
} else {
|
|
mcp_http_serve_one(fd, srv, session);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* "--http 8781", "--http :8781" und "--http 0.0.0.0:8781" sind alle gemeint.
|
|
* atoi(":8781") is 0 — with the colon in front the server bound to a random
|
|
* free port that nobody could find. Skip past the last colon, then read. */
|
|
int mcp_parse_port(const char *s)
|
|
{
|
|
const char *p = strrchr(s, ':');
|
|
int port = atoi(p ? p + 1 : s);
|
|
|
|
if (port <= 0 || port > 65535) {
|
|
fprintf(stderr, "mcp: unusable port in '%s' (want 8781, :8781 or 0.0.0.0:8781)\n", s);
|
|
return -1;
|
|
}
|
|
return port;
|
|
}
|
|
|
|
|
|
#endif /* MCP_IMPLEMENTATION */
|
|
|
|
#endif /* MCP_H */
|