/* * 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 #include #include #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; }