/* 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). A stdio server appends its pid to LOG_DIR/pids and its working directory to * LOG_DIR/cwd when it starts, and FAKE_MCP_TOKEN's value, when set, to LOG_DIR/env. 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' * With FAKE_MCP_RESOURCES set it offers resources too (resources/list in two pages, an MCP App * among them; resources/templates/list; resources/read): * file:///notes.txt text "hello from a resource" * img://dot.png a 1x1 PNG * bin://blob 5 bytes of application/octet-stream * ui://app an MCP App (text/html;profile=mcp-app) * anything else error -32002 "Resource not found" * With FAKE_MCP_PREFIX set, every tool's name starts with it (and a call names it so). * With FAKE_MCP_RESOURCES=many its resources/list never ends: 400 resources a page, always with * a next cursor. */ #include #include #include #include #include #include #include #include #include #include #include static time_t deadline; static int modern, use_sse, stdio_mode, resources, endless; static const char *tool_prefix = ""; 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}}"; /* TOOLS (a tools/list page) with tool_prefix before each name, malloc'd. */ static char *prefixed(const char *tools) { size_t np = strlen(tool_prefix), n = strlen(tools); char *out = malloc(n + 16 * np + 1), *o = out; if (!out) { die("malloc"); } for (const char *p = tools; *p;) { if (strncmp(p, "{\"name\":\"", 9) == 0) { memcpy(o, p, 9); o += 9; p += 9; memcpy(o, tool_prefix, np); o += np; } else { *o++ = *p++; } } *o = '\0'; return out; } /* 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\":{}%s},\"instructions\":\"A fake server for tests.\"," "\"_meta\":{\"io.modelcontextprotocol/serverInfo\":{\"name\":\"fake\",\"version\":\"1\"}}}}", id, rt, resources ? ",\"resources\":{}" : ""); } else if (strcmp(method, "initialize") == 0 && !modern) { (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"protocolVersion\":\"2025-11-25\"," "\"capabilities\":{\"tools\":{}%s},\"serverInfo\":{\"name\":\"fake\",\"version\":\"1\"}," "\"instructions\":\"A fake server for tests.\"}}", id, resources ? ",\"resources\":{}" : ""); *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; char *page = prefixed(second ? page2 : page1); (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"tools\":[%s]%s}}", id, rt, page, second ? "" : ",\"nextCursor\":\"p2\""); free(page); } else if (endless && strcmp(method, "resources/list") == 0) { char cursor[64] = ""; int page = field(body, "cursor", cursor, sizeof cursor) == 0 && cursor[0] == 'r' ? atoi(cursor + 1) : 0; int n = snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"resources\":[", id, rt); for (int k = 0; k < 400; k++) { n += snprintf(out + n, 65536 - (size_t)n, "%s{\"uri\":\"file:///p%d/item-%04d.txt\",\"name\":\"item %d\"}", k ? "," : "", page, k, k); } (void)snprintf(out + n, 65536 - (size_t)n, "],\"nextCursor\":\"r%d\"}}", page + 1); } else if (resources && strcmp(method, "resources/list") == 0) { char cursor[64] = ""; int second = field(body, "cursor", cursor, sizeof cursor) == 0 && strcmp(cursor, "r2") == 0; (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"resources\":[%s]%s}}", id, rt, second ? "{\"uri\":\"img://dot.png\",\"name\":\"dot\",\"mimeType\":\"image/png\"}," "{\"uri\":\"ui://app\",\"name\":\"app\",\"mimeType\":\"text/html;profile=mcp-app\"}" : "{\"uri\":\"file:///notes.txt\",\"name\":\"notes\",\"mimeType\":\"text/plain\"}," "{\"uri\":\"bin://blob\",\"name\":\"blob\"}", second ? "" : ",\"nextCursor\":\"r2\""); } else if (resources && strcmp(method, "resources/templates/list") == 0) { (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"resourceTemplates\":[{\"uriTemplate\":\"file:///{path}\"," "\"name\":\"files\"}]}}", id, rt); } else if (resources && strcmp(method, "resources/read") == 0) { char uri[256] = ""; (void)field(body, "uri", uri, sizeof uri); if (strcmp(uri, "file:///notes.txt") == 0) { (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"contents\":[{\"uri\":\"%s\",\"mimeType\":" "\"text/plain\",\"text\":\"hello from a resource\"}]}}", id, rt, uri); } else if (strcmp(uri, "img://dot.png") == 0) { (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"contents\":[{\"uri\":\"%s\",\"mimeType\":" "\"image/png\",\"blob\":\"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==\"}]}}", id, rt, uri); } else if (strcmp(uri, "bin://blob") == 0) { (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{%s\"contents\":[{\"uri\":\"%s\",\"mimeType\":" "\"application/octet-stream\",\"blob\":\"AAECAwQ=\"}]}}", id, rt, uri); } else { (void)snprintf(out, 65536, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32002,\"message\":\"Resource not found\"}}", id); } } else if (strcmp(method, "tools/call") == 0) { char *q; (void)field(body, "name", name, sizeof name); if (*tool_prefix && strncmp(name, tool_prefix, strlen(tool_prefix)) == 0) { memmove(name, name + strlen(tool_prefix), strlen(name) - strlen(tool_prefix) + 1); } (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; { char cwd[1024]; const char *token = getenv("FAKE_MCP_TOKEN"); FILE *f; (void)snprintf(path, sizeof path, "%s/pids", log_dir); if ((f = fopen(path, "a"))) { fprintf(f, "%ld\n", (long)getpid()); fclose(f); } (void)snprintf(path, sizeof path, "%s/cwd", log_dir); if (getcwd(cwd, sizeof cwd) && (f = fopen(path, "a"))) { fprintf(f, "%s\n", cwd); fclose(f); } (void)snprintf(path, sizeof path, "%s/env", log_dir); if (token && (f = fopen(path, "a"))) { fprintf(f, "%s\n", token); fclose(f); } } (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; resources = getenv("FAKE_MCP_RESOURCES") != NULL; tool_prefix = getenv("FAKE_MCP_PREFIX") ? getenv("FAKE_MCP_PREFIX") : ""; endless = resources && strcmp(getenv("FAKE_MCP_RESOURCES"), "many") == 0; 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; }