/* Test-only MCP server: streamable HTTP on 127.0.0.1 (each connection in a process of its own,
* every request saved), or stdio (one JSON-RPC message per line). It exits on its own deadline,
* so a failed test cannot leave it running.
*
* Usage: fake_mcp PORT_FILE LOG_DIR DEADLINE_SECONDS ERA [sse]
* fake_mcp --stdio LOG_DIR DEADLINE_SECONDS ERA
* ERA modern: speaks 2026-07-28 only (server/discover, _meta on every request, no session).
* ERA legacy: speaks the 2025-11-25 handshake only (initialize, notifications/initialized, a
* session id over HTTP); anything else first is refused as a 2025 server does.
* sse: requests are answered with an SSE stream (a progress notification, then the
* response) instead of JSON.
* Requests are saved as LOG_DIR/k.req (HTTP: headers and body) or appended to LOG_DIR/stdio.log
* (one line each). LOG_DIR/ledger gets a line per call of a tool that is not read-only, written
* before it answers. Its tools (tools/list in two pages):
* echo read-only: "echo: ARGUMENTS"
* write_note appends to the ledger: "noted"
* fail isError with "it failed"
* boom a JSON-RPC error -32000 "boom"
* slow answers after 30 seconds
* die appends to the ledger, then the server exits without answering
* big 30000 bytes of text, 'a' then 'z' */
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
static time_t deadline;
static int modern, use_sse, stdio_mode;
static const char *log_dir;
static void die(const char *what) {
perror(what);
exit(2);
}
static int send_all(int fd, const char *p, size_t n) {
while (n > 0) {
ssize_t w = write(fd, p, n);
if (w < 0) {
if (errno == EINTR) {
continue;
}
return -1;
}
p += w;
n -= (size_t)w;
}
return 0;
}
static void ledger(const char *line) {
char path[1100];
FILE *f;
(void)snprintf(path, sizeof path, "%s/ledger", log_dir);
if (!(f = fopen(path, "a")) || fprintf(f, "%s\n", line) < 0 || fclose(f) != 0) {
die(path);
}
}
/* The JSON value after "KEY": in S (the first such key), copied into OUT: a string's contents
* (no unescaping), or a number, object or array as written. 0, or -1 when it is not there. */
static int field(const char *s, const char *key, char *out, size_t cap) {
char pat[128];
const char *p, *e;
(void)snprintf(pat, sizeof pat, "\"%s\":", key);
if (!(p = strstr(s, pat))) {
return -1;
}
p += strlen(pat);
while (*p == ' ') {
p++;
}
if (*p == '"') {
for (e = ++p; *e && *e != '"'; e++) {
if (*e == '\\' && e[1]) {
e++;
}
}
} else if (*p == '{' || *p == '[') {
int depth = 0, in_str = 0;
for (e = p; *e; e++) {
if (in_str) {
if (*e == '\\' && e[1]) {
e++;
} else if (*e == '"') {
in_str = 0;
}
} else if (*e == '"') {
in_str = 1;
} else if (*e == '{' || *e == '[') {
depth++;
} else if ((*e == '}' || *e == ']') && --depth == 0) {
e++;
break;
}
}
} else {
e = p + strcspn(p, ",}] \r\n");
}
if ((size_t)(e - p) >= cap) {
return -1;
}
memcpy(out, p, (size_t)(e - p));
out[e - p] = '\0';
return 0;
}
static const char page1[] =
"{\"name\":\"echo\",\"description\":\"Echoes its arguments.\",\"inputSchema\":{\"type\":\"object\","
"\"properties\":{\"text\":{\"type\":\"string\"}}},\"annotations\":{\"readOnlyHint\":true}},"
"{\"name\":\"write_note\",\"description\":\"Writes a note.\",\"inputSchema\":{\"type\":\"object\","
"\"properties\":{\"note\":{\"type\":\"string\"}}}},"
"{\"name\":\"fail\",\"description\":\"Always fails.\",\"inputSchema\":{\"type\":\"object\"}},"
"{\"name\":\"boom\",\"description\":\"A protocol error.\",\"inputSchema\":{\"type\":\"object\"}}";
static const char page2[] =
"{\"name\":\"slow\",\"description\":\"Takes thirty seconds.\",\"inputSchema\":{\"type\":\"object\"}},"
"{\"name\":\"die\",\"description\":\"Exits mid-call.\",\"inputSchema\":{\"type\":\"object\"}},"
"{\"name\":\"big\",\"description\":\"A long answer.\",\"inputSchema\":{\"type\":\"object\"},"
"\"annotations\":{\"readOnlyHint\":true}}";
/* A JSON string's body for TEXT (quotes and backslashes escaped), malloc'd. */
static char *quoted(const char *text) {
size_t n = strlen(text);
char *out = malloc(2 * n + 1), *o = out;
if (!out) {
die("malloc");
}
for (const char *p = text; *p; p++) {
if (*p == '"' || *p == '\\') {
*o++ = '\\';
}
*o++ = *p;
}
*o = '\0';
return out;
}
/* The answer to one JSON-RPC message BODY (malloc'd), or NULL for none (a notification). *STATUS
* gets the HTTP status; *SESSION is set when the answer starts a session. A call to die exits. */
static char *answer(const char *body, const char *version_header, const char *session_header, int *status,
int *session) {
char method[128] = "", id[64] = "", name[128] = "", args[8192] = "{}", proto[64] = "";
char *out = malloc(65536);
const char *rt = modern ? "\"resultType\":\"complete\"," : "";
if (!out) {
die("malloc");
}
*status = 200;
*session = 0;
(void)field(body, "method", method, sizeof method);
if (field(body, "id", id, sizeof id) != 0) {
free(out);
*status = 202;
return NULL; /* a notification */
}
if (modern) {
if (field(body, "io.modelcontextprotocol/protocolVersion", proto, sizeof proto) != 0 ||
(!stdio_mode && (!version_header || strcmp(version_header, proto) != 0))) {
*status = 400;
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32020,\"message\":\"header mismatch\"}}", id);
return out;
}
if (strcmp(proto, "2026-07-28") != 0) {
*status = 400;
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32022,\"message\":\"unsupported\","
"\"data\":{\"supported\":[\"2026-07-28\"],\"requested\":\"%s\"}}}",
id, proto);
return out;
}
} else if (strcmp(method, "initialize") != 0 && !stdio_mode && (!session_header || strcmp(session_header, "sess-1") != 0)) {
*status = 400;
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32600,\"message\":\"Bad Request: Server not "
"initialized\"}}");
return out;
} else if (!stdio_mode && strcmp(method, "initialize") != 0 && (!version_header || strcmp(version_header, "2025-11-25") != 0)) {
*status = 400;
(void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32600,\"message\":\"bad version\"}}", id);
return out;
}
if (strcmp(method, "server/discover") == 0 && modern) {
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"supportedVersions\":[\"2026-07-28\"],"
"\"capabilities\":{\"tools\":{}},\"instructions\":\"A fake server for tests.\","
"\"_meta\":{\"io.modelcontextprotocol/serverInfo\":{\"name\":\"fake\",\"version\":\"1\"}}}}",
id, rt);
} else if (strcmp(method, "initialize") == 0 && !modern) {
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"protocolVersion\":\"2025-11-25\","
"\"capabilities\":{\"tools\":{}},\"serverInfo\":{\"name\":\"fake\",\"version\":\"1\"},"
"\"instructions\":\"A fake server for tests.\"}}",
id);
*session = 1;
} else if (strcmp(method, "tools/list") == 0) {
char cursor[64] = "";
int second = field(body, "cursor", cursor, sizeof cursor) == 0 && strcmp(cursor, "p2") == 0;
(void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"tools\":[%s]%s}}", id, rt,
second ? page2 : page1, second ? "" : ",\"nextCursor\":\"p2\"");
} else if (strcmp(method, "tools/call") == 0) {
char *q;
(void)field(body, "name", name, sizeof name);
(void)field(body, "arguments", args, sizeof args);
if (strcmp(name, "echo") == 0) {
q = quoted(args);
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"content\":[{\"type\":\"text\",\"text\":\"echo: %s\"}],"
"\"isError\":false}}",
id, rt, q);
free(q);
} else if (strcmp(name, "write_note") == 0) {
ledger(args);
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"content\":[{\"type\":\"text\",\"text\":\"noted\"}]}}",
id, rt);
} else if (strcmp(name, "fail") == 0) {
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"content\":[{\"type\":\"text\",\"text\":\"it failed\"}],"
"\"isError\":true}}",
id, rt);
} else if (strcmp(name, "boom") == 0) {
(void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32000,\"message\":\"boom\"}}", id);
} else if (strcmp(name, "slow") == 0) {
sleep(30);
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"content\":[{\"type\":\"text\",\"text\":\"late\"}]}}",
id, rt);
} else if (strcmp(name, "die") == 0) {
ledger(args);
if (stdio_mode) {
exit(3);
}
kill(getppid(), SIGTERM); /* the listening server too */
_exit(3);
} else if (strcmp(name, "big") == 0) {
int n = snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"content\":[{\"type\":\"text\",\"text\":\"", id, rt);
memset(out + n, 'a', 15000);
memset(out + n + 15000, 'z', 15000);
(void)snprintf(out + n + 30000, 65536 - (size_t)n - 30000, "\"}]}}");
} else {
(void)snprintf(out, 65536,
"{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602,\"message\":\"Unknown tool: %s\"}}", id, name);
}
} else {
(void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601,\"message\":\"Method not found\"}}", id);
}
return out;
}
/* ---- streamable HTTP --------------------------------------------------------------------- */
/* The value of header NAME (case as written by pic) in the request REQ, into OUT, or NULL. */
static const char *header(const char *req, const char *name, char *out, size_t cap) {
const char *end = strstr(req, "\r\n\r\n");
size_t n = strlen(name);
for (const char *p = strstr(req, "\r\n"); p && p < end; p = strstr(p + 2, "\r\n")) {
if (strncasecmp(p + 2, name, n) == 0 && p[2 + n] == ':') {
const char *v = p + 3 + n, *e;
while (*v == ' ') {
v++;
}
e = strstr(v, "\r\n");
(void)snprintf(out, cap, "%.*s", (int)(e - v), v);
return out;
}
}
return NULL;
}
static void serve(int fd, int k) {
size_t cap = 1 << 20, used = 0, want = 0;
char *buf = malloc(cap + 1), *end = NULL, path[1100], vh[64], sh[64], head[512];
const char *version, *sess;
char *reply;
int status, session, h;
FILE *f;
if (!buf) {
die("malloc");
}
while (!end || used < want) {
struct pollfd p = {fd, POLLIN, 0};
ssize_t r;
if (time(NULL) >= deadline || poll(&p, 1, 1000) < 0) {
break;
}
if (!(p.revents & (POLLIN | POLLHUP))) {
continue;
}
r = recv(fd, buf + used, cap - used, 0);
if (r <= 0) {
break;
}
used += (size_t)r;
buf[used] = '\0';
if (!end && (end = strstr(buf, "\r\n\r\n"))) {
const char *cl = strstr(buf, "Content-Length: ");
want = (size_t)(end + 4 - buf) + (cl ? strtoul(cl + 16, NULL, 10) : 0);
}
}
(void)snprintf(path, sizeof path, "%s/%d.req", log_dir, k);
if (!(f = fopen(path, "wb")) || fwrite(buf, 1, used, f) != used || fclose(f) != 0) {
die(path);
}
if (!end) {
free(buf);
return;
}
if (strncmp(buf, "DELETE ", 7) == 0 || strncmp(buf, "GET ", 4) == 0) {
static const char gone[] = "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
static const char ok[] = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
(void)(modern || buf[0] == 'G' ? send_all(fd, gone, sizeof gone - 1) : send_all(fd, ok, sizeof ok - 1));
free(buf);
return;
}
version = header(buf, "MCP-Protocol-Version", vh, sizeof vh);
sess = header(buf, "Mcp-Session-Id", sh, sizeof sh);
reply = answer(end + 4, version, sess, &status, &session);
if (!reply) {
h = snprintf(head, sizeof head, "HTTP/1.1 %d Accepted\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", status);
(void)send_all(fd, head, (size_t)h);
} else if (use_sse && status == 200) {
static const char progress[] =
"event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\",\"params\":"
"{\"progressToken\":1,\"progress\":1}}\n\n";
h = snprintf(head, sizeof head, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n%sConnection: close\r\n\r\n",
session ? "Mcp-Session-Id: sess-1\r\n" : "");
(void)(send_all(fd, head, (size_t)h) || send_all(fd, progress, sizeof progress - 1) ||
send_all(fd, "event: message\ndata: ", 21) || send_all(fd, reply, strlen(reply)) || send_all(fd, "\n\n", 2));
} else {
h = snprintf(head, sizeof head,
"HTTP/1.1 %d Fake\r\nContent-Type: application/json\r\n%sContent-Length: %zu\r\nConnection: close\r\n\r\n",
status, session ? "Mcp-Session-Id: sess-1\r\n" : "", strlen(reply));
(void)(send_all(fd, head, (size_t)h) || send_all(fd, reply, strlen(reply)));
}
free(reply);
free(buf);
}
/* ---- stdio ------------------------------------------------------------------------------ */
static int stdio_main(void) {
char path[1100], *line = NULL;
size_t cap = 0;
ssize_t n;
FILE *logf;
(void)snprintf(path, sizeof path, "%s/stdio.log", log_dir);
while ((n = getline(&line, &cap, stdin)) > 0 && time(NULL) < deadline) {
int status, session;
char *reply;
if (!(logf = fopen(path, "a")) || fputs(line, logf) < 0 || fclose(logf) != 0) {
die(path);
}
reply = answer(line, NULL, NULL, &status, &session);
if (reply) {
(void)(send_all(1, reply, strlen(reply)) || send_all(1, "\n", 1));
free(reply);
}
}
free(line);
return 0;
}
int main(int argc, char **argv) {
struct sockaddr_in addr;
socklen_t alen = sizeof addr;
int lfd, one = 1;
FILE *pf;
if (argc >= 5 && strcmp(argv[1], "--stdio") == 0) {
stdio_mode = 1;
log_dir = argv[2];
deadline = time(NULL) + atoi(argv[3]);
modern = strcmp(argv[4], "modern") == 0;
return stdio_main();
}
if (argc < 5) {
fprintf(stderr, "usage: fake_mcp PORT_FILE LOG_DIR DEADLINE_SECONDS modern|legacy [sse]\n"
" fake_mcp --stdio LOG_DIR DEADLINE_SECONDS modern|legacy\n");
return 2;
}
log_dir = argv[2];
modern = strcmp(argv[4], "modern") == 0;
use_sse = argc > 5 && strcmp(argv[5], "sse") == 0;
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
deadline = time(NULL) + atoi(argv[3]);
lfd = socket(AF_INET, SOCK_STREAM, 0);
if (lfd < 0 || setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one) != 0) {
die("socket");
}
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(lfd, (struct sockaddr *)&addr, sizeof addr) != 0 || listen(lfd, 16) != 0 ||
getsockname(lfd, (struct sockaddr *)&addr, &alen) != 0) {
die("bind");
}
{
char tmp[1100];
(void)snprintf(tmp, sizeof tmp, "%s.tmp", argv[1]);
pf = fopen(tmp, "w");
if (!pf || fprintf(pf, "%d\n", ntohs(addr.sin_port)) < 0 || fclose(pf) != 0 || rename(tmp, argv[1]) != 0) {
die(argv[1]);
}
}
for (int k = 1; time(NULL) < deadline;) {
struct pollfd p = {lfd, POLLIN, 0};
int fd;
pid_t pid;
if (poll(&p, 1, 200) <= 0 || (fd = accept(lfd, NULL, NULL)) < 0) {
continue;
}
pid = fork();
if (pid == 0) {
close(lfd);
serve(fd, k);
_exit(0);
}
k++;
close(fd);
}
return 0;
}