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
+977
-198
No files matched your search
@@ -102,7 +102,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \
|
||||
.PHONY: all help debug release static shared example sdl2 clean run python-lib mcp-lib json \
|
||||
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
|
||||
appdir appimage run-appimage icon \
|
||||
test-toml test-plugin test-blueprint test-a11y test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
|
||||
test-toml test-plugin test-blueprint test-a11y test-mcp test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
|
||||
test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \
|
||||
category-libs category-sos libs \
|
||||
lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
|
||||
@@ -244,7 +244,7 @@ lib-sdl2:
|
||||
lib-python:
|
||||
$(MAKE) -C $(PY_DIR)
|
||||
|
||||
lib-mcp:
|
||||
lib-mcp: lib-python
|
||||
$(MAKE) -C $(MC_DIR)
|
||||
|
||||
libs: static lib-events lib-control lib-errors lib-operators lib-variables \
|
||||
@@ -430,17 +430,9 @@ $(BUILD)/python.so: examples/python/python.c static lib-python
|
||||
python-lib: static lib-python $(BUILD)/python.so ## Library Python (CPython embutido) -> build/python.so
|
||||
@echo "Build python OK: $(BUILD)/python.so"
|
||||
|
||||
# -- Library MCP (usa tinyblocks-python) ---
|
||||
$(BUILD)/mcp.so: examples/mcp/mcp.c static lib-mcp
|
||||
$(CC) $(CFLAGS_REL) \
|
||||
-I$(MC_DIR)/include -I$(PY_DIR)/include -Iinclude -fPIC -shared \
|
||||
$< -o $@ -L$(MC_DIR)/build -L$(PY_DIR)/build -L$(BUILD) \
|
||||
-ltinyblocks-mcp -ltinyblocks-python -ltinyblocks \
|
||||
'-Wl,-rpath,$$ORIGIN' '-Wl,-rpath,$(abspath $(MC_DIR)/build)' \
|
||||
'-Wl,-rpath,$(abspath $(PY_DIR)/build)'
|
||||
|
||||
mcp-lib: static lib-mcp $(BUILD)/mcp.so ## Library cliente MCP -> build/mcp.so
|
||||
@echo "Build mcp OK: $(BUILD)/mcp.so"
|
||||
# -- Library MCP (cliente MCP em Python embutido; blocos da categoria "MCP") ---
|
||||
mcp-lib: static lib-mcp ## Library MCP -> libraries/tinyblocks-mcp/build/libtinyblocks-mcp.so
|
||||
@echo "Build mcp OK: $(MC_DIR)/build/libtinyblocks-mcp.so"
|
||||
|
||||
ed-modules: ## Reconstroi so as libraries privadas do editor (hot reload)
|
||||
$(MAKE) -C $(ED_DIR)
|
||||
@@ -519,6 +511,20 @@ $(BUILD)/environ_test: tests/environ_test.c $(EN_DIR)/src/tb_environ.c static
|
||||
test-environ: $(BUILD)/environ_test ## Roda o teste da environ (ASan/UBSan)
|
||||
./$(BUILD)/environ_test
|
||||
|
||||
# -- Teste da library mcp (servidor de teste tests/mcp_server.py, stdio e HTTP) ---
|
||||
# Sem sanitizers: o CPython embutido nao convive bem com o ASan.
|
||||
ER_DIR := $(LIBDIR)/tinyblocks-errors
|
||||
$(BUILD)/mcp_test: tests/mcp_test.c tests/mcp_server.py $(ER_DIR)/src/tb_errors.c static lib-mcp
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -g -I$(MC_DIR)/include -I$(PY_DIR)/include -I$(ER_DIR)/include \
|
||||
tests/mcp_test.c $(ER_DIR)/src/tb_errors.c -o $@ \
|
||||
-Wl,--whole-archive $(LIB_A) -Wl,--no-whole-archive \
|
||||
-L$(MC_DIR)/build -L$(PY_DIR)/build -ltinyblocks-mcp -ltinyblocks-python -lm -rdynamic \
|
||||
'-Wl,-rpath,$(abspath $(MC_DIR)/build)' '-Wl,-rpath,$(abspath $(PY_DIR)/build)'
|
||||
|
||||
test-mcp: $(BUILD)/mcp_test ## Roda o teste do cliente MCP (stdio, HTTP e SSE)
|
||||
./$(BUILD)/mcp_test
|
||||
|
||||
# -- Teste da library a11y (arvore acessivel) ---
|
||||
$(BUILD)/a11y_test: tests/a11y_test.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h static
|
||||
@mkdir -p $(BUILD)
|
||||
|
||||
@@ -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);
|
||||
|
||||
/* Lista ferramentas disponíveis -> JSON array de objetos {name, description} */
|
||||
TB_MCP_API char* tb_mcp_list_tools(const char* url);
|
||||
/* 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 */
|
||||
|
||||
/* 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) {
|
||||
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';
|
||||
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:
|
||||
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)}}
|
||||
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:
|
||||
return json.loads(body)
|
||||
except Exception as e:
|
||||
return {"error": {"code": -2, "message": "invalid JSON: " + str(e)}}
|
||||
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 _stdio_jsonrpc(cmd, method, params):
|
||||
import subprocess
|
||||
args = cmd.split()
|
||||
def _send(self, obj):
|
||||
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)}}
|
||||
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 send(obj):
|
||||
line = (json.dumps(obj) + "\n").encode()
|
||||
proc.stdin.write(line)
|
||||
proc.stdin.flush()
|
||||
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 recv():
|
||||
line = proc.stdout.readline()
|
||||
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:
|
||||
return {}
|
||||
return json.loads(line.decode().strip())
|
||||
|
||||
continue
|
||||
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)
|
||||
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 _dispatch(url, method, params):
|
||||
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://"):
|
||||
return _stdio_jsonrpc(url[len("stdio://"):], method, params)
|
||||
self.t = _TbMcpStdio(url[len("stdio://"):])
|
||||
elif url.startswith("http://") or url.startswith("https://"):
|
||||
self.t = _TbMcpHttp(url)
|
||||
else:
|
||||
return _http_jsonrpc(url, method, params)
|
||||
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 mcp_ping(url):
|
||||
resp = _dispatch(url, "ping", {})
|
||||
if "error" in resp:
|
||||
return "erro: " + resp["error"].get("message", str(resp["error"]))
|
||||
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:
|
||||
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 _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 _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)
|
||||
|
||||
|
||||
@_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)))
|
||||
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:
|
||||
parts.append(str(item))
|
||||
return "\n".join(parts)
|
||||
return json.dumps(content, ensure_ascii=False, indent=2)
|
||||
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 ""
|
||||
@@ -13,7 +13,7 @@
|
||||
* tb_python - wrapper fino sobre o interpretador CPython embutido.
|
||||
*
|
||||
* O interpretador é compartilhado em todo o processo (singleton ref-counted).
|
||||
* Compile a lib como .so compartilhada para que python.so e mcp.so usem o
|
||||
* Compile a lib como .so compartilhada para que python.so e a libtinyblocks-mcp.so usem o
|
||||
* mesmo intérprete: libtinyblocks-python.so.
|
||||
*/
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Servidor MCP de teste (sem dependencias), para o test-mcp.
|
||||
|
||||
python3 tests/mcp_server.py --stdio
|
||||
python3 tests/mcp_server.py --http PORTA [--sse]
|
||||
|
||||
Coisas dificeis de proposito: notificacoes antes de cada resposta, um pedido
|
||||
"ping" do servidor no meio de tools/call, uma linha de log que nao e JSON (stdio),
|
||||
lista de ferramentas paginada, ferramenta que falha (isError) e ferramenta que
|
||||
derruba o servidor (o cliente deve reconectar).
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
PROTOCOL = "2025-06-18"
|
||||
|
||||
TOOLS = [
|
||||
{"name": "echo", "description": "Devolve a mensagem.\nSegunda linha da descricao.",
|
||||
"inputSchema": {"type": "object", "properties": {"message": {"type": "string"}}}},
|
||||
{"name": "add", "description": "Soma a e b.",
|
||||
"inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}},
|
||||
{"name": "fail", "description": "Sempre falha.", "inputSchema": {"type": "object"}},
|
||||
{"name": "image", "description": "Devolve uma imagem.", "inputSchema": {"type": "object"}},
|
||||
{"name": "crash", "description": "Derruba o servidor.", "inputSchema": {"type": "object"}},
|
||||
]
|
||||
PAGE = 3
|
||||
|
||||
|
||||
def text(t):
|
||||
return [{"type": "text", "text": t}]
|
||||
|
||||
|
||||
def call_tool(name, args):
|
||||
"""-> (result, crash)"""
|
||||
if name == "echo":
|
||||
return {"content": text(str(args.get("message", "")))}, False
|
||||
if name == "add":
|
||||
s = args.get("a", 0) + args.get("b", 0)
|
||||
return {"content": text(str(int(s) if float(s).is_integer() else s))}, False
|
||||
if name == "fail":
|
||||
return {"content": text("falhou de propósito"), "isError": True}, False
|
||||
if name == "image":
|
||||
return {"content": [{"type": "image", "data": "iVBORw0KGgo=", "mimeType": "image/png"},
|
||||
{"type": "text", "text": "legenda"}]}, False
|
||||
if name == "crash":
|
||||
return None, True
|
||||
return None, False
|
||||
|
||||
|
||||
def handle(msg):
|
||||
"""Mensagem do cliente -> (resposta ou None, crash)"""
|
||||
method = msg.get("method")
|
||||
rid = msg.get("id")
|
||||
if rid is None:
|
||||
return None, False # notificacao
|
||||
p = msg.get("params") or {}
|
||||
if method == "initialize":
|
||||
res = {"protocolVersion": PROTOCOL, "capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "tb-teste", "version": "0.1"}}
|
||||
elif method == "ping":
|
||||
res = {}
|
||||
elif method == "tools/list":
|
||||
start = int(p.get("cursor") or 0)
|
||||
res = {"tools": TOOLS[start:start + PAGE]}
|
||||
if start + PAGE < len(TOOLS):
|
||||
res["nextCursor"] = str(start + PAGE)
|
||||
elif method == "tools/call":
|
||||
res, crash = call_tool(p.get("name"), p.get("arguments") or {})
|
||||
if crash:
|
||||
return None, True
|
||||
if res is None:
|
||||
return {"jsonrpc": "2.0", "id": rid,
|
||||
"error": {"code": -32602, "message": "ferramenta desconhecida: %s" % p.get("name")}}, False
|
||||
else:
|
||||
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "metodo desconhecido"}}, False
|
||||
return {"jsonrpc": "2.0", "id": rid, "result": res}, False
|
||||
|
||||
|
||||
LOG = {"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "processando"}}
|
||||
|
||||
|
||||
def run_stdio():
|
||||
out = sys.stdout
|
||||
|
||||
def send(obj):
|
||||
out.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
|
||||
server_req = 1000
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
msg = json.loads(line)
|
||||
if "method" not in msg:
|
||||
continue # resposta do cliente (ao nosso ping)
|
||||
if msg.get("method") == "tools/call":
|
||||
out.write("log do servidor que nao e JSON\n")
|
||||
send({"jsonrpc": "2.0", "id": server_req, "method": "ping"}) # cliente deve responder
|
||||
server_req += 1
|
||||
reply = json.loads(sys.stdin.readline())
|
||||
if reply.get("result") != {}:
|
||||
send({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -1, "message": "cliente nao respondeu o ping"}})
|
||||
continue
|
||||
resp, crash = handle(msg)
|
||||
if crash:
|
||||
sys.exit(3)
|
||||
if resp is not None:
|
||||
send(LOG)
|
||||
send(resp)
|
||||
|
||||
|
||||
def run_http(port, sse):
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sessions = set()
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _reply(self, code, body=None, ctype="application/json", headers=None):
|
||||
data = body.encode("utf-8") if body is not None else b""
|
||||
self.send_response(code)
|
||||
for k, v in (headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
if body is not None:
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_DELETE(self):
|
||||
sessions.discard(self.headers.get("Mcp-Session-Id"))
|
||||
self._reply(200)
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/mcp":
|
||||
return self._reply(404, json.dumps({"error": "nao achei"}))
|
||||
accept = self.headers.get("Accept", "")
|
||||
if "application/json" not in accept or "text/event-stream" not in accept:
|
||||
return self._reply(406, json.dumps({"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32000, "message": "Accept incompleto"}}))
|
||||
msg = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))).decode("utf-8"))
|
||||
headers = {}
|
||||
if msg.get("method") == "initialize":
|
||||
sid = uuid.uuid4().hex
|
||||
sessions.add(sid)
|
||||
headers["Mcp-Session-Id"] = sid
|
||||
else:
|
||||
sid = self.headers.get("Mcp-Session-Id")
|
||||
if sid not in sessions:
|
||||
return self._reply(404, json.dumps({"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32001, "message": "sessao desconhecida"}}))
|
||||
if self.headers.get("MCP-Protocol-Version") != PROTOCOL:
|
||||
return self._reply(400, json.dumps({"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32000, "message": "sem MCP-Protocol-Version"}}))
|
||||
if "method" not in msg or msg.get("id") is None:
|
||||
return self._reply(202, None, headers=headers)
|
||||
resp, crash = handle(msg)
|
||||
if crash:
|
||||
return self._reply(500, json.dumps({"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32603, "message": "o servidor caiu"}}))
|
||||
if sse:
|
||||
body = ": aquecendo\n\n" + "event: message\ndata: " + json.dumps(LOG) + "\n\n" + \
|
||||
"event: message\ndata: " + json.dumps(resp, ensure_ascii=False) + "\n\n"
|
||||
return self._reply(200, body, "text/event-stream", headers)
|
||||
self._reply(200, json.dumps(resp, ensure_ascii=False), "application/json", headers)
|
||||
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", port), H)
|
||||
print("pronto", flush=True)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "--stdio" in sys.argv:
|
||||
run_stdio()
|
||||
elif "--http" in sys.argv:
|
||||
run_http(int(sys.argv[sys.argv.index("--http") + 1]), "--sse" in sys.argv)
|
||||
else:
|
||||
print(__doc__)
|
||||
@@ -0,0 +1,190 @@
|
||||
/* Teste da tinyblocks-mcp contra o servidor de teste (tests/mcp_server.py),
|
||||
* por stdio e por HTTP (resposta JSON e SSE), na API em C e nos blocos. */
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks-mcp/tb_mcp.h>
|
||||
#include <tb_errors.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 char g_server[512]; /* caminho do tests/mcp_server.py */
|
||||
|
||||
/* Sobe o servidor HTTP de teste e espera ele dizer "pronto" */
|
||||
static pid_t start_http(int port, bool sse) {
|
||||
int fd[2];
|
||||
if (pipe(fd) != 0) return -1;
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
dup2(fd[1], 1);
|
||||
close(fd[0]);
|
||||
char p[16];
|
||||
snprintf(p, sizeof(p), "%d", port);
|
||||
if (sse) execlp("python3", "python3", g_server, "--http", p, "--sse", (char*)NULL);
|
||||
else execlp("python3", "python3", g_server, "--http", p, (char*)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
close(fd[1]);
|
||||
char buf[64] = "";
|
||||
ssize_t n = read(fd[0], buf, sizeof(buf) - 1);
|
||||
close(fd[0]);
|
||||
if (n <= 0 || !strstr(buf, "pronto")) { kill(pid, SIGTERM); return -1; }
|
||||
return pid;
|
||||
}
|
||||
|
||||
static void stop_http(pid_t pid) {
|
||||
if (pid <= 0) return;
|
||||
kill(pid, SIGTERM);
|
||||
waitpid(pid, NULL, 0);
|
||||
}
|
||||
|
||||
/* Bateria comum a todos os transportes */
|
||||
static void suite(const char* label, const char* url, bool can_crash) {
|
||||
char msg[256];
|
||||
bool ok;
|
||||
char* r;
|
||||
#define T(cond, what) do { snprintf(msg, sizeof(msg), "%s: %s", label, what); CHECK(cond, msg); } while (0)
|
||||
|
||||
r = tb_mcp_ping(url, &ok);
|
||||
T(ok && r && !strcmp(r, "ok"), "ping");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_server_info(url, &ok);
|
||||
T(ok && r && !strcmp(r, "tb-teste 0.1"), "nome e versão do servidor");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_list_tools(url, &ok);
|
||||
T(ok && r && strstr(r, "echo: Devolve a mensagem.") && strstr(r, "crash: Derruba o servidor.") &&
|
||||
!strstr(r, "Segunda linha"), "lista as ferramentas (todas as páginas, 1a linha da descrição)");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_tool_names(url, &ok);
|
||||
T(ok && r && !strcmp(r, "echo\nadd\nfail\nimage\ncrash"), "nomes das ferramentas");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "echo", "{\"message\": \"olá, \\\"mundo\\\"\\n2a linha\"}", &ok);
|
||||
T(ok && r && !strcmp(r, "olá, \"mundo\"\n2a linha"), "chama echo (aspas, acento, quebra de linha)");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "add", "{\"a\": 2, \"b\": 40}", &ok);
|
||||
T(ok && r && !strcmp(r, "42"), "chama add (2 + 40 = 42)");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "image", "", &ok);
|
||||
T(ok && r && !strcmp(r, "[imagem image/png]\nlegenda"), "conteúdo de imagem vira texto, sem argumentos");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "fail", "{}", &ok);
|
||||
T(!ok && r && strstr(r, "falhou de propósito"), "ferramenta com isError vira erro");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "nao_existe", "{}", &ok);
|
||||
T(!ok && r && strstr(r, "ferramenta desconhecida"), "erro JSON-RPC vira erro com a mensagem");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "echo", "{quebrado", &ok);
|
||||
T(!ok && r && strstr(r, "JSON"), "argumentos inválidos: erro sem chamar o servidor");
|
||||
free(r);
|
||||
|
||||
r = tb_mcp_call_tool(url, "echo", "[1, 2]", &ok);
|
||||
T(!ok && r && strstr(r, "objeto JSON"), "argumentos devem ser um objeto");
|
||||
free(r);
|
||||
|
||||
if (can_crash) {
|
||||
r = tb_mcp_call_tool(url, "crash", "{}", &ok);
|
||||
T(!ok, "servidor que cai: a chamada falha");
|
||||
free(r);
|
||||
r = tb_mcp_call_tool(url, "echo", "{\"message\": \"voltei\"}", &ok);
|
||||
T(ok && r && !strcmp(r, "voltei"), "depois de cair, reconecta sozinho");
|
||||
free(r);
|
||||
}
|
||||
#undef T
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
(void)argc;
|
||||
/* tests/mcp_server.py, ao lado deste teste no repositorio */
|
||||
snprintf(g_server, sizeof(g_server), "%s", "tests/mcp_server.py");
|
||||
if (access(g_server, R_OK) != 0) { printf("FAIL não achei %s (rode da raiz)\n", g_server); return 1; }
|
||||
(void)argv;
|
||||
|
||||
CHECK(tb_mcp_init(), "cliente MCP carrega no Python embutido");
|
||||
|
||||
char url[600];
|
||||
snprintf(url, sizeof(url), "stdio://python3 %s --stdio", g_server);
|
||||
suite("stdio", url, true);
|
||||
|
||||
bool ok;
|
||||
char* r = tb_mcp_ping("stdio://comando-que-nao-existe-xyz", &ok);
|
||||
CHECK(!ok && r && strstr(r, "comando nao encontrado"), "stdio: comando inexistente dá erro claro");
|
||||
free(r);
|
||||
r = tb_mcp_ping("ftp://x", &ok);
|
||||
CHECK(!ok && r && strstr(r, "endereco invalido"), "endereço inválido dá erro claro");
|
||||
free(r);
|
||||
|
||||
int port = 18000 + (int)(getpid() % 2000);
|
||||
pid_t http = start_http(port, false);
|
||||
CHECK(http > 0, "servidor HTTP de teste sobe");
|
||||
snprintf(url, sizeof(url), "http://127.0.0.1:%d/mcp", port);
|
||||
if (http > 0) suite("http", url, false);
|
||||
stop_http(http);
|
||||
r = tb_mcp_ping(url, &ok); /* a sessao era desse servidor, que saiu */
|
||||
CHECK(!ok && r && strstr(r, "conectar"), "http: servidor fora do ar dá erro de conexão");
|
||||
free(r);
|
||||
|
||||
pid_t sse = start_http(port + 1, true);
|
||||
CHECK(sse > 0, "servidor HTTP (SSE) de teste sobe");
|
||||
snprintf(url, sizeof(url), "http://127.0.0.1:%d/mcp", port + 1);
|
||||
if (sse > 0) suite("http+sse", url, false);
|
||||
|
||||
/* Blocos: MCP.Call devolve o texto; erro vira erro do TinyBlocks e o
|
||||
* "tente obter" transforma em resultado */
|
||||
TinyBlocks* rt = NULL;
|
||||
tinyblocks_init(&rt, NULL);
|
||||
tb_library_register(rt, tb_errors_get_library());
|
||||
tb_library_register(rt, tb_mcp_get_library());
|
||||
TinyBlocks_TypeBlock* tcall = tb_type_block_find(rt, "MCP.Call");
|
||||
CHECK(tcall && tcall->label && !strcmp(tcall->label, "chame %2 do servidor MCP %1 com %3"),
|
||||
"blocos: MCP.Call registrado com o rótulo do editor");
|
||||
if (tcall) {
|
||||
TinyBlocks_Block* call = tb_block_create(rt, tcall);
|
||||
tb_block_set_default(call, 0, tb_value_text(url));
|
||||
tb_block_set_default(call, 1, tb_value_text("add"));
|
||||
tb_block_set_default(call, 2, tb_value_text("{\"a\": 1, \"b\": 2}"));
|
||||
tb_block_eval(call, rt);
|
||||
CHECK(call->outputs[0].kind == TB_VALUE_TEXT && !strcmp(call->outputs[0].as.text, "3"),
|
||||
"blocos: chame add com {a: 1, b: 2} = 3");
|
||||
|
||||
tb_block_set_default(call, 1, tb_value_text("fail"));
|
||||
call->dirty = true;
|
||||
tinyblocks_clear_error(rt);
|
||||
tb_block_eval(call, rt);
|
||||
const char* e = tinyblocks_last_error(rt);
|
||||
CHECK(e && strstr(e, "MCP: falhou de propósito"), "blocos: falha da ferramenta vira erro do TinyBlocks");
|
||||
tinyblocks_clear_error(rt);
|
||||
|
||||
TinyBlocks_Block* att = tb_block_create(rt, tb_type_block_find(rt, "Errors.Attempt"));
|
||||
tb_block_connect(att, 0, call, 0);
|
||||
call->dirty = true; /* chama de novo, agora por dentro do "tente obter" */
|
||||
tb_block_eval(att, rt);
|
||||
CHECK(tb_value_is_err(att->outputs[0]), "blocos: \"tente obter\" transforma a falha em Erro(...)");
|
||||
tinyblocks_clear_error(rt);
|
||||
|
||||
TinyBlocks_Block* ping = tb_block_create(rt, tb_type_block_find(rt, "MCP.Ping"));
|
||||
tb_block_set_default(ping, 0, tb_value_text("http://127.0.0.1:1/mcp"));
|
||||
tb_block_eval(ping, rt);
|
||||
CHECK(ping->outputs[0].kind == TB_VALUE_INTEGER && ping->outputs[0].as.integer == 0 &&
|
||||
!tinyblocks_last_error(rt)[0], "blocos: \"responde?\" é falso sem erro quando o servidor não existe");
|
||||
}
|
||||
tinyblocks_deinit(&rt);
|
||||
stop_http(sse);
|
||||
|
||||
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
|
||||
return fails != 0;
|
||||
}
|
||||
Reference in new issue
Block a user