tinyblocks-mcp-server (C, sem Python): servidor MCP nas duas eras do protocolo. Moderna (2026-07-28): sem handshake, versão e capacidades em _meta a cada pedido, server/discover, resultType, cabeçalhos MCP-Protocol-Version/Mcp-Method/Mcp-Name conferidos com o corpo (HeaderMismatch, UnsupportedProtocolVersion). Antiga: initialize. HTTP só em 127.0.0.1 (Origin conferido, GET/DELETE 405, sem sessão), sem bloquear (o editor atende a cada quadro), e stdio. test-mcp-server. Ferramentas do editor (tb_editor_mcp.c; http://127.0.0.1:7811/mcp, TINYBLOCKS_MCP_PORT muda a porta, 0 = sem rede): get_editor, list_block_types, list_stacks (scratchblocks + ids dos blocos), get_scratchblocks, add_scratchblocks, replace_stack, move_stack, delete_stack, add_block / move_block (solto, embaixo, num campo ou numa boca; alone = só o bloco) / delete_block / set_inputs, run / stop / get_output, new_tab / select_tab, save_project / open_project e ui_tree / ui_action / ui_type (a interface pela árvore acessível). O editor exporta e importa scratchblocks por pilha (numa aba existente, numa posição), e o modelo de blocos fica na API privada para o servidor. O scratchblocks usa também os rótulos declarados pelas libraries. Duplicar um bloco C de três bocas copiava só duas. O cliente (tinyblocks-mcp) fala as duas eras: sonda com server/discover no stdio, pedido moderno no HTTP, e cai para o initialize com servidores antigos. test-mcp testa contra o servidor antigo de teste e contra o moderno (stdio e HTTP); harness cenário 29 usa as ferramentas do editor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
231 lines
12 KiB
C
231 lines
12 KiB
C
/* Teste da tinyblocks-mcp-server: as duas eras do protocolo (handle direto),
|
|
* validacao dos cabecalhos HTTP, stdio e o HTTP de verdade (um processo
|
|
* filho serve, o teste pede por socket). */
|
|
#define _POSIX_C_SOURCE 200809L
|
|
#include <signal.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <arpa/inet.h>
|
|
#include <netinet/in.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/wait.h>
|
|
#include <time.h>
|
|
#include <tb_mcp_server.h>
|
|
|
|
static int fails = 0;
|
|
#define CHECK(cond, msg) do { if (cond) printf("ok %s\n", msg); else { printf("FAIL %s\n", msg); fails++; } } while (0)
|
|
|
|
static void soma(void* user, TbMcpRequest* rq) {
|
|
int* calls = user;
|
|
(*calls)++;
|
|
if (!tb_mcp_req_has(rq, "a")) { tb_mcp_req_error(rq, "falta o argumento a"); return; }
|
|
double r = tb_mcp_req_num(rq, "a", 0) + tb_mcp_req_num(rq, "b", 0);
|
|
TinyBlocks_JsonValue* o = tb_json_object();
|
|
TinyBlocks_JsonValue* n = tb_json_number(r);
|
|
tb_json_object_set(o, "soma", n);
|
|
tb_json_release(n);
|
|
tb_mcp_req_structured(rq, o);
|
|
}
|
|
|
|
static void eco(void* user, TbMcpRequest* rq) {
|
|
(void)user;
|
|
tb_mcp_req_text(rq, "eco: %s", tb_mcp_req_str(rq, "texto", ""));
|
|
}
|
|
|
|
static const TbMcpTool T_SOMA = { "soma", "Soma", "Soma a e b",
|
|
"{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"number\"},\"b\":{\"type\":\"number\"}}}",
|
|
TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, soma };
|
|
static const TbMcpTool T_ECO = { "eco", "Eco", "Devolve o texto",
|
|
"{\"type\":\"object\",\"properties\":{\"texto\":{\"type\":\"string\"}}}", 0, eco };
|
|
|
|
#define MODERN_META "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"," \
|
|
"\"io.modelcontextprotocol/clientCapabilities\":{}," \
|
|
"\"io.modelcontextprotocol/clientInfo\":{\"name\":\"teste\",\"version\":\"1\"}}"
|
|
|
|
static void sleep_ms(long ms) {
|
|
struct timespec ts = { ms / 1000, (ms % 1000) * 1000000L };
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
|
|
static bool has(const char* s, const char* sub) { return s && strstr(s, sub); }
|
|
|
|
/* Pedido HTTP cru; devolve status e corpo (malloc) */
|
|
static int http(int port, const char* method, const char* extra_headers, const char* body, char** out) {
|
|
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
|
struct sockaddr_in a;
|
|
memset(&a, 0, sizeof(a));
|
|
a.sin_family = AF_INET;
|
|
a.sin_port = htons((unsigned short)port);
|
|
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
|
for (int i = 0; i < 50 && connect(fd, (struct sockaddr*)&a, sizeof(a)) != 0; i++) sleep_ms(20);
|
|
char req[4096];
|
|
int n = snprintf(req, sizeof(req), "%s /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\n%sContent-Length: %zu\r\n\r\n%s",
|
|
method, extra_headers ? extra_headers : "", body ? strlen(body) : 0, body ? body : "");
|
|
send(fd, req, (size_t)n, 0);
|
|
size_t cap = 65536, len = 0;
|
|
char* buf = malloc(cap);
|
|
ssize_t r;
|
|
while ((r = recv(fd, buf + len, cap - len - 1, 0)) > 0) len += (size_t)r;
|
|
buf[len] = 0;
|
|
close(fd);
|
|
int status = 0;
|
|
sscanf(buf, "HTTP/1.1 %d", &status);
|
|
char* b = strstr(buf, "\r\n\r\n");
|
|
*out = strdup(b ? b + 4 : "");
|
|
free(buf);
|
|
return status;
|
|
}
|
|
|
|
int main(void) {
|
|
int calls = 0;
|
|
TbMcpServer* s = tb_mcp_server_new("tb-teste", "9.9", "Servidor de teste.");
|
|
tb_mcp_server_add_tool(s, &T_SOMA, &calls);
|
|
tb_mcp_server_add_tool(s, &T_ECO, NULL);
|
|
int st;
|
|
char* r;
|
|
|
|
/* -- era moderna (2026-07-28) -- */
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":\"d1\",\"method\":\"server/discover\",\"params\":{" MODERN_META "}}", NULL, &st);
|
|
CHECK(st == 200 && has(r, "\"id\":\"d1\"") && has(r, "\"supportedVersions\":[\"2026-07-28\"") &&
|
|
has(r, "\"resultType\":\"complete\"") && has(r, "\"io.modelcontextprotocol/serverInfo\":{\"name\":\"tb-teste\"") &&
|
|
has(r, "\"instructions\":\"Servidor de teste.\""), "moderno: server/discover");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{" MODERN_META "}}", NULL, &st);
|
|
CHECK(st == 200 && has(r, "\"name\":\"soma\"") && has(r, "\"name\":\"eco\"") && has(r, "\"readOnlyHint\":true") &&
|
|
has(r, "\"ttlMs\":") && has(r, "\"cacheScope\":\"private\"") && strstr(r, "soma") < strstr(r, "\"eco\""),
|
|
"moderno: tools/list (ordem fixa, dicas, cache)");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\","
|
|
"\"arguments\":{\"a\":2,\"b\":40}," MODERN_META "}}", NULL, &st);
|
|
CHECK(st == 200 && has(r, "\"structuredContent\":{\"soma\":42}") && has(r, "\"text\":\"{\\\"soma\\\":42}\"") &&
|
|
has(r, "\"isError\":false") && calls == 1, "moderno: tools/call com resultado estruturado (e o JSON em texto)");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\","
|
|
"\"arguments\":{}," MODERN_META "}}", NULL, &st);
|
|
CHECK(has(r, "\"isError\":true") && has(r, "falta o argumento a"), "erro da ferramenta: isError com a mensagem");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\",\"params\":{\"name\":\"nao\"," MODERN_META "}}", NULL, &st);
|
|
CHECK(has(r, "\"code\":-32602") && has(r, "Ferramenta desconhecida"), "ferramenta desconhecida: -32602");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"tools/list\",\"params\":{\"_meta\":{"
|
|
"\"io.modelcontextprotocol/protocolVersion\":\"1900-01-01\","
|
|
"\"io.modelcontextprotocol/clientCapabilities\":{}}}}", NULL, &st);
|
|
CHECK(st == 400 && has(r, "\"code\":-32022") && has(r, "\"supported\":[\"2026-07-28\"]") &&
|
|
has(r, "\"requested\":\"1900-01-01\""), "versão desconhecida: -32022 com as suportadas");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/list\",\"params\":{\"_meta\":{"
|
|
"\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"}}}", NULL, &st);
|
|
CHECK(st == 400 && has(r, "\"code\":-32602"), "sem clientCapabilities: -32602 (400)");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"x/y\",\"params\":{" MODERN_META "}}", NULL, &st);
|
|
CHECK(st == 404 && has(r, "\"code\":-32601"), "método desconhecido: -32601 (404)");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{quebrado", NULL, &st);
|
|
CHECK(st == 400 && has(r, "\"code\":-32700"), "JSON inválido: -32700");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{}}", NULL, &st);
|
|
CHECK(!r && st == 202, "notificação: sem resposta (202)");
|
|
|
|
/* cabecalhos HTTP espelham o corpo */
|
|
const char* call = "{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"tools/call\",\"params\":{\"name\":\"eco\","
|
|
"\"arguments\":{\"texto\":\"oi\"}," MODERN_META "}}";
|
|
TbMcpHttpHeaders h = { "2026-07-28", "tools/call", "eco" };
|
|
r = tb_mcp_server_handle(s, call, &h, &st);
|
|
CHECK(st == 200 && has(r, "eco: oi"), "HTTP: cabeçalhos certos passam");
|
|
free(r);
|
|
h.name = "=?base64?ZWNv?="; /* "eco" em base64 */
|
|
r = tb_mcp_server_handle(s, call, &h, &st);
|
|
CHECK(st == 200 && has(r, "eco: oi"), "HTTP: Mcp-Name em base64 é decodificado");
|
|
free(r);
|
|
h.name = "soma";
|
|
r = tb_mcp_server_handle(s, call, &h, &st);
|
|
CHECK(st == 400 && has(r, "\"code\":-32020"), "HTTP: Mcp-Name diferente do corpo: -32020");
|
|
free(r);
|
|
h.name = "eco"; h.method = NULL;
|
|
r = tb_mcp_server_handle(s, call, &h, &st);
|
|
CHECK(st == 400 && has(r, "\"code\":-32020"), "HTTP: sem Mcp-Method: -32020");
|
|
free(r);
|
|
h.method = "tools/call"; h.protocol_version = "2025-11-25";
|
|
r = tb_mcp_server_handle(s, call, &h, &st);
|
|
CHECK(st == 400 && has(r, "\"code\":-32020"), "HTTP: versão do cabeçalho diferente do _meta: -32020");
|
|
free(r);
|
|
|
|
/* -- era antiga (initialize) -- */
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{"
|
|
"\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},"
|
|
"\"clientInfo\":{\"name\":\"velho\",\"version\":\"1\"}}}", NULL, &st);
|
|
CHECK(st == 200 && has(r, "\"protocolVersion\":\"2025-06-18\"") && has(r, "\"serverInfo\":{\"name\":\"tb-teste\"") &&
|
|
has(r, "\"tools\":{"), "antigo: initialize negocia a versão pedida");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{"
|
|
"\"protocolVersion\":\"2099-01-01\",\"capabilities\":{}}}", NULL, &st);
|
|
CHECK(has(r, "\"protocolVersion\":\"2025-11-25\""), "antigo: versão desconhecida no initialize -> a mais nova antiga");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"eco\","
|
|
"\"arguments\":{\"texto\":\"velho\"}}}", NULL, &st);
|
|
CHECK(st == 200 && has(r, "eco: velho"), "antigo: tools/call sem _meta");
|
|
free(r);
|
|
r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\"}", NULL, &st);
|
|
CHECK(st == 200 && has(r, "\"result\""), "antigo: ping");
|
|
free(r);
|
|
|
|
/* -- stdio -- */
|
|
{
|
|
const char* in_text =
|
|
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{}}}\n"
|
|
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n"
|
|
"\n"
|
|
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"eco\",\"arguments\":{\"texto\":\"linha\"}}}\n";
|
|
FILE* in = fmemopen((void*)in_text, strlen(in_text), "r");
|
|
char* outbuf = NULL;
|
|
size_t outlen = 0;
|
|
FILE* out = open_memstream(&outbuf, &outlen);
|
|
int n = tb_mcp_server_serve_stdio(s, in, out);
|
|
fclose(in);
|
|
fclose(out);
|
|
CHECK(n == 2 && has(outbuf, "\"id\":1") && has(outbuf, "eco: linha") && strchr(outbuf, '\n') < strrchr(outbuf, '\n'),
|
|
"stdio: uma resposta por linha, notificação sem resposta");
|
|
free(outbuf);
|
|
}
|
|
|
|
/* -- HTTP de verdade -- */
|
|
CHECK(tb_mcp_server_listen(s, 0) && tb_mcp_server_port(s) > 0, "HTTP: escuta numa porta livre de 127.0.0.1");
|
|
int port = tb_mcp_server_port(s);
|
|
fflush(stdout);
|
|
pid_t child = fork();
|
|
if (child == 0) { for (;;) { tb_mcp_server_poll(s); sleep_ms(2); } }
|
|
char* b = NULL;
|
|
char hdr[512];
|
|
snprintf(hdr, sizeof(hdr), "Content-Type: application/json\r\nAccept: application/json, text/event-stream\r\n"
|
|
"MCP-Protocol-Version: 2026-07-28\r\nMcp-Method: tools/call\r\nMcp-Name: soma\r\n");
|
|
st = http(port, "POST", hdr, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\","
|
|
"\"arguments\":{\"a\":1,\"b\":1}," MODERN_META "}}", &b);
|
|
CHECK(st == 200 && has(b, "\"soma\":2"), "HTTP: POST /mcp moderno");
|
|
free(b);
|
|
st = http(port, "POST", "MCP-Protocol-Version: 2026-07-28\r\nMcp-Method: tools/list\r\n",
|
|
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\"," MODERN_META "}}", &b);
|
|
CHECK(st == 400 && has(b, "-32020"), "HTTP: cabeçalho que não bate dá 400 HeaderMismatch");
|
|
free(b);
|
|
st = http(port, "POST", "Origin: http://malicioso.example\r\n", "{}", &b);
|
|
CHECK(st == 403, "HTTP: Origin de fora dá 403");
|
|
free(b);
|
|
st = http(port, "POST", "Origin: http://localhost:5173\r\n",
|
|
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-03-26\",\"capabilities\":{}}}", &b);
|
|
CHECK(st == 200 && has(b, "\"protocolVersion\":\"2025-03-26\""), "HTTP: Origin local e initialize antigo");
|
|
free(b);
|
|
st = http(port, "POST", NULL, "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", &b);
|
|
CHECK(st == 202 && !b[0], "HTTP: notificação dá 202 sem corpo");
|
|
free(b);
|
|
st = http(port, "GET", NULL, NULL, &b);
|
|
CHECK(st == 405, "HTTP: GET dá 405 (sem stream nem sessão)");
|
|
free(b);
|
|
kill(child, SIGTERM);
|
|
waitpid(child, NULL, 0);
|
|
|
|
tb_mcp_server_free(s);
|
|
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
|
|
return fails != 0;
|
|
}
|