Editor como servidor MCP: agentes leem e editam as pilhas por código

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>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-23 08:13:24 -03:00
1 parent 10a8099c46
commit 2a2d22a64a
19 files changed
+2669 -116

No files matched your search

@@ -0,0 +1,218 @@
/*
* TinyBlocks - tb_mcp_http.c
* Transporte "Streamable HTTP" do servidor MCP: um endpoint POST /mcp, so em
* 127.0.0.1, sem bloquear (tb_mcp_server_poll a cada quadro). Cada pedido e
* uma conexao: le cabecalhos + corpo (Content-Length), responde JSON, fecha.
*/
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "tb_mcp_server_internal.h"
#define MAX_REQUEST (4u << 20) /* 4 MiB por pedido */
#define CONN_TIMEOUT 5000u /* ms sem completar o pedido: larga */
static unsigned now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (unsigned)(ts.tv_sec * 1000u + (unsigned)(ts.tv_nsec / 1000000));
}
static void set_nonblock(int fd) {
int fl = fcntl(fd, F_GETFL, 0);
if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
bool tb_mcp_server_listen(TbMcpServer* s, int port) {
if (!s) return false;
tb_mcp_http_close(s);
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) return false;
int one = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
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); /* so a propria maquina */
if (bind(fd, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(fd, 16) != 0) { close(fd); return false; }
socklen_t al = sizeof(a);
getsockname(fd, (struct sockaddr*)&a, &al);
set_nonblock(fd);
s->listen_fd = fd;
s->port = ntohs(a.sin_port);
return true;
}
int tb_mcp_server_port(const TbMcpServer* s) { return s && s->listen_fd >= 0 ? s->port : 0; }
static void conn_drop(TbMcpServer* s, int i) {
close(s->conns[i].fd);
free(s->conns[i].buf);
s->conns[i] = s->conns[--s->conn_n];
}
void tb_mcp_http_close(TbMcpServer* s) {
while (s->conn_n > 0) conn_drop(s, 0);
if (s->listen_fd >= 0) close(s->listen_fd);
s->listen_fd = -1;
s->port = 0;
}
/* Valor de um cabecalho (nome sem diferenciar maiusculas); copia em out */
static bool header(const char* head, size_t head_len, const char* name, char* out, size_t cap) {
size_t nl = strlen(name);
const char* p = head;
const char* end = head + head_len;
while (p < end) {
const char* eol = memchr(p, '\n', (size_t)(end - p));
if (!eol) eol = end;
if ((size_t)(eol - p) > nl && !strncasecmp(p, name, nl) && p[nl] == ':') {
const char* v = p + nl + 1;
while (v < eol && (*v == ' ' || *v == '\t')) v++;
const char* ve = eol;
while (ve > v && (ve[-1] == '\r' || ve[-1] == ' ')) ve--;
size_t n = (size_t)(ve - v) < cap - 1 ? (size_t)(ve - v) : cap - 1;
memcpy(out, v, n);
out[n] = 0;
return true;
}
p = eol + 1;
}
return false;
}
static void send_all(int fd, const char* data, size_t n) {
int fl = fcntl(fd, F_GETFL, 0); /* a resposta sai inteira */
if (fl >= 0) fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
while (n > 0) {
ssize_t w = send(fd, data, n, MSG_NOSIGNAL);
if (w <= 0) { if (w < 0 && errno == EINTR) continue; return; }
data += w;
n -= (size_t)w;
}
}
static void respond(int fd, int status, const char* body) {
const char* reason = status == 200 ? "OK" : status == 202 ? "Accepted" : status == 400 ? "Bad Request" :
status == 403 ? "Forbidden" : status == 404 ? "Not Found" :
status == 405 ? "Method Not Allowed" : status == 413 ? "Payload Too Large" : "Error";
size_t bl = body ? strlen(body) : 0;
char head[256];
int hn = snprintf(head, sizeof(head),
"HTTP/1.1 %d %s\r\n%sContent-Length: %zu\r\nConnection: close\r\n%s\r\n",
status, reason, body ? "Content-Type: application/json\r\n" : "", bl,
status == 405 ? "Allow: POST\r\n" : "");
send_all(fd, head, (size_t)hn);
if (bl) send_all(fd, body, bl);
}
/* Origin presente precisa ser desta maquina (contra DNS rebinding) */
static bool origin_ok(const char* o) {
if (!o || !o[0] || !strcmp(o, "null")) return true;
const char* h = strstr(o, "://");
if (!h) return false;
h += 3;
static const char* local[] = { "localhost", "127.0.0.1", "[::1]" };
for (size_t i = 0; i < sizeof(local) / sizeof(local[0]); i++) {
size_t n = strlen(local[i]);
if (!strncmp(h, local[i], n) && (h[n] == 0 || h[n] == ':' || h[n] == '/')) return true;
}
return false;
}
/* Pedido completo? (cabecalhos + corpo). -1 = invalido / grande demais */
static int request_ready(TbMcpConn* c, size_t* head_len, size_t* body_len) {
char* sep = NULL;
for (size_t i = 0; i + 3 < c->len; i++)
if (!memcmp(c->buf + i, "\r\n\r\n", 4)) { sep = c->buf + i; break; }
if (!sep) return c->len > 65536 ? -1 : 0;
*head_len = (size_t)(sep - c->buf);
char v[32];
size_t cl = header(c->buf, *head_len, "Content-Length", v, sizeof(v)) ? strtoul(v, NULL, 10) : 0;
if (cl > MAX_REQUEST) return -1;
*body_len = cl;
return c->len >= *head_len + 4 + cl ? 1 : 0;
}
static void serve(TbMcpServer* s, TbMcpConn* c, size_t head_len, size_t body_len) {
char* head = c->buf;
head[head_len] = 0;
char method[8] = "", path[128] = "";
sscanf(head, "%7s %127s", method, path);
char* q = strchr(path, '?');
if (q) *q = 0;
char origin[256] = "";
header(head, head_len, "Origin", origin, sizeof(origin));
if (!origin_ok(origin)) {
respond(c->fd, 403, "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32600,\"message\":\"Origin nao permitido\"}}");
return;
}
if (strcmp(path, "/mcp") != 0) { respond(c->fd, 404, "{\"error\":\"o endpoint MCP e /mcp\"}"); return; }
if (strcmp(method, "POST") != 0) { respond(c->fd, 405, NULL); return; } /* sem stream GET nem sessao */
char ver[64] = "", mmethod[128] = "", mname[512] = "";
TbMcpHttpHeaders h = {
header(head, head_len, "MCP-Protocol-Version", ver, sizeof(ver)) ? ver : NULL,
header(head, head_len, "Mcp-Method", mmethod, sizeof(mmethod)) ? mmethod : NULL,
header(head, head_len, "Mcp-Name", mname, sizeof(mname)) ? mname : NULL,
};
char* body = malloc(body_len + 1);
if (!body) { respond(c->fd, 413, NULL); return; }
memcpy(body, c->buf + head_len + 4, body_len);
body[body_len] = 0;
int status = 200;
char* resp = tb_mcp_server_handle(s, body, &h, &status);
free(body);
respond(c->fd, resp ? status : 202, resp);
free(resp);
}
int tb_mcp_server_poll(TbMcpServer* s) {
if (!s || s->listen_fd < 0) return 0;
for (;;) { /* conexoes novas */
int fd = accept(s->listen_fd, NULL, NULL);
if (fd < 0) break;
if (s->conn_n >= TB_MCP_MAX_CONNS) { close(fd); continue; }
set_nonblock(fd);
TbMcpConn* c = &s->conns[s->conn_n++];
memset(c, 0, sizeof(*c));
c->fd = fd;
c->since_ms = now_ms();
}
int served = 0;
unsigned now = now_ms();
for (int i = s->conn_n - 1; i >= 0; i--) {
TbMcpConn* c = &s->conns[i];
bool closed = false;
for (;;) {
if (c->len + 4096 + 1 > c->cap) {
size_t cap = c->cap ? c->cap * 2 : 8192;
char* nb = realloc(c->buf, cap);
if (!nb) { closed = true; break; }
c->buf = nb;
c->cap = cap;
}
ssize_t r = recv(c->fd, c->buf + c->len, c->cap - c->len - 1, 0);
if (r > 0) { c->len += (size_t)r; continue; }
if (r == 0) closed = true;
else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) closed = true;
break;
}
size_t hl = 0, bl = 0;
int ready = c->buf ? request_ready(c, &hl, &bl) : 0;
if (ready > 0) { serve(s, c, hl, bl); served++; conn_drop(s, i); continue; }
if (ready < 0) { respond(c->fd, 413, NULL); conn_drop(s, i); continue; }
if (closed || now - c->since_ms > CONN_TIMEOUT) conn_drop(s, i);
}
return served;
}
@@ -0,0 +1,462 @@
/*
* TinyBlocks - tb_mcp_server.c
* Protocolo MCP do lado do servidor (ver tb_mcp_server.h): JSON-RPC, as duas
* eras do protocolo, ferramentas e o transporte stdio. O HTTP fica em
* tb_mcp_http.c.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "tb_mcp_server.h"
#include "tb_mcp_server_internal.h"
/* Versao moderna primeiro; as antigas atendem pelo initialize */
static const char* const s_versions[] = {
TB_MCP_PROTOCOL_MODERN, "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"
};
#define N_VERSIONS ((int)(sizeof(s_versions) / sizeof(s_versions[0])))
#define LEGACY_LATEST "2025-11-25"
#define ERR_PARSE (-32700)
#define ERR_INVALID_REQUEST (-32600)
#define ERR_METHOD_NOT_FOUND (-32601)
#define ERR_INVALID_PARAMS (-32602)
#define ERR_HEADER_MISMATCH (-32020)
#define ERR_UNSUPPORTED_VER (-32022)
#define META_VERSION "io.modelcontextprotocol/protocolVersion"
#define META_CAPS "io.modelcontextprotocol/clientCapabilities"
#define META_SERVER "io.modelcontextprotocol/serverInfo"
/* struct TbMcpServer: tb_mcp_server_internal.h (o HTTP usa os campos) */
struct TbMcpRequest {
TinyBlocks_JsonValue* args; /* emprestado */
char* text;
size_t len, cap;
bool is_error;
TinyBlocks_JsonValue* structured; /* nosso */
};
/* -- JSON: construir consumindo a referencia do valor ---------------------- */
static void jset(TinyBlocks_JsonValue* o, const char* k, TinyBlocks_JsonValue* v) {
if (!v) return;
tb_json_object_set(o, k, v);
tb_json_release(v);
}
static void jpush(TinyBlocks_JsonValue* a, TinyBlocks_JsonValue* v) {
if (!v) return;
tb_json_array_push(a, v);
tb_json_release(v);
}
/* Valor emprestado de um objeto (o objeto continua dono) */
static const TinyBlocks_JsonValue* jget(const TinyBlocks_JsonValue* o, const char* k) {
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
if (v) tb_json_release(v);
return v;
}
static const char* jstr(const TinyBlocks_JsonValue* o, const char* k) {
const TinyBlocks_JsonValue* v = jget(o, k);
return v ? tb_json_as_string(v) : NULL;
}
static bool version_supported(const char* v) {
for (int i = 0; v && i < N_VERSIONS; i++) if (!strcmp(v, s_versions[i])) return true;
return false;
}
static bool version_modern(const char* v) { return v && !strcmp(v, TB_MCP_PROTOCOL_MODERN); }
static TinyBlocks_JsonValue* server_info(TbMcpServer* s) {
TinyBlocks_JsonValue* o = tb_json_object();
jset(o, "name", tb_json_string(s->name));
jset(o, "version", tb_json_string(s->version));
return o;
}
/* -- Servidor ---------------------------------------------------------------- */
TbMcpServer* tb_mcp_server_new(const char* name, const char* version, const char* instructions) {
TbMcpServer* s = calloc(1, sizeof(*s));
if (!s) return NULL;
s->name = strdup(name ? name : "tinyblocks");
s->version = strdup(version ? version : "1.0.0");
s->instructions = strdup(instructions ? instructions : "");
s->listen_fd = -1;
return s;
}
void tb_mcp_server_free(TbMcpServer* s) {
if (!s) return;
tb_mcp_http_close(s);
free(s->tools);
free(s->name);
free(s->version);
free(s->instructions);
free(s);
}
bool tb_mcp_server_add_tool(TbMcpServer* s, const TbMcpTool* t, void* user) {
if (!s || !t || !t->name || !t->call) return false;
if (s->tool_n == s->tool_cap) {
int cap = s->tool_cap ? s->tool_cap * 2 : 16;
void* n = realloc(s->tools, (size_t)cap * sizeof(*s->tools));
if (!n) return false;
s->tools = n;
s->tool_cap = cap;
}
s->tools[s->tool_n].tool = t;
s->tools[s->tool_n].user = user;
s->tool_n++;
return true;
}
int tb_mcp_server_tool_count(const TbMcpServer* s) { return s ? s->tool_n : 0; }
/* -- Pedido (dentro de uma ferramenta) ------------------------------------- */
const TinyBlocks_JsonValue* tb_mcp_req_args(TbMcpRequest* rq) { return rq ? rq->args : NULL; }
const TinyBlocks_JsonValue* tb_mcp_req_arg(TbMcpRequest* rq, const char* key) {
return rq && rq->args ? jget(rq->args, key) : NULL;
}
bool tb_mcp_req_has(TbMcpRequest* rq, const char* key) {
const TinyBlocks_JsonValue* v = tb_mcp_req_arg(rq, key);
return v && tb_json_kind(v) != TB_JSON_NULL;
}
const char* tb_mcp_req_str(TbMcpRequest* rq, const char* key, const char* def) {
const TinyBlocks_JsonValue* v = tb_mcp_req_arg(rq, key);
const char* s = v ? tb_json_as_string(v) : NULL;
return s ? s : def;
}
double tb_mcp_req_num(TbMcpRequest* rq, const char* key, double def) {
const TinyBlocks_JsonValue* v = tb_mcp_req_arg(rq, key);
if (!v) return def;
if (tb_json_kind(v) == TB_JSON_STRING) { /* "12" tambem vale */
char* end = NULL;
const char* s = tb_json_as_string(v);
double d = strtod(s, &end);
return end && end != s ? d : def;
}
return tb_json_as_number(v, def);
}
bool tb_mcp_req_bool(TbMcpRequest* rq, const char* key, bool def) {
const TinyBlocks_JsonValue* v = tb_mcp_req_arg(rq, key);
return v ? tb_json_as_bool(v, def) : def;
}
static void req_vappend(TbMcpRequest* rq, const char* fmt, va_list ap) {
va_list cp;
va_copy(cp, ap);
int n = vsnprintf(NULL, 0, fmt, cp);
va_end(cp);
if (n < 0) return;
if (rq->len + (size_t)n + 1 > rq->cap) {
size_t cap = rq->cap ? rq->cap : 256;
while (cap < rq->len + (size_t)n + 1) cap *= 2;
char* t = realloc(rq->text, cap);
if (!t) return;
rq->text = t;
rq->cap = cap;
}
vsnprintf(rq->text + rq->len, rq->cap - rq->len, fmt, ap);
rq->len += (size_t)n;
}
void tb_mcp_req_text(TbMcpRequest* rq, const char* fmt, ...) {
if (!rq) return;
va_list ap;
va_start(ap, fmt);
req_vappend(rq, fmt, ap);
va_end(ap);
}
void tb_mcp_req_error(TbMcpRequest* rq, const char* fmt, ...) {
if (!rq) return;
rq->is_error = true;
rq->len = 0; /* o erro substitui o que havia */
if (rq->text) rq->text[0] = 0;
va_list ap;
va_start(ap, fmt);
req_vappend(rq, fmt, ap);
va_end(ap);
}
void tb_mcp_req_structured(TbMcpRequest* rq, TinyBlocks_JsonValue* value) {
if (!rq) { tb_json_release(value); return; }
if (rq->structured) tb_json_release(rq->structured);
rq->structured = value;
}
/* -- Respostas JSON-RPC -------------------------------------------------- */
static char* reply_result(const TinyBlocks_JsonValue* id, TinyBlocks_JsonValue* result) {
TinyBlocks_JsonValue* r = tb_json_object();
jset(r, "jsonrpc", tb_json_string("2.0"));
jset(r, "id", id ? tb_json_clone(id) : tb_json_null());
jset(r, "result", result);
char* out = tb_json_stringify(r);
tb_json_release(r);
return out;
}
static char* reply_error(const TinyBlocks_JsonValue* id, int code, const char* msg, TinyBlocks_JsonValue* data) {
TinyBlocks_JsonValue* r = tb_json_object();
TinyBlocks_JsonValue* e = tb_json_object();
jset(e, "code", tb_json_number(code));
jset(e, "message", tb_json_string(msg));
if (data) jset(e, "data", data);
jset(r, "jsonrpc", tb_json_string("2.0"));
if (id) jset(r, "id", tb_json_clone(id));
jset(r, "error", e);
char* out = tb_json_stringify(r);
tb_json_release(r);
return out;
}
/* Todo resultado leva resultType e (na era moderna) quem o servidor e */
static TinyBlocks_JsonValue* result_new(TbMcpServer* s) {
TinyBlocks_JsonValue* r = tb_json_object();
jset(r, "resultType", tb_json_string("complete"));
TinyBlocks_JsonValue* meta = tb_json_object();
jset(meta, META_SERVER, server_info(s));
jset(r, "_meta", meta);
return r;
}
static TinyBlocks_JsonValue* capabilities(void) {
TinyBlocks_JsonValue* caps = tb_json_object();
TinyBlocks_JsonValue* tools = tb_json_object();
jset(tools, "listChanged", tb_json_bool(false));
jset(caps, "tools", tools);
return caps;
}
static TinyBlocks_JsonValue* versions_array(void) {
TinyBlocks_JsonValue* a = tb_json_array();
for (int i = 0; i < N_VERSIONS; i++) jpush(a, tb_json_string(s_versions[i]));
return a;
}
/* -- Metodos ------------------------------------------------------------- */
static char* do_initialize(TbMcpServer* s, const TinyBlocks_JsonValue* id, const TinyBlocks_JsonValue* params) {
const char* want = params ? jstr(params, "protocolVersion") : NULL;
const char* ver = (want && version_supported(want) && !version_modern(want)) ? want : LEGACY_LATEST;
TinyBlocks_JsonValue* r = tb_json_object();
jset(r, "protocolVersion", tb_json_string(ver));
jset(r, "capabilities", capabilities());
jset(r, "serverInfo", server_info(s));
if (s->instructions[0]) jset(r, "instructions", tb_json_string(s->instructions));
return reply_result(id, r);
}
static char* do_discover(TbMcpServer* s, const TinyBlocks_JsonValue* id) {
TinyBlocks_JsonValue* r = result_new(s);
jset(r, "supportedVersions", versions_array());
jset(r, "capabilities", capabilities());
if (s->instructions[0]) jset(r, "instructions", tb_json_string(s->instructions));
jset(r, "ttlMs", tb_json_number(60000));
jset(r, "cacheScope", tb_json_string("private"));
return reply_result(id, r);
}
static TinyBlocks_JsonValue* tool_json(const TbMcpTool* t) {
TinyBlocks_JsonValue* o = tb_json_object();
jset(o, "name", tb_json_string(t->name));
if (t->title) jset(o, "title", tb_json_string(t->title));
jset(o, "description", tb_json_string(t->description ? t->description : ""));
TinyBlocks_JsonValue* schema = t->input_schema ? tb_json_parse(t->input_schema, NULL, 0) : NULL;
if (!schema) { /* esquema invalido: objeto vazio */
schema = tb_json_object();
jset(schema, "type", tb_json_string("object"));
}
jset(o, "inputSchema", schema);
TinyBlocks_JsonValue* ann = tb_json_object();
jset(ann, "readOnlyHint", tb_json_bool((t->hints & TB_MCP_READ_ONLY) != 0));
jset(ann, "destructiveHint", tb_json_bool((t->hints & TB_MCP_DESTRUCTIVE) != 0));
jset(ann, "idempotentHint", tb_json_bool((t->hints & TB_MCP_IDEMPOTENT) != 0));
jset(ann, "openWorldHint", tb_json_bool(false));
jset(o, "annotations", ann);
return o;
}
static char* do_tools_list(TbMcpServer* s, const TinyBlocks_JsonValue* id) {
TinyBlocks_JsonValue* r = result_new(s);
TinyBlocks_JsonValue* list = tb_json_array();
for (int i = 0; i < s->tool_n; i++) jpush(list, tool_json(s->tools[i].tool));
jset(r, "tools", list);
jset(r, "ttlMs", tb_json_number(60000));
jset(r, "cacheScope", tb_json_string("private"));
return reply_result(id, r);
}
static char* do_tools_call(TbMcpServer* s, const TinyBlocks_JsonValue* id, const TinyBlocks_JsonValue* params,
int* status) {
const char* name = params ? jstr(params, "name") : NULL;
const TbMcpTool* tool = NULL;
void* user = NULL;
for (int i = 0; name && i < s->tool_n; i++)
if (!strcmp(s->tools[i].tool->name, name)) { tool = s->tools[i].tool; user = s->tools[i].user; }
if (!tool) {
char msg[200];
snprintf(msg, sizeof(msg), "Ferramenta desconhecida: %.120s", name ? name : "(sem nome)");
*status = 200;
return reply_error(id, ERR_INVALID_PARAMS, msg, NULL);
}
const TinyBlocks_JsonValue* args = jget(params, "arguments");
TinyBlocks_JsonValue* empty = NULL;
if (!args || tb_json_kind(args) != TB_JSON_OBJECT) args = empty = tb_json_object();
TbMcpRequest rq = { (TinyBlocks_JsonValue*)args, NULL, 0, 0, false, NULL };
tool->call(user, &rq);
if (empty) tb_json_release(empty);
TinyBlocks_JsonValue* r = result_new(s);
TinyBlocks_JsonValue* content = tb_json_array();
if (rq.len || !rq.structured) {
TinyBlocks_JsonValue* item = tb_json_object();
jset(item, "type", tb_json_string("text"));
jset(item, "text", tb_json_string(rq.text ? rq.text : ""));
jpush(content, item);
}
if (rq.structured) {
if (!rq.len) { /* compatibilidade: o JSON tambem em texto */
char* js = tb_json_stringify(rq.structured);
TinyBlocks_JsonValue* item = tb_json_object();
jset(item, "type", tb_json_string("text"));
jset(item, "text", tb_json_string(js));
jpush(content, item);
free(js);
}
jset(r, "structuredContent", rq.structured);
}
jset(r, "content", content);
jset(r, "isError", tb_json_bool(rq.is_error));
free(rq.text);
return reply_result(id, r);
}
/* Cabecalho Mcp-Name pode vir em base64: =?base64?...?= */
static char* header_decode(const char* v) {
size_t n = v ? strlen(v) : 0;
if (n < 11 || strncmp(v, "=?base64?", 9) || strcmp(v + n - 2, "?=")) return v ? strdup(v) : NULL;
static const char* tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char* out = malloc(n);
if (!out) return NULL;
size_t o = 0;
unsigned acc = 0;
int bits = 0;
for (size_t i = 9; i < n - 2; i++) {
const char* p = strchr(tbl, v[i]);
if (v[i] == '=' || !p || !*p) break;
acc = (acc << 6) | (unsigned)(p - tbl);
bits += 6;
if (bits >= 8) { bits -= 8; out[o++] = (char)((acc >> bits) & 0xFF); }
}
out[o] = 0;
return out;
}
char* tb_mcp_server_handle(TbMcpServer* s, const char* body, const TbMcpHttpHeaders* h, int* http_status) {
int st = 200;
char* out = NULL;
char err[160] = "";
TinyBlocks_JsonValue* msg = body ? tb_json_parse(body, err, sizeof(err)) : NULL;
if (!msg) {
st = 400;
out = reply_error(NULL, ERR_PARSE, err[0] ? err : "JSON invalido", NULL);
goto done;
}
if (tb_json_kind(msg) != TB_JSON_OBJECT) {
st = 400;
out = reply_error(NULL, ERR_INVALID_REQUEST, "Esperava um objeto JSON-RPC (lotes nao sao aceitos)", NULL);
goto done;
}
const TinyBlocks_JsonValue* id = jget(msg, "id");
if (id && tb_json_kind(id) == TB_JSON_NULL) id = NULL;
const char* method = jstr(msg, "method");
if (!method) {
if (id) { st = 400; out = reply_error(id, ERR_INVALID_REQUEST, "Pedido sem method", NULL); }
else st = 202; /* resposta de cliente: ignora */
goto done;
}
if (!id) { st = 202; goto done; } /* notificacao (initialized, cancelled...) */
const TinyBlocks_JsonValue* params = jget(msg, "params");
const TinyBlocks_JsonValue* meta = params ? jget(params, "_meta") : NULL;
const char* mver = meta ? jstr(meta, META_VERSION) : NULL;
const char* hver = h ? h->protocol_version : NULL;
if (!strcmp(method, "initialize")) { /* era antiga */
out = do_initialize(s, id, params);
goto done;
}
if (mver || version_modern(hver)) { /* era moderna: valida o pedido */
if (!version_supported(mver ? mver : hver) || !version_modern(mver ? mver : hver)) {
TinyBlocks_JsonValue* data = tb_json_object();
TinyBlocks_JsonValue* sup = tb_json_array();
jpush(sup, tb_json_string(TB_MCP_PROTOCOL_MODERN));
jset(data, "supported", sup);
jset(data, "requested", tb_json_string(mver ? mver : hver));
st = 400;
out = reply_error(id, ERR_UNSUPPORTED_VER, "Unsupported protocol version", data);
goto done;
}
if (!mver || !jget(meta, META_CAPS)) {
st = 400;
out = reply_error(id, ERR_INVALID_PARAMS,
"Faltam campos obrigatorios em _meta (protocolVersion e clientCapabilities)", NULL);
goto done;
}
if (h) { /* HTTP: cabecalhos espelham o corpo */
char why[200] = "";
if (!hver || strcmp(hver, mver))
snprintf(why, sizeof(why), "Header mismatch: MCP-Protocol-Version '%s' != '%s'", hver ? hver : "", mver);
else if (!h->method || strcmp(h->method, method))
snprintf(why, sizeof(why), "Header mismatch: Mcp-Method '%s' != '%s'", h->method ? h->method : "", method);
else if (!strcmp(method, "tools/call")) {
const char* pname = jstr(params, "name");
char* hn = header_decode(h->name);
if (!hn || !pname || strcmp(hn, pname))
snprintf(why, sizeof(why), "Header mismatch: Mcp-Name '%s' != '%s'", hn ? hn : "", pname ? pname : "");
free(hn);
}
if (why[0]) { st = 400; out = reply_error(id, ERR_HEADER_MISMATCH, why, NULL); goto done; }
}
}
if (!strcmp(method, "server/discover")) out = do_discover(s, id);
else if (!strcmp(method, "ping")) out = reply_result(id, result_new(s));
else if (!strcmp(method, "tools/list")) out = do_tools_list(s, id);
else if (!strcmp(method, "tools/call")) out = do_tools_call(s, id, params, &st);
else {
char m[200];
snprintf(m, sizeof(m), "Metodo desconhecido: %.120s", method);
st = mver ? 404 : 200;
out = reply_error(id, ERR_METHOD_NOT_FOUND, m, NULL);
}
done:
if (msg) tb_json_release(msg);
if (http_status) *http_status = st;
return out;
}
/* -- stdio --------------------------------------------------------------- */
int tb_mcp_server_serve_stdio(TbMcpServer* s, FILE* in, FILE* out) {
char* line = NULL;
size_t cap = 0;
int served = 0;
ssize_t n;
while ((n = getline(&line, &cap, in)) >= 0) {
while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0;
if (n == 0) continue;
char* resp = tb_mcp_server_handle(s, line, NULL, NULL);
if (resp) {
fputs(resp, out);
fputc('\n', out);
fflush(out);
free(resp);
served++;
}
}
free(line);
return served;
}