MCP funcionando: cliente conforme o protocolo, blocos na library e testes
A tinyblocks-mcp passa a ser uma library de blocos (categoria MCP, carregável pelas Bibliotecas): "servidor MCP %1 responde?", nome do servidor, ferramentas, nomes das ferramentas e "chame %2 do servidor MCP %1 com %3". Falha vira erro do TinyBlocks (pega no "se der erro" e no "tente obter"); só o "responde?" nunca falha. Cliente (Python embutido, tudo sob _tbmcp_ no __main__): - uma sessão por servidor: initialize uma vez, processo stdio vivo, reconecta se o servidor cair - stdio: shlex, ignora notificações e linhas que não são JSON-RPC, responde ping do servidor, tempo limite, stderr do servidor no erro - Streamable HTTP: Mcp-Session-Id, MCP-Protocol-Version, resposta JSON ou SSE, DELETE ao fechar - lista paginada; conteúdo de texto, imagem, recurso e estruturado; isError e erros JSON-RPC viram mensagens em português Corrige o carregamento do módulo (o vetor do xxd não termina em \0) e o build (lib-mcp depende de lib-python). O plugin examples/mcp saiu: os blocos vivem na library. test-mcp: servidor de teste próprio (tests/mcp_server.py) por stdio, HTTP e HTTP+SSE, com notificações no meio, ping do servidor, log que não é JSON, paginação, falhas e queda do servidor; e os blocos. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2d580005b1
commit
11d6e5317b
9 files changed
+986
-207
No files matched your search
@@ -1,5 +1,5 @@
|
||||
# Makefile da library mcp (cliente MCP; reusa tinyblocks-python)
|
||||
# Constroi build/libtinyblocks-mcp.so
|
||||
# Makefile da library mcp (cliente MCP e blocos "MCP"; reusa tinyblocks-python)
|
||||
# Constroi build/libtinyblocks-mcp.so (o mesmo interpretador da libtinyblocks-python)
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
PYDIR := ../tinyblocks-python
|
||||
@@ -22,7 +22,7 @@ shared: $(LIB_SO)
|
||||
$(PY_HDR): src/tb_mcp.py
|
||||
xxd -i -n tb_mcp_py $< $@
|
||||
|
||||
$(OBJ): src/tb_mcp.c $(PY_HDR) $(PYDIR)/include/tinyblocks-python/tb_python.h
|
||||
$(OBJ): src/tb_mcp.c $(PY_HDR) include/tinyblocks-mcp/tb_mcp.h $(PYDIR)/include/tinyblocks-python/tb_python.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
/*
|
||||
* TinyBlocks - tb_mcp.h
|
||||
* Cliente MCP (Model Context Protocol), implementado em Python embutido
|
||||
* (tinyblocks-python), e a library de blocos "MCP" que o usa.
|
||||
*
|
||||
* Endereco do servidor:
|
||||
* stdio://npx -y @modelcontextprotocol/server-everything (processo filho)
|
||||
* http://localhost:3001/mcp ("Streamable HTTP")
|
||||
*
|
||||
* Uma sessao por endereco fica aberta entre as chamadas (o initialize e feito
|
||||
* uma vez e o processo stdio continua vivo); tb_mcp_deinit fecha todas.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_MCP_H
|
||||
#define TINYBLOCKS_MCP_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
# define TB_MCP_API __declspec(dllexport)
|
||||
@@ -9,28 +22,19 @@
|
||||
# define TB_MCP_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
/*
|
||||
* tb_mcp - cliente MCP (Model Context Protocol) sobre transporte HTTP
|
||||
* e stdio, implementado em Python via tinyblocks-python.
|
||||
*
|
||||
* Transport HTTP (streamable): url = "http://host:port/mcp"
|
||||
* Transport stdio: url = "stdio://npx @modelcontextprotocol/server-filesystem /tmp"
|
||||
*
|
||||
* Todas as funções retornam string heap-alocada (caller frees) ou NULL em erro.
|
||||
*/
|
||||
TB_MCP_API bool tb_mcp_init(void);
|
||||
TB_MCP_API void tb_mcp_deinit(void);
|
||||
|
||||
TB_MCP_API bool tb_mcp_init(void);
|
||||
TB_MCP_API void tb_mcp_deinit(void);
|
||||
/* Todas devolvem texto alocado (o chamador libera). *ok = false: o texto e a
|
||||
* mensagem de erro (ok pode ser NULL). */
|
||||
TB_MCP_API char* tb_mcp_ping(const char* url, bool* ok); /* "ok" */
|
||||
TB_MCP_API char* tb_mcp_server_info(const char* url, bool* ok); /* "nome versao" */
|
||||
TB_MCP_API char* tb_mcp_list_tools(const char* url, bool* ok); /* "nome: descricao" / linha */
|
||||
TB_MCP_API char* tb_mcp_tool_names(const char* url, bool* ok); /* um nome por linha */
|
||||
TB_MCP_API char* tb_mcp_call_tool(const char* url, const char* tool,
|
||||
const char* args_json, bool* ok); /* conteudo em texto */
|
||||
|
||||
/* Lista ferramentas disponíveis -> JSON array de objetos {name, description} */
|
||||
TB_MCP_API char* tb_mcp_list_tools(const char* url);
|
||||
|
||||
/* Chama uma ferramenta com argumentos JSON -> resultado JSON */
|
||||
TB_MCP_API char* tb_mcp_call_tool(const char* url,
|
||||
const char* tool_name,
|
||||
const char* args_json);
|
||||
|
||||
/* Ping: verifica se o servidor responde -> "ok" ou mensagem de erro */
|
||||
TB_MCP_API char* tb_mcp_ping(const char* url);
|
||||
/* Library de blocos (categoria "MCP") */
|
||||
TB_MCP_API const TinyBlocks_LibraryDescriptor* tb_mcp_get_library(void);
|
||||
|
||||
#endif /* TINYBLOCKS_MCP_H */
|
||||
@@ -3,7 +3,7 @@
|
||||
name = "tinyblocks-mcp"
|
||||
version = "1.0.0"
|
||||
category = "MCP"
|
||||
description = "Cliente MCP (usa tinyblocks-python)"
|
||||
description = "Ferramentas de servidores MCP (stdio ou HTTP); usa tinyblocks-python"
|
||||
color = [233, 30, 99, 255]
|
||||
dark = [194, 24, 91, 255]
|
||||
|
||||
@@ -11,5 +11,4 @@ dark = [194, 24, 91, 255]
|
||||
sources = ["src/tb_mcp.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-mcp.so"
|
||||
static = "build/libtinyblocks-mcp.a"
|
||||
depends = ["tinyblocks-python"]
|
||||
@@ -1,3 +1,8 @@
|
||||
/*
|
||||
* TinyBlocks - tb_mcp.c
|
||||
* Cliente MCP (o protocolo fica em tb_mcp.py, no Python embutido) e os
|
||||
* blocos da categoria "MCP".
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -6,37 +11,40 @@
|
||||
#include "tinyblocks-mcp/tb_mcp.h"
|
||||
#include "tinyblocks-python/tb_python.h"
|
||||
|
||||
/* Código Python gerado por: xxd -i tb_mcp.py > tb_mcp_py.h */
|
||||
/* Codigo Python gerado por: xxd -i -n tb_mcp_py tb_mcp.py > tb_mcp_py.h */
|
||||
#include "tb_mcp_py.h"
|
||||
|
||||
/* -- Singleton --- */
|
||||
/* -- Modulo Python --- */
|
||||
static bool s_module_loaded = false;
|
||||
|
||||
static bool ensure_module(void) {
|
||||
if (s_module_loaded) return true;
|
||||
/*
|
||||
* Executa o módulo Python em __main__ para que as funções persistam
|
||||
* entre chamadas. tb_mcp_py é unsigned char[] gerado pelo xxd -i.
|
||||
*/
|
||||
char* err = tb_python_exec_main((const char*)tb_mcp_py);
|
||||
bool ok = (err != NULL && strlen(err) == 0);
|
||||
if (!ok && err) fprintf(stderr, "[tinyblocks-mcp] erro ao carregar modulo Python:\n%s\n", err);
|
||||
/* o xxd nao termina o vetor com '\0' */
|
||||
char* src = malloc(tb_mcp_py_len + 1);
|
||||
if (!src) return false;
|
||||
memcpy(src, tb_mcp_py, tb_mcp_py_len);
|
||||
src[tb_mcp_py_len] = 0;
|
||||
/* no __main__: as definicoes persistem entre as chamadas */
|
||||
char* err = tb_python_exec_main(src);
|
||||
free(src);
|
||||
bool ok = err && !err[0];
|
||||
if (!ok && err) fprintf(stderr, "[tinyblocks-mcp] erro ao carregar o cliente MCP:\n%s\n", err);
|
||||
free(err);
|
||||
s_module_loaded = ok;
|
||||
return ok;
|
||||
}
|
||||
|
||||
TB_MCP_API bool tb_mcp_init(void) {
|
||||
if (!tb_python_init()) return false;
|
||||
return ensure_module();
|
||||
return tb_python_init() && ensure_module();
|
||||
}
|
||||
|
||||
TB_MCP_API void tb_mcp_deinit(void) {
|
||||
if (s_module_loaded) free(tb_python_exec_main("_tbmcp_close_all()"));
|
||||
s_module_loaded = false;
|
||||
tb_python_deinit();
|
||||
}
|
||||
|
||||
/* -- Helper: escapa string para literal Python --- */
|
||||
/* Literal Python ("...") com escapes */
|
||||
static char* py_str(const char* s) {
|
||||
size_t n = strlen(s);
|
||||
char* out = malloc(n * 4 + 3);
|
||||
@@ -49,77 +57,170 @@ static char* py_str(const char* s) {
|
||||
else if (c == '\\') { *p++ = '\\'; *p++ = '\\'; }
|
||||
else if (c == '\n') { *p++ = '\\'; *p++ = 'n'; }
|
||||
else if (c == '\r') { *p++ = '\\'; *p++ = 'r'; }
|
||||
else if (c < 0x20) {
|
||||
p += sprintf(p, "\\x%02x", c);
|
||||
} else {
|
||||
*p++ = (char)c;
|
||||
}
|
||||
else if (c < 0x20) { p += sprintf(p, "\\x%02x", c); }
|
||||
else *p++ = (char)c;
|
||||
}
|
||||
*p++ = '"';
|
||||
*p = '\0';
|
||||
*p = 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* -- Helper genérico: monta e executa chamada Python fn(arg...) --- */
|
||||
static char* py_call(const char* fn, const char* const* args, int n) {
|
||||
if (!ensure_module()) return strdup("erro: modulo MCP nao carregado");
|
||||
|
||||
/* Constrói "print(fn(arg0, arg1, ...))" */
|
||||
/* print(fn(args...)); o Python devolve "+texto" (sucesso) ou "!erro" */
|
||||
static char* py_call(const char* fn, const char* const* args, int n, bool* ok) {
|
||||
if (ok) *ok = false;
|
||||
if (!ensure_module()) return strdup("o cliente MCP nao carregou (Python)");
|
||||
size_t total = strlen(fn) + 16;
|
||||
char** esc = malloc(n * sizeof(char*));
|
||||
if (!esc) return strdup("erro: memoria");
|
||||
for (int i = 0; i < n; i++) {
|
||||
esc[i] = py_str(args[i]);
|
||||
if (!esc[i]) {
|
||||
for (int j = 0; j < i; j++) free(esc[j]);
|
||||
free(esc);
|
||||
return strdup("erro: memoria");
|
||||
}
|
||||
char* esc[4] = {0};
|
||||
for (int i = 0; i < n && i < 4; i++) {
|
||||
esc[i] = py_str(args[i] ? args[i] : "");
|
||||
if (!esc[i]) { for (int j = 0; j < i; j++) free(esc[j]); return strdup("sem memoria"); }
|
||||
total += strlen(esc[i]) + 2;
|
||||
}
|
||||
|
||||
char* code = malloc(total + 16);
|
||||
if (!code) {
|
||||
for (int i = 0; i < n; i++) free(esc[i]);
|
||||
free(esc);
|
||||
return strdup("erro: memoria");
|
||||
}
|
||||
|
||||
char* code = malloc(total);
|
||||
if (!code) { for (int i = 0; i < n; i++) free(esc[i]); return strdup("sem memoria"); }
|
||||
char* p = code;
|
||||
p += sprintf(p, "print(%s(", fn);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (i > 0) { *p++ = ','; *p++ = ' '; }
|
||||
p += sprintf(p, "%s", esc[i]);
|
||||
}
|
||||
sprintf(p, "))");
|
||||
|
||||
for (int i = 0; i < n; i++) p += sprintf(p, "%s%s", i ? ", " : "", esc[i]);
|
||||
strcpy(p, "))");
|
||||
for (int i = 0; i < n; i++) free(esc[i]);
|
||||
free(esc);
|
||||
|
||||
char* out = tb_python_exec_main(code);
|
||||
free(code);
|
||||
|
||||
/* Remove trailing newline */
|
||||
if (out) {
|
||||
size_t len = strlen(out);
|
||||
while (len > 0 && (out[len-1] == '\n' || out[len-1] == '\r'))
|
||||
out[--len] = '\0';
|
||||
if (!out) return strdup("o Python nao respondeu");
|
||||
size_t len = strlen(out);
|
||||
while (len > 0 && (out[len - 1] == '\n' || out[len - 1] == '\r')) out[--len] = 0;
|
||||
if (out[0] == '+' || out[0] == '!') {
|
||||
if (ok) *ok = out[0] == '+';
|
||||
memmove(out, out + 1, len);
|
||||
}
|
||||
return out ? out : strdup("");
|
||||
return out; /* sem prefixo: traceback do Python (erro) */
|
||||
}
|
||||
|
||||
/* -- API pública --- */
|
||||
TB_MCP_API char* tb_mcp_ping(const char* url) {
|
||||
const char* args[] = {url};
|
||||
return py_call("mcp_ping", args, 1);
|
||||
TB_MCP_API char* tb_mcp_ping(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_ping", a, 1, ok);
|
||||
}
|
||||
TB_MCP_API char* tb_mcp_server_info(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_server", a, 1, ok);
|
||||
}
|
||||
TB_MCP_API char* tb_mcp_list_tools(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_tools", a, 1, ok);
|
||||
}
|
||||
TB_MCP_API char* tb_mcp_tool_names(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_tool_names", a, 1, ok);
|
||||
}
|
||||
TB_MCP_API char* tb_mcp_call_tool(const char* url, const char* tool, const char* args_json, bool* ok) {
|
||||
const char* a[] = { url, tool, args_json && args_json[0] ? args_json : "{}" };
|
||||
return py_call("_tbmcp_call", a, 3, ok);
|
||||
}
|
||||
|
||||
TB_MCP_API char* tb_mcp_list_tools(const char* url) {
|
||||
const char* args[] = {url};
|
||||
return py_call("mcp_list_tools", args, 1);
|
||||
/* == Blocos ==================================================================
|
||||
* Falha vira erro do TinyBlocks: para o script, ou cai no "se der erro" /
|
||||
* "tente obter" (biblioteca de erros). So o "responde?" nunca falha. */
|
||||
static void out_text(TinyBlocks_Block* self, TinyBlocks* rt, char* res, bool ok) {
|
||||
if (ok) tb_block_set_output(self, 0, tb_value_text(res ? res : ""));
|
||||
else tinyblocks_set_error(rt, "MCP: %s", res ? res : "erro");
|
||||
free(res);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
TB_MCP_API char* tb_mcp_call_tool(const char* url, const char* tool_name, const char* args_json) {
|
||||
const char* args[] = {url, tool_name, args_json ? args_json : "{}"};
|
||||
return py_call("mcp_call_tool", args, 3);
|
||||
static void eval_ping(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok;
|
||||
free(tb_mcp_ping(tb_block_input_text(self, rt, 0), &ok));
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_server(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok;
|
||||
char* r = tb_mcp_server_info(tb_block_input_text(self, rt, 0), &ok);
|
||||
out_text(self, rt, r, ok);
|
||||
}
|
||||
|
||||
static void eval_tools(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok;
|
||||
char* r = tb_mcp_list_tools(tb_block_input_text(self, rt, 0), &ok);
|
||||
out_text(self, rt, r, ok);
|
||||
}
|
||||
|
||||
static void eval_tool_names(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok;
|
||||
char* r = tb_mcp_tool_names(tb_block_input_text(self, rt, 0), &ok);
|
||||
out_text(self, rt, r, ok);
|
||||
}
|
||||
|
||||
static void eval_call(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok;
|
||||
char* url = strdup(tb_block_input_text(self, rt, 0)); /* as 3 entradas dividem o cache */
|
||||
char* tool = strdup(tb_block_input_text(self, rt, 1));
|
||||
const char* args = tb_block_input_text(self, rt, 2);
|
||||
char* r = (url && tool) ? tb_mcp_call_tool(url, tool, args, &ok) : (ok = false, strdup("sem memoria"));
|
||||
free(url);
|
||||
free(tool);
|
||||
out_text(self, rt, r, ok);
|
||||
}
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*),
|
||||
const char* label, const char* defaults) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
if (!t) return false;
|
||||
tb_type_block_set_label(t, label, defaults);
|
||||
return tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
#define MCP_URL "stdio://npx -y @modelcontextprotocol/server-everything"
|
||||
|
||||
static bool mcp_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
if (!tb_mcp_init()) return false;
|
||||
static const TinyBlocks_Category cat = {
|
||||
"MCP",
|
||||
{ 233/255.f, 30/255.f, 99/255.f, 1.f},
|
||||
{ 194/255.f, 24/255.f, 91/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
TB_BLOCK_META("MCP.Ping", "eval_ping", "Verdadeiro se o servidor MCP responde");
|
||||
TB_BLOCK_META("MCP.Server", "eval_server", "Nome e versao do servidor MCP");
|
||||
TB_BLOCK_META("MCP.ListTools", "eval_tools", "Ferramentas do servidor, uma por linha (nome: descricao)");
|
||||
TB_BLOCK_META("MCP.ToolNames", "eval_tool_names", "So os nomes das ferramentas, um por linha");
|
||||
TB_BLOCK_META("MCP.Call", "eval_call",
|
||||
"Chama uma ferramenta com argumentos JSON e devolve o resultado em texto");
|
||||
|
||||
static const TinyBlocks_SlotDesc url_in[] = {{"servidor", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc call_in[] = {{"servidor", TB_VALUE_TEXT}, {"ferramenta", TB_VALUE_TEXT},
|
||||
{"argumentos", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc ok_out[] = {{"responde?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc txt_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
|
||||
return reg(rt, lib, "MCP.Ping", url_in, 1, ok_out, 1, eval_ping,
|
||||
"servidor MCP %1 responde?", MCP_URL)
|
||||
&& reg(rt, lib, "MCP.Server", url_in, 1, txt_out, 1, eval_server,
|
||||
"nome do servidor MCP %1", MCP_URL)
|
||||
&& reg(rt, lib, "MCP.ListTools", url_in, 1, txt_out, 1, eval_tools,
|
||||
"ferramentas do servidor MCP %1", MCP_URL)
|
||||
&& reg(rt, lib, "MCP.ToolNames", url_in, 1, txt_out, 1, eval_tool_names,
|
||||
"nomes das ferramentas de %1", MCP_URL)
|
||||
&& reg(rt, lib, "MCP.Call", call_in, 3, txt_out, 1, eval_call,
|
||||
"chame %2 do servidor MCP %1 com %3", MCP_URL "|echo|{\"message\": \"oi\"}");
|
||||
}
|
||||
|
||||
static void mcp_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
tb_mcp_deinit();
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(mcp,
|
||||
"tinyblocks-mcp",
|
||||
"1.0.0",
|
||||
mcp_init,
|
||||
mcp_deinit)
|
||||
|
||||
TB_MCP_API const TinyBlocks_LibraryDescriptor* tb_mcp_get_library(void) {
|
||||
return &_tb_lib_desc_mcp;
|
||||
}
|
||||
@@ -1,115 +1,412 @@
|
||||
import json
|
||||
# Cliente MCP (Model Context Protocol) do TinyBlocks.
|
||||
#
|
||||
# Roda no __main__ do Python embutido (tinyblocks-python), por isso tudo aqui
|
||||
# comeca com _tbmcp: nao pisa nas definicoes dos blocos Python do usuario.
|
||||
#
|
||||
# Transportes:
|
||||
# stdio://<comando> processo filho, JSON-RPC uma mensagem por linha
|
||||
# http://... ou https://... "Streamable HTTP": POST com resposta JSON ou SSE,
|
||||
# sessao pelo cabecalho Mcp-Session-Id
|
||||
#
|
||||
# Uma sessao por URL fica aberta entre as chamadas (o initialize acontece uma
|
||||
# vez; o processo stdio continua vivo). As funcoes publicas devolvem texto com
|
||||
# um prefixo: "+" sucesso, "!" erro (o C transforma em erro do TinyBlocks).
|
||||
|
||||
def _http_jsonrpc(url, method, params):
|
||||
import urllib.request, urllib.error
|
||||
payload = json.dumps({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": method,
|
||||
"params": params
|
||||
}).encode()
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
)
|
||||
import json as _tbmcp_json
|
||||
|
||||
_TBMCP_PROTOCOL = "2025-06-18"
|
||||
_TBMCP_TIMEOUT = 30.0
|
||||
|
||||
|
||||
class _TbMcpError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _tbmcp_result(msg):
|
||||
if not isinstance(msg, dict):
|
||||
raise _TbMcpError("resposta invalida do servidor")
|
||||
if "error" in msg:
|
||||
err = msg["error"] or {}
|
||||
text = err.get("message", "erro") if isinstance(err, dict) else str(err)
|
||||
code = err.get("code") if isinstance(err, dict) else None
|
||||
raise _TbMcpError(text if code is None else "%s (codigo %s)" % (text, code))
|
||||
return msg.get("result", {})
|
||||
|
||||
|
||||
def _tbmcp_error_reply(req_id, code, text):
|
||||
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": text}}
|
||||
|
||||
|
||||
def _tbmcp_answer(msg):
|
||||
"""Resposta a um pedido do servidor (so sabemos responder ping)."""
|
||||
if msg.get("method") == "ping":
|
||||
return {"jsonrpc": "2.0", "id": msg.get("id"), "result": {}}
|
||||
return _tbmcp_error_reply(msg.get("id"), -32601, "metodo nao suportado: %s" % msg.get("method"))
|
||||
|
||||
|
||||
class _TbMcpStdio:
|
||||
def __init__(self, cmd):
|
||||
import os, shlex, subprocess, tempfile
|
||||
argv = shlex.split(cmd)
|
||||
if not argv:
|
||||
raise _TbMcpError("comando vazio em stdio://")
|
||||
self.err = tempfile.TemporaryFile()
|
||||
try:
|
||||
self.p = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=self.err, bufsize=0)
|
||||
except FileNotFoundError:
|
||||
raise _TbMcpError("comando nao encontrado: %s" % argv[0])
|
||||
except OSError as e:
|
||||
raise _TbMcpError("nao consegui iniciar %s: %s" % (argv[0], e))
|
||||
self.fd = self.p.stdout.fileno()
|
||||
self.buf = b""
|
||||
self.next_id = 1
|
||||
self.proto = None
|
||||
self._os = os
|
||||
|
||||
def alive(self):
|
||||
return self.p.poll() is None
|
||||
|
||||
def _stderr_tail(self):
|
||||
try:
|
||||
self.err.seek(0)
|
||||
tail = self.err.read().decode("utf-8", "replace").strip().splitlines()[-3:]
|
||||
return (": " + " / ".join(tail)) if tail else ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
def _send(self, obj):
|
||||
try:
|
||||
self.p.stdin.write((_tbmcp_json.dumps(obj) + "\n").encode("utf-8"))
|
||||
self.p.stdin.flush()
|
||||
except (BrokenPipeError, OSError):
|
||||
raise _TbMcpError("o servidor fechou a entrada" + self._stderr_tail())
|
||||
|
||||
def _readline(self, deadline):
|
||||
import select, time
|
||||
while b"\n" not in self.buf:
|
||||
left = deadline - time.monotonic()
|
||||
if left <= 0:
|
||||
raise _TbMcpError("tempo esgotado esperando o servidor")
|
||||
ready, _, _ = select.select([self.fd], [], [], left)
|
||||
if not ready:
|
||||
continue
|
||||
chunk = self._os.read(self.fd, 65536)
|
||||
if not chunk:
|
||||
code = self.p.poll()
|
||||
raise _TbMcpError("o servidor terminou (codigo %s)%s" % (code, self._stderr_tail()))
|
||||
self.buf += chunk
|
||||
line, self.buf = self.buf.split(b"\n", 1)
|
||||
return line
|
||||
|
||||
def notify(self, method, params):
|
||||
self._send({"jsonrpc": "2.0", "method": method, "params": params})
|
||||
|
||||
def request(self, method, params):
|
||||
import time
|
||||
rid = self.next_id
|
||||
self.next_id += 1
|
||||
self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
|
||||
deadline = time.monotonic() + _TBMCP_TIMEOUT
|
||||
while True:
|
||||
line = self._readline(deadline).strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
msg = _tbmcp_json.loads(line.decode("utf-8"))
|
||||
except ValueError:
|
||||
continue # linha que nao e JSON-RPC (log do servidor)
|
||||
for m in (msg if isinstance(msg, list) else [msg]):
|
||||
if not isinstance(m, dict):
|
||||
continue
|
||||
if "method" in m: # pedido ou notificacao do servidor
|
||||
if "id" in m:
|
||||
self._send(_tbmcp_answer(m))
|
||||
continue
|
||||
if m.get("id") == rid:
|
||||
return m
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.p.stdin.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.p.terminate()
|
||||
self.p.wait(timeout=2)
|
||||
except Exception:
|
||||
try:
|
||||
self.p.kill()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.p.stdout.close()
|
||||
self.err.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class _TbMcpHttp:
|
||||
def __init__(self, url):
|
||||
self.url = url
|
||||
self.session = None
|
||||
self.proto = None
|
||||
self.next_id = 1
|
||||
|
||||
def alive(self):
|
||||
return True
|
||||
|
||||
def _headers(self):
|
||||
h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
|
||||
if self.session:
|
||||
h["Mcp-Session-Id"] = self.session
|
||||
if self.proto:
|
||||
h["MCP-Protocol-Version"] = self.proto
|
||||
return h
|
||||
|
||||
def _open(self, obj, method="POST"):
|
||||
import urllib.request, urllib.error
|
||||
data = _tbmcp_json.dumps(obj).encode("utf-8") if obj is not None else None
|
||||
req = urllib.request.Request(self.url, data=data, headers=self._headers(), method=method)
|
||||
try:
|
||||
return urllib.request.urlopen(req, timeout=_TBMCP_TIMEOUT)
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = ""
|
||||
try: # corpo JSON-RPC com a mensagem do erro
|
||||
body = _tbmcp_json.loads(e.read().decode("utf-8", "replace"))
|
||||
if isinstance(body, dict) and isinstance(body.get("error"), dict):
|
||||
detail = ": " + str(body["error"].get("message", ""))
|
||||
except Exception:
|
||||
pass
|
||||
if e.code == 404 and self.session:
|
||||
raise _TbMcpError("sessao expirada (HTTP 404)")
|
||||
raise _TbMcpError("HTTP %d %s%s" % (e.code, e.reason, detail))
|
||||
except urllib.error.URLError as e:
|
||||
raise _TbMcpError("nao consegui conectar em %s: %s" % (self.url, e.reason))
|
||||
except OSError as e:
|
||||
raise _TbMcpError("erro de rede: %s" % e)
|
||||
|
||||
def _post(self, obj, rid):
|
||||
r = self._open(obj)
|
||||
with r:
|
||||
sid = r.headers.get("Mcp-Session-Id")
|
||||
if sid:
|
||||
self.session = sid
|
||||
if rid is None:
|
||||
return None # notificacao: 202 sem corpo
|
||||
ctype = r.headers.get("Content-Type", "")
|
||||
if "text/event-stream" in ctype:
|
||||
return self._read_sse(r, rid)
|
||||
body = r.read().decode("utf-8")
|
||||
if not body.strip():
|
||||
raise _TbMcpError("o servidor respondeu vazio")
|
||||
try:
|
||||
msg = _tbmcp_json.loads(body)
|
||||
except ValueError:
|
||||
raise _TbMcpError("o servidor nao respondeu JSON")
|
||||
for m in (msg if isinstance(msg, list) else [msg]):
|
||||
if isinstance(m, dict) and m.get("id") == rid and "method" not in m:
|
||||
return m
|
||||
raise _TbMcpError("o servidor nao respondeu ao pedido")
|
||||
|
||||
def _read_sse(self, r, rid):
|
||||
data = []
|
||||
for raw in r:
|
||||
line = raw.decode("utf-8").rstrip("\r\n")
|
||||
if line == "":
|
||||
if not data:
|
||||
continue
|
||||
try:
|
||||
msg = _tbmcp_json.loads("\n".join(data))
|
||||
except ValueError:
|
||||
msg = None
|
||||
data = []
|
||||
for m in (msg if isinstance(msg, list) else [msg]):
|
||||
if not isinstance(m, dict):
|
||||
continue
|
||||
if "method" in m:
|
||||
if "id" in m: # pedido do servidor: responde por POST
|
||||
self._post(_tbmcp_answer(m), None)
|
||||
continue
|
||||
if m.get("id") == rid:
|
||||
return m
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
continue # comentario / keep-alive
|
||||
if line.startswith("data:"):
|
||||
data.append(line[5:].lstrip(" "))
|
||||
raise _TbMcpError("o servidor fechou o stream sem responder")
|
||||
|
||||
def notify(self, method, params):
|
||||
self._post({"jsonrpc": "2.0", "method": method, "params": params}, None)
|
||||
|
||||
def request(self, method, params):
|
||||
rid = self.next_id
|
||||
self.next_id += 1
|
||||
return self._post({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}, rid)
|
||||
|
||||
def close(self):
|
||||
if not self.session:
|
||||
return
|
||||
try:
|
||||
self._open(None, "DELETE").close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class _TbMcpSession:
|
||||
def __init__(self, url):
|
||||
if url.startswith("stdio://"):
|
||||
self.t = _TbMcpStdio(url[len("stdio://"):])
|
||||
elif url.startswith("http://") or url.startswith("https://"):
|
||||
self.t = _TbMcpHttp(url)
|
||||
else:
|
||||
raise _TbMcpError("endereco invalido (use stdio://comando ou http://...): %s" % url)
|
||||
try:
|
||||
res = _tbmcp_result(self.t.request("initialize", {
|
||||
"protocolVersion": _TBMCP_PROTOCOL,
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "tinyblocks", "version": "1.0.0"},
|
||||
}))
|
||||
self.info = res.get("serverInfo", {}) or {}
|
||||
self.t.proto = res.get("protocolVersion") or _TBMCP_PROTOCOL
|
||||
self.t.notify("notifications/initialized", {})
|
||||
except Exception:
|
||||
self.t.close()
|
||||
raise
|
||||
|
||||
def alive(self):
|
||||
return self.t.alive()
|
||||
|
||||
def call(self, method, params):
|
||||
return _tbmcp_result(self.t.request(method, params))
|
||||
|
||||
def close(self):
|
||||
self.t.close()
|
||||
|
||||
|
||||
_tbmcp_sessions = {}
|
||||
|
||||
|
||||
def _tbmcp_session(url):
|
||||
s = _tbmcp_sessions.get(url)
|
||||
if s is not None and s.alive():
|
||||
return s
|
||||
if s is not None:
|
||||
s.close()
|
||||
s = _TbMcpSession(url)
|
||||
_tbmcp_sessions[url] = s
|
||||
return s
|
||||
|
||||
|
||||
def _tbmcp_do(url, method, params):
|
||||
"""Chama o metodo; se a sessao caiu (servidor reiniciou), abre outra uma vez."""
|
||||
url = url.strip()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
body = r.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": {"code": e.code, "message": e.reason}}
|
||||
except Exception as e:
|
||||
return {"error": {"code": -1, "message": str(e)}}
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception as e:
|
||||
return {"error": {"code": -2, "message": "invalid JSON: " + str(e)}}
|
||||
return _tbmcp_session(url).call(method, params)
|
||||
except _TbMcpError as e:
|
||||
msg = str(e)
|
||||
if not ("terminou" in msg or "expirada" in msg or "fechou" in msg):
|
||||
raise
|
||||
old = _tbmcp_sessions.pop(url, None)
|
||||
if old is not None:
|
||||
old.close()
|
||||
return _tbmcp_session(url).call(method, params)
|
||||
|
||||
def _stdio_jsonrpc(cmd, method, params):
|
||||
import subprocess
|
||||
args = cmd.split()
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
args,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
return {"error": {"code": -1, "message": str(e)}}
|
||||
|
||||
def send(obj):
|
||||
line = (json.dumps(obj) + "\n").encode()
|
||||
proc.stdin.write(line)
|
||||
proc.stdin.flush()
|
||||
def _tbmcp_api(fn):
|
||||
"""Embrulha as funcoes chamadas pelo C: "+texto" ou "!erro"."""
|
||||
def wrapper(*args):
|
||||
try:
|
||||
return "+" + fn(*args)
|
||||
except _TbMcpError as e:
|
||||
return "!" + str(e)
|
||||
except Exception as e:
|
||||
return "!%s: %s" % (type(e).__name__, e)
|
||||
return wrapper
|
||||
|
||||
def recv():
|
||||
line = proc.stdout.readline()
|
||||
if not line:
|
||||
return {}
|
||||
return json.loads(line.decode().strip())
|
||||
|
||||
try:
|
||||
send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
|
||||
"protocolVersion":"2024-11-05",
|
||||
"capabilities":{},
|
||||
"clientInfo":{"name":"tinyblocks-mcp","version":"1.0"}
|
||||
}})
|
||||
recv()
|
||||
send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}})
|
||||
send({"jsonrpc":"2.0","id":2,"method":method,"params":params})
|
||||
resp = recv()
|
||||
return resp
|
||||
except Exception as e:
|
||||
return {"error":{"code":-1,"message":str(e)}}
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=3)
|
||||
def _tbmcp_content_text(content):
|
||||
parts = []
|
||||
for item in content if isinstance(content, list) else [content]:
|
||||
if not isinstance(item, dict):
|
||||
parts.append(str(item))
|
||||
continue
|
||||
kind = item.get("type")
|
||||
if kind == "text":
|
||||
parts.append(item.get("text", ""))
|
||||
elif kind in ("image", "audio"):
|
||||
parts.append("[%s %s]" % ("imagem" if kind == "image" else "audio", item.get("mimeType", "")))
|
||||
elif kind == "resource":
|
||||
res = item.get("resource", {}) or {}
|
||||
parts.append(res.get("text", res.get("uri", "")))
|
||||
elif kind == "resource_link":
|
||||
parts.append(item.get("uri", ""))
|
||||
else:
|
||||
parts.append(_tbmcp_json.dumps(item, ensure_ascii=False))
|
||||
return "\n".join(parts)
|
||||
|
||||
def _dispatch(url, method, params):
|
||||
if url.startswith("stdio://"):
|
||||
return _stdio_jsonrpc(url[len("stdio://"):], method, params)
|
||||
else:
|
||||
return _http_jsonrpc(url, method, params)
|
||||
|
||||
def mcp_ping(url):
|
||||
resp = _dispatch(url, "ping", {})
|
||||
if "error" in resp:
|
||||
return "erro: " + resp["error"].get("message", str(resp["error"]))
|
||||
@_tbmcp_api
|
||||
def _tbmcp_ping(url):
|
||||
_tbmcp_do(url, "ping", {})
|
||||
return "ok"
|
||||
|
||||
def mcp_list_tools(url):
|
||||
resp = _dispatch(url, "tools/list", {})
|
||||
if "error" in resp:
|
||||
return "erro: " + resp["error"].get("message", str(resp["error"]))
|
||||
result = resp.get("result", resp)
|
||||
tools = result.get("tools", [])
|
||||
out = []
|
||||
for t in tools:
|
||||
name = t.get("name","?")
|
||||
desc = t.get("description","")
|
||||
out.append(name + ": " + desc)
|
||||
return "\n".join(out) if out else "(nenhuma ferramenta)"
|
||||
|
||||
def mcp_call_tool(url, tool_name, args_json):
|
||||
@_tbmcp_api
|
||||
def _tbmcp_server(url):
|
||||
info = _tbmcp_session(url.strip()).info
|
||||
return ("%s %s" % (info.get("name", "?"), info.get("version", ""))).strip()
|
||||
|
||||
|
||||
def _tbmcp_all_tools(url):
|
||||
tools, cursor = [], None
|
||||
for _ in range(100): # paginas
|
||||
params = {"cursor": cursor} if cursor else {}
|
||||
res = _tbmcp_do(url, "tools/list", params)
|
||||
tools.extend(res.get("tools", []) or [])
|
||||
cursor = res.get("nextCursor")
|
||||
if not cursor:
|
||||
break
|
||||
return tools
|
||||
|
||||
|
||||
@_tbmcp_api
|
||||
def _tbmcp_tools(url):
|
||||
tools = _tbmcp_all_tools(url)
|
||||
return "\n".join("%s: %s" % (t.get("name", "?"), (t.get("description") or "").strip().split("\n")[0])
|
||||
for t in tools)
|
||||
|
||||
|
||||
@_tbmcp_api
|
||||
def _tbmcp_tool_names(url):
|
||||
return "\n".join(t.get("name", "?") for t in _tbmcp_all_tools(url))
|
||||
|
||||
|
||||
@_tbmcp_api
|
||||
def _tbmcp_call(url, tool, args_json):
|
||||
try:
|
||||
args = json.loads(args_json) if args_json and args_json.strip() else {}
|
||||
except Exception as e:
|
||||
return "erro: args JSON invalido: " + str(e)
|
||||
resp = _dispatch(url, "tools/call", {"name": tool_name, "arguments": args})
|
||||
if "error" in resp:
|
||||
return "erro: " + resp["error"].get("message", str(resp["error"]))
|
||||
result = resp.get("result", resp)
|
||||
content = result.get("content", result)
|
||||
if isinstance(content, list):
|
||||
parts = []
|
||||
for item in content:
|
||||
if isinstance(item, dict):
|
||||
parts.append(item.get("text", json.dumps(item)))
|
||||
else:
|
||||
parts.append(str(item))
|
||||
return "\n".join(parts)
|
||||
return json.dumps(content, ensure_ascii=False, indent=2)
|
||||
args = _tbmcp_json.loads(args_json) if args_json and args_json.strip() else {}
|
||||
except ValueError as e:
|
||||
raise _TbMcpError("argumentos nao sao JSON valido: %s" % e)
|
||||
if not isinstance(args, dict):
|
||||
raise _TbMcpError("os argumentos devem ser um objeto JSON, como {\"x\": 1}")
|
||||
res = _tbmcp_do(url, "tools/call", {"name": tool, "arguments": args})
|
||||
content = res.get("content")
|
||||
if content is None and "structuredContent" in res:
|
||||
text = _tbmcp_json.dumps(res["structuredContent"], ensure_ascii=False)
|
||||
else:
|
||||
text = _tbmcp_content_text(content or [])
|
||||
if res.get("isError"):
|
||||
raise _TbMcpError(text or "a ferramenta falhou")
|
||||
return text
|
||||
|
||||
|
||||
def _tbmcp_close_all():
|
||||
for s in list(_tbmcp_sessions.values()):
|
||||
try:
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
_tbmcp_sessions.clear()
|
||||
return ""
|
||||
Reference in new issue
Block a user