From 2a2d22a64a05590362f8e99a6c99d610b92f9d44 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Fri, 23 Oct 2026 08:13:24 -0300 Subject: [PATCH] =?UTF-8?q?Editor=20como=20servidor=20MCP:=20agentes=20lee?= =?UTF-8?q?m=20e=20editam=20as=20pilhas=20por=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tinyblocks-mcp-server (C, sem Python): servidor MCP nas duas eras do protocolo. Moderna (2026-07-28): sem handshake, versão e capacidades em _meta a cada pedido, server/discover, resultType, cabeçalhos MCP-Protocol-Version/Mcp-Method/Mcp-Name conferidos com o corpo (HeaderMismatch, UnsupportedProtocolVersion). Antiga: initialize. HTTP só em 127.0.0.1 (Origin conferido, GET/DELETE 405, sem sessão), sem bloquear (o editor atende a cada quadro), e stdio. test-mcp-server. Ferramentas do editor (tb_editor_mcp.c; http://127.0.0.1:7811/mcp, TINYBLOCKS_MCP_PORT muda a porta, 0 = sem rede): get_editor, list_block_types, list_stacks (scratchblocks + ids dos blocos), get_scratchblocks, add_scratchblocks, replace_stack, move_stack, delete_stack, add_block / move_block (solto, embaixo, num campo ou numa boca; alone = só o bloco) / delete_block / set_inputs, run / stop / get_output, new_tab / select_tab, save_project / open_project e ui_tree / ui_action / ui_type (a interface pela árvore acessível). O editor exporta e importa scratchblocks por pilha (numa aba existente, numa posição), e o modelo de blocos fica na API privada para o servidor. O scratchblocks usa também os rótulos declarados pelas libraries. Duplicar um bloco C de três bocas copiava só duas. O cliente (tinyblocks-mcp) fala as duas eras: sonda com server/discover no stdio, pedido moderno no HTTP, e cai para o initialize com servidores antigos. test-mcp testa contra o servidor antigo de teste e contra o moderno (stdio e HTTP); harness cenário 29 usa as ferramentas do editor. Co-Authored-By: Claude Opus 5.5 --- Makefile | 35 +- libraries/tinyblocks-editor/Makefile | 8 +- .../tinyblocks-editor/include/tb_editor.h | 6 + .../include/tb_editor_internal.h | 51 + libraries/tinyblocks-editor/library.toml | 4 +- libraries/tinyblocks-editor/src/tb_editor.c | 232 +++-- .../tinyblocks-editor/src/tb_editor_mcp.c | 929 ++++++++++++++++++ libraries/tinyblocks-mcp-server/Makefile | 30 + .../include/tb_mcp_server.h | 105 ++ .../include/tb_mcp_server_internal.h | 40 + libraries/tinyblocks-mcp-server/library.toml | 19 + .../tinyblocks-mcp-server/src/tb_mcp_http.c | 218 ++++ .../tinyblocks-mcp-server/src/tb_mcp_server.c | 462 +++++++++ .../include/tinyblocks-mcp/tb_mcp.h | 6 +- libraries/tinyblocks-mcp/src/tb_mcp.c | 4 + libraries/tinyblocks-mcp/src/tb_mcp.py | 138 ++- tests/editor_harness.c | 181 ++++ tests/mcp_server_test.c | 230 +++++ tests/mcp_test.c | 87 +- 19 files changed, 2669 insertions(+), 116 deletions(-) create mode 100644 libraries/tinyblocks-editor/src/tb_editor_mcp.c create mode 100644 libraries/tinyblocks-mcp-server/Makefile create mode 100644 libraries/tinyblocks-mcp-server/include/tb_mcp_server.h create mode 100644 libraries/tinyblocks-mcp-server/include/tb_mcp_server_internal.h create mode 100644 libraries/tinyblocks-mcp-server/library.toml create mode 100644 libraries/tinyblocks-mcp-server/src/tb_mcp_http.c create mode 100644 libraries/tinyblocks-mcp-server/src/tb_mcp_server.c create mode 100644 tests/mcp_server_test.c diff --git a/Makefile b/Makefile index e328985..152a69b 100644 --- a/Makefile +++ b/Makefile @@ -46,6 +46,7 @@ SD_DIR := $(LIBDIR)/tinyblocks-sdl2 PY_DIR := $(LIBDIR)/tinyblocks-python MC_DIR := $(LIBDIR)/tinyblocks-mcp A11Y_DIR := $(LIBDIR)/tinyblocks-a11y +MCPS_DIR := $(LIBDIR)/tinyblocks-mcp-server GFX_INC := $(GX_DIR)/include GFX_HDR := $(GFX_INC)/tb_graphics.h @@ -96,13 +97,14 @@ LIBM_A := $(LIBM_DIR)/build/libtinyblocks-libman.a SYN_A := $(SYN_DIR)/build/libtinyblocks-syntax.a SB_A := $(SB_DIR)/build/libtinyblocks-scratchblocks.a A11Y_A := $(A11Y_DIR)/build/libtinyblocks-a11y.a +MCPS_A := $(MCPS_DIR)/build/libtinyblocks-mcp-server.a LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ $(foreach l,$(CAT_LIBS),-L$(LIBDIR)/tinyblocks-$(l)/build) -L$(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-mcp 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-mcp-server 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 \ @@ -166,12 +168,15 @@ lib-$(1): endef $(foreach l,$(CAT_LIBS),$(eval $(call CAT_LIB_TARGET,$(l)))) -lib-editor: lib-a11y +lib-editor: lib-a11y lib-mcp-server $(MAKE) -C $(ED_DIR) lib-a11y: $(MAKE) -C $(A11Y_DIR) +lib-mcp-server: + $(MAKE) -C $(MCPS_DIR) + lib-toml: $(MAKE) -C $(TOML_DIR) @@ -249,7 +254,7 @@ lib-mcp: lib-python libs: static lib-events lib-control lib-errors lib-operators lib-variables \ lib-appearance lib-pen lib-fs lib-os lib-input lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-scratchblocks lib-regex lib-markdown lib-opentype lib-api lib-libman lib-a11y lib-editor + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-scratchblocks lib-regex lib-markdown lib-opentype lib-api lib-libman lib-a11y lib-mcp-server lib-editor @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + syntax + regex + markdown + opentype + api + libman + a11y + editor" category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so) @@ -292,9 +297,9 @@ $(BUILD)/editor: examples/editor/main.c static libs -I$(ED_DIR)/include -I$(GFX_INC) $(CAT_INCS) \ -I$(FS_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include \ -I$(JSON_DIR)/include -I$(XML_DIR)/include -I$(CSV_DIR)/include -I$(BP_DIR)/include \ - -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(SYN_DIR)/include -I$(A11Y_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(SYN_DIR)/include -I$(A11Y_DIR)/include -I$(MCPS_DIR)/include \ $< -o $@ \ - -Wl,--start-group $(ED_A) $(A11Y_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(SB_A) $(API_A) $(LIBM_A) $(SYN_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ + -Wl,--start-group $(ED_A) $(A11Y_A) $(MCPS_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(SB_A) $(API_A) $(LIBM_A) $(SYN_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ $(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm -rdynamic \ '-Wl,-rpath,$$ORIGIN' @@ -445,15 +450,17 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(EIMG_DIR)/include/tb_editor_image.h \ $(EFILES_DIR)/include/tb_editor_files.h \ $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h \ + $(EDITOR_SRC)/tb_editor_mcp.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ lib-blueprint ed-modules @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) \ - -I$(ED_DIR)/include -I$(A11Y_DIR)/include -DTB_EDITOR_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ + -I$(ED_DIR)/include -I$(A11Y_DIR)/include -I$(MCPS_DIR)/include -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include -I$(SB_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ $(EDITOR_SRC)/tb_editor_modules.c \ $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c \ + $(EDITOR_SRC)/tb_editor_mcp.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ $(BP_DIR)/src/blueprint.c $(BP_DIR)/src/serialize.c \ $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ @@ -514,10 +521,10 @@ test-environ: $(BUILD)/environ_test ## Roda o teste da environ (ASan/UBSan) # -- 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 +$(BUILD)/mcp_test: tests/mcp_test.c tests/mcp_server.py $(ER_DIR)/src/tb_errors.c static lib-mcp lib-mcp-server @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 $@ \ + $(CC) $(CFLAGS) -g -I$(MC_DIR)/include -I$(PY_DIR)/include -I$(ER_DIR)/include -I$(MCPS_DIR)/include \ + tests/mcp_test.c $(ER_DIR)/src/tb_errors.c $(MCPS_A) -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)' @@ -525,6 +532,16 @@ $(BUILD)/mcp_test: tests/mcp_test.c tests/mcp_server.py $(ER_DIR)/src/tb_errors. test-mcp: $(BUILD)/mcp_test ## Roda o teste do cliente MCP (stdio, HTTP e SSE) ./$(BUILD)/mcp_test +# -- Teste do servidor MCP (as duas eras do protocolo, stdio e HTTP) --- +$(BUILD)/mcp_server_test: tests/mcp_server_test.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ + $(MCPS_DIR)/include/tb_mcp_server.h $(MCPS_DIR)/include/tb_mcp_server_internal.h static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -DTB_MCP_SERVER_PRIVATE_API -I$(MCPS_DIR)/include \ + $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c tests/mcp_server_test.c -o $@ $(LIB_A) -lm + +test-mcp-server: $(BUILD)/mcp_server_test ## Roda o teste do servidor MCP (ASan/UBSan) + ./$(BUILD)/mcp_server_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) diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile index 2c4b249..65806cd 100644 --- a/libraries/tinyblocks-editor/Makefile +++ b/libraries/tinyblocks-editor/Makefile @@ -17,6 +17,7 @@ CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ -I../tinyblocks-syntax/include \ -I../tinyblocks-scratchblocks/include \ -I../tinyblocks-a11y/include \ + -I../tinyblocks-mcp-server/include \ -Ilibraries/tinyblocks-editor-widgets/include \ -Ilibraries/tinyblocks-editor-image/include \ -Ilibraries/tinyblocks-editor-files/include @@ -28,7 +29,7 @@ IMG_A := $(IMG_DIR)/build/libtinyblocks-editor-image.a FILES_DIR := libraries/tinyblocks-editor-files FILES_A := $(FILES_DIR)/build/libtinyblocks-editor-files.a -OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o $(BUILD)/tb_editor_modules.o +OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o $(BUILD)/tb_editor_modules.o $(BUILD)/tb_editor_mcp.o LIB_A := $(BUILD)/libtinyblocks-editor.a LIB_SO := $(BUILD)/libtinyblocks-editor.so @@ -54,6 +55,11 @@ $(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h include/tb_editor_inte @mkdir -p $(BUILD) $(CC) $(CFLAGS) -fPIC -c $< -o $@ +$(BUILD)/tb_editor_mcp.o: src/tb_editor_mcp.c include/tb_editor_internal.h \ + ../tinyblocks-mcp-server/include/tb_mcp_server.h ../tinyblocks-a11y/include/tb_a11y.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + $(BUILD)/tb_stage_widget.o: src/tb_stage_widget.c include/tb_stage_widget.h \ ../tinyblocks-graphics/include/tb_graphics.h @mkdir -p $(BUILD) diff --git a/libraries/tinyblocks-editor/include/tb_editor.h b/libraries/tinyblocks-editor/include/tb_editor.h index 80c4ca5..b2e54a9 100644 --- a/libraries/tinyblocks-editor/include/tb_editor.h +++ b/libraries/tinyblocks-editor/include/tb_editor.h @@ -41,4 +41,10 @@ TB_API void tb_editor_preload(const char* path); typedef struct TinyBlocks_A11yTree TinyBlocks_A11yTree; TB_API TinyBlocks_A11yTree* tb_editor_accessible(TinyBlocks_Block* scene); +/* Servidor MCP do editor (tb_mcp_server.h, da tinyblocks-mcp-server): as + * ferramentas para agentes lerem e editarem as pilhas. Escuta em + * http://127.0.0.1:TINYBLOCKS_MCP_PORT/mcp (padrao 7811; 0 = so sem rede). */ +struct TbMcpServer; +TB_API struct TbMcpServer* tb_editor_mcp_server(TinyBlocks_Block* scene); + #endif /* TINYBLOCKS_EDITOR_H */ diff --git a/libraries/tinyblocks-editor/include/tb_editor_internal.h b/libraries/tinyblocks-editor/include/tb_editor_internal.h index 85062ee..996479e 100644 --- a/libraries/tinyblocks-editor/include/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/include/tb_editor_internal.h @@ -973,6 +973,9 @@ typedef struct Ed { TinyBlocks_A11yTree* ax_tree; bool ax_enabled; /* TINYBLOCKS_A11Y=0 desliga */ bool ax_on; /* montando a arvore neste desenho */ + + /* Servidor MCP: agentes leem e editam as pilhas por ferramentas */ + struct TbMcpServer* mcp; } Ed; static inline TinyBlocks_A11yTree* ed_ax(Ed* ed) { return ed->ax_on ? ed->ax_tree : NULL; } @@ -1026,6 +1029,54 @@ typedef struct TabClass { } TabClass; const TabClass* tab_class(const Tab* T); + +/* == Modelo de blocos (tb_editor.c), usado tambem pelo servidor MCP === + * Indices de bloco sao posicoes no pool da aba (T->ws); "pilha" = bloco de + * topo (T->top). Mudou a aba: layout_tab(T). */ +int blk_new(Tab* T, TinyBlocks_TypeBlock* type); +void top_add(Tab* T, int bi); +void top_remove(Tab* T, int bi); +void blk_link(Tab* T, int parent, int rel, int child); +void detach(Tab* T, int bi); /* vira pilha, com os de baixo */ +void attach_insert(Tab* T, int parent, int rel, int bi); /* pilha bi em parent/rel */ +void attach_arg(Tab* T, int parent, int s, int bi); /* reporter bi no campo s */ +int chain_last(Tab* T, int bi); +int stack_root(Tab* T, int bi); +void free_tree(Ed* ed, Tab* T, int bi); /* bi, o encaixado e os de baixo */ +void delete_heal(Ed* ed, Tab* T, int bi); /* so bi; os de baixo sobem */ +void layout_tab(Tab* T); +void stack_bounds(Tab* T, int root, float* x0, float* y0, float* x1, float* y1); +void cleanup_ws(Ed* ed); +Shape shape_of(const TinyBlocks_TypeBlock* t); +bool shape_is_value(Shape s); +int shape_mouths(Shape s); +bool is_cap(const TinyBlocks_TypeBlock* t); +const char* mouth_label(const TinyBlocks_TypeBlock* t, int k); +int input_count(const TinyBlocks_TypeBlock* t); +bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i); +const char* slot_src(const EdBlock* b, int s); +int cat_of(Ed* ed, const char* type_name); +const BlockSpec* spec_of_type(const TinyBlocks_TypeBlock* t); +void ax_block_label(Tab* T, int bi, char* out, size_t cap, int depth); /* "repita (10) vezes" */ +void tab_select(Ed* ed, int i); +void run_flag(Ed* ed); +void run_click(Ed* ed, int bi); /* na aba atual */ +void vm_stop(Ed* ed); +bool project_load(Ed* ed, const char* path); +bool project_save(Ed* ed, const char* path); +/* scratchblocks: pilha head (head < 0 = aba inteira) -> texto (malloc) */ +char* ed_scratchblocks_export(Ed* ed, const Tab* T, int head); +/* texto -> pilhas novas na aba T a partir de (x, y); devolve quantas (-1 = nenhuma) */ +int ed_scratchblocks_import(Ed* ed, Tab* T, const char* text, float x, float y, + int* heads, int max, char* warn, size_t warn_cap); + +void ed_type_text(Ed* ed, const char* text); /* como digitar no teclado */ +void ed_press_key(Ed* ed, int scancode); + +/* == Servidor MCP do editor (tb_editor_mcp.c) == */ +void ed_mcp_start(Ed* ed); /* TINYBLOCKS_MCP_PORT (0 = desliga) */ +void ed_mcp_poll(Ed* ed); /* a cada quadro */ +void ed_mcp_stop(Ed* ed); bool tab_has_define(const Tab* T); bool tab_has_define(const Tab* T); void tab_doc_free(Tab* T); diff --git a/libraries/tinyblocks-editor/library.toml b/libraries/tinyblocks-editor/library.toml index 7190c69..716f7a5 100644 --- a/libraries/tinyblocks-editor/library.toml +++ b/libraries/tinyblocks-editor/library.toml @@ -11,10 +11,10 @@ dark = [255, 51, 85, 255] bundle_members = ["tinyblocks-editor-widgets", "tinyblocks-editor-image", "tinyblocks-editor-files"] [build] -sources = ["src/tb_editor.c", "src/tb_stage_widget.c", "src/tb_editor_modules.c"] +sources = ["src/tb_editor.c", "src/tb_stage_widget.c", "src/tb_editor_modules.c", "src/tb_editor_mcp.c"] includes = ["include"] # tb_editor_internal.h, tb_editor_modules.h e tb_stage_widget.h sao API privada defines = ["TB_EDITOR_PRIVATE_API"] shared = "build/libtinyblocks-editor.so" static = "build/libtinyblocks-editor.a" -depends = ["tinyblocks-a11y", "tinyblocks-editor-widgets", "tinyblocks-editor-image", "tinyblocks-editor-files"] +depends = ["tinyblocks-a11y", "tinyblocks-mcp-server", "tinyblocks-editor-widgets", "tinyblocks-editor-image", "tinyblocks-editor-files"] diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index 41b6cfc..fb63704 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -165,7 +165,7 @@ static const BlockSpec* spec_of(const char* tn) { /* Rotulo do tipo: o da tabela do editor ou o que a library declarou * (tb_type_block_set_label); NULL = so o nome e os campos */ -static const BlockSpec* spec_of_type(const TinyBlocks_TypeBlock* t) { +const BlockSpec* spec_of_type(const TinyBlocks_TypeBlock* t) { static BlockSpec own; if (!t) return NULL; const BlockSpec* sp = spec_of(t->type_name); @@ -176,14 +176,14 @@ static const BlockSpec* spec_of_type(const TinyBlocks_TypeBlock* t) { return &own; } -static int input_count(const TinyBlocks_TypeBlock* t) { +int input_count(const TinyBlocks_TypeBlock* t) { if (!t) return 0; return t->input_desc_count < MAX_INPUTS ? (int)t->input_desc_count : MAX_INPUTS; } /* A forma vem do tipo (a library declara): bloco C = classe de fluxo, chapeu/booleano = shape ou saida TB_SLOT_BOOLEAN */ -static Shape shape_of(const TinyBlocks_TypeBlock* t) { +Shape shape_of(const TinyBlocks_TypeBlock* t) { if (!t) return SH_STACK; if (t->flow) return t->flow->mouths >= 3 ? SH_C3 : t->flow->mouths == 2 ? SH_C2 : SH_C1; switch (t->shape) { @@ -197,19 +197,19 @@ static Shape shape_of(const TinyBlocks_TypeBlock* t) { return t->output_desc_count > 0 ? SH_REPORTER : SH_STACK; } -static bool shape_is_value(Shape s) { return s == SH_REPORTER || s == SH_BOOL; } +bool shape_is_value(Shape s) { return s == SH_REPORTER || s == SH_BOOL; } /* Bocas de um bloco C (0 se nao for C) */ -static int shape_mouths(Shape s) { return s == SH_C1 ? 1 : s == SH_C2 ? 2 : s == SH_C3 ? 3 : 0; } +int shape_mouths(Shape s) { return s == SH_C1 ? 1 : s == SH_C2 ? 2 : s == SH_C3 ? 3 : 0; } /* Texto da faixa entre a boca k e a k+1 ("senão", "se der erro"...) */ -static const char* mouth_label(const TinyBlocks_TypeBlock* t, int k) { +const char* mouth_label(const TinyBlocks_TypeBlock* t, int k) { if (!t || !t->flow || k < 0 || k >= TB_FLOW_MAX_MOUTHS - 1) return ""; return t->flow->labels[k] ? t->flow->labels[k] : ""; } /* Bloco "tampa" (como o "sempre" do Scratch): nada encaixa embaixo dele */ -static bool is_cap(const TinyBlocks_TypeBlock* t) { +bool is_cap(const TinyBlocks_TypeBlock* t) { return t && t->flow && t->flow->cap; } @@ -228,7 +228,7 @@ static const UserParam* user_param_at(const UserBlockDef* def, int idx) { } /* Campo hexagonal (recebe booleano): traco do campo, declarado no tipo */ -static bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i) { +bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i) { return i >= 0 && (tb_type_block_input_flags(t, (uint32_t)i) & TB_SLOT_BOOLEAN); } @@ -261,7 +261,7 @@ static int cat_of_type(Ed* ed, const TinyBlocks_TypeBlock* t) { return -1; } -static int cat_of(Ed* ed, const char* n) { +int cat_of(Ed* ed, const char* n) { if (!n) return -1; return cat_of_type(ed, tb_type_block_find(ed->rt, n)); } @@ -343,7 +343,7 @@ static int blk_alloc(Tab* T) { return -1; } -static int blk_new(Tab* T, TinyBlocks_TypeBlock* type) { +int blk_new(Tab* T, TinyBlocks_TypeBlock* type) { int i = blk_alloc(T); if (i < 0) return -1; EdBlock* b = &T->ws[i]; @@ -353,7 +353,7 @@ static int blk_new(Tab* T, TinyBlocks_TypeBlock* type) { return i; } -static void top_remove(Tab* T, int bi) { +void top_remove(Tab* T, int bi) { for (int i = 0; i < T->top_n; i++) { if (T->top[i] != bi) continue; memmove(&T->top[i], &T->top[i+1], (size_t)(T->top_n - i - 1) * sizeof(int)); @@ -363,13 +363,13 @@ static void top_remove(Tab* T, int bi) { } /* Adiciona (ou traz para a frente) uma pilha de topo */ -static void top_add(Tab* T, int bi) { +void top_add(Tab* T, int bi) { top_remove(T, bi); if (T->top_n < MAX_WS) T->top[T->top_n++] = bi; } /* Liga child ao pai na relação rel (child - -1 desliga) */ -static void blk_link(Tab* T, int parent, int rel, int child) { +void blk_link(Tab* T, int parent, int rel, int child) { EdBlock* p = &T->ws[parent]; if (rel == REL_NEXT) p->next = child; else if (rel < REL_ARG0) p->sub[rel - REL_SUB0] = child; @@ -385,7 +385,7 @@ static int linked(Tab* T, int parent, int rel) { } /* Solta bi do pai; vira topo de pilha (levando os blocos abaixo dele) */ -static void detach(Tab* T, int bi) { +void detach(Tab* T, int bi) { EdBlock* b = &T->ws[bi]; if (b->parent < 0) return; blk_link(T, b->parent, b->prel, -1); @@ -393,12 +393,12 @@ static void detach(Tab* T, int bi) { top_add(T, bi); } -static int chain_last(Tab* T, int bi) { +int chain_last(Tab* T, int bi) { while (T->ws[bi].next >= 0) bi = T->ws[bi].next; return bi; } -static int stack_root(Tab* T, int bi) { +int stack_root(Tab* T, int bi) { while (T->ws[bi].parent >= 0) bi = T->ws[bi].parent; return bi; } @@ -410,7 +410,7 @@ static float chain_h(Tab* T, int head) { } /* Insere a pilha bi (de topo) em parent/rel; o que estava lá vai para baixo dela */ -static void attach_insert(Tab* T, int parent, int rel, int bi) { +void attach_insert(Tab* T, int parent, int rel, int bi) { top_remove(T, bi); int old = linked(T, parent, rel); int last = chain_last(T, bi); @@ -428,7 +428,7 @@ static void attach_above(Tab* T, int target, int bi) { } /* Encaixa o repórter bi no campo s; um repórter que já estava lá é expulso */ -static void attach_arg(Tab* T, int parent, int s, int bi) { +void attach_arg(Tab* T, int parent, int s, int bi) { top_remove(T, bi); int old = T->ws[parent].args[s]; if (old >= 0) { @@ -466,7 +466,7 @@ static int copy_tree(Tab* S, int si, Tab* D, bool with_next) { int k = copy_tree(S, o->args[s], D, false); if (k >= 0) blk_link(D, ni, REL_ARG0 + s, k); } - for (int k = 0; k < 2; k++) { + for (int k = 0; k < MAX_MOUTHS; k++) { if (o->sub[k] < 0) continue; int h = copy_tree(S, o->sub[k], D, true); if (h >= 0) blk_link(D, ni, REL_SUB0 + k, h); @@ -478,7 +478,7 @@ static int copy_tree(Tab* S, int si, Tab* D, bool with_next) { } /* Libera bi, tudo o que está encaixado nele e os blocos abaixo */ -static void free_tree(Ed* ed, Tab* T, int bi) { +void free_tree(Ed* ed, Tab* T, int bi) { while (bi >= 0) { EdBlock* b = &T->ws[bi]; int nx = b->next; @@ -496,7 +496,7 @@ static void free_tree(Ed* ed, Tab* T, int bi) { } /* Apaga só bi (com o que está encaixado nele); os blocos abaixo sobem */ -static void delete_heal(Ed* ed, Tab* T, int bi) { +void delete_heal(Ed* ed, Tab* T, int bi) { EdBlock* b = &T->ws[bi]; int nx = b->next, par = b->parent, rel = b->prel; if (nx >= 0) { b->next = -1; T->ws[nx].parent = -1; T->ws[nx].prel = REL_NONE; } @@ -512,7 +512,7 @@ static void delete_heal(Ed* ed, Tab* T, int bi) { /* === * Layout: mede (tamanhos) e posiciona (coordenadas do workspace) * === */ -static const char* slot_src(const EdBlock* b, int s) { +const char* slot_src(const EdBlock* b, int s) { return (is_lit_text(b->type) && s == 0) ? b->lit_text : b->in_text[s]; } @@ -779,7 +779,7 @@ static void place_chain(Tab* T, int head, float x, float y) { for (int c = head; c >= 0; c = T->ws[c].next) { place(T, c, x, y); y += T->ws[c].h; } } -static void layout_tab(Tab* T) { +void layout_tab(Tab* T) { for (int i = 0; i < T->top_n; i++) { int h = T->top[i]; measure_chain(T, h); @@ -935,7 +935,7 @@ static void ax_cat(char* out, size_t cap, size_t* len, const char* s) { /* Rotulo falado de um bloco, com o que esta nos campos: * "repita (10) vezes", "se <(x) > (5)> então", "defina desenhe (x)" */ -static void ax_block_label(Tab* T, int bi, char* out, size_t cap, int depth) { +void ax_block_label(Tab* T, int bi, char* out, size_t cap, int depth) { EdBlock* b = &T->ws[bi]; size_t len = 0; out[0] = 0; @@ -1513,14 +1513,14 @@ static void vm_frame(Ed* ed) { } /* Botao vermelho: para todos os scripts */ -static void vm_stop(Ed* ed) { +void vm_stop(Ed* ed) { bool was = ed->vm_running; run_reset(ed); if (was) run_end(ed); } /* Bandeira verde: roda os scripts "quando a bandeira for clicado", de cima para baixo */ -static void run_flag(Ed* ed) { +void run_flag(Ed* ed) { run_begin(ed, true); tb_input_timer_reset(); /* como no Scratch: a bandeira zera o cronometro */ int heads[MAX_WS], n = 0; @@ -1625,7 +1625,7 @@ static void bubble_set(Ed* ed, int root, TinyBlocks_Value* v) { } /* Clique num bloco: roda a pilha inteira, ou mostra o valor de um repórter */ -static void run_click(Ed* ed, int bi) { +void run_click(Ed* ed, int bi) { int root = stack_root(&CT, bi); Shape sh = shape_of(blk_type(ed, &CT.ws[root])); run_begin(ed, false); @@ -2473,7 +2473,7 @@ static float fly_max_scroll(Ed* ed) { /* === * Abas e blocos compostos * === */ -static void tab_select(Ed* ed, int i) { +void tab_select(Ed* ed, int i) { if (i < 0 || i >= ed->tab_n) return; ed->cur_tab = i; ed->editing = false; @@ -2745,42 +2745,45 @@ static void save_composite_from_tab(Ed* ed) { /* === * Blueprint: conversao Ed <-> TbBlueprint e I/O de projeto * === */ +/* Blocos, pilhas e grupos de uma aba do editor -> aba da blueprint */ +static void tab_to_bp(const Tab* T, TbBpTab* B) { + B->comp_id = T->comp_id; + B->color_idx = T->color_idx; + B->ws_sx = T->ws_sx; B->ws_sy = T->ws_sy; + B->top_n = T->top_n; + for (int i = 0; i < T->top_n; i++) B->top[i] = T->top[i]; + B->group_n = T->group_n < TB_BP_MAX_GROUPS ? T->group_n : TB_BP_MAX_GROUPS; + for (int g = 0; g < B->group_n; g++) { + const WsGroup* G = &T->groups[g]; + B->groups[g] = (TbBpGroup){ G->x, G->y, G->w, G->h, G->color, "" }; + snprintf(B->groups[g].title, sizeof(B->groups[g].title), "%s", G->title); + } + for (int i = 0; i < MAX_WS; i++) { + const EdBlock* b = &T->ws[i]; + if (!b->used) continue; + TbBpBlock* o = &B->blocks[i]; + o->used = true; + snprintf(o->type, sizeof(o->type), "%s", b->type_name); + o->x = b->x; o->y = b->y; + o->parent = b->parent; o->prel = b->prel; o->next = b->next; + for (int k = 0; k < MAX_MOUTHS; k++) o->sub[k] = b->sub[k]; + for (int s = 0; s < MAX_INPUTS; s++) { + o->args[s] = b->args[s]; + snprintf(o->in_text[s], sizeof(o->in_text[s]), "%s", b->in_text[s]); + } + snprintf(o->lit, sizeof(o->lit), "%s", b->lit_text); + } +} + static TbBlueprint* ed_to_blueprint(Ed* ed) { TbBlueprint* bp = tb_blueprint_new(); if (!bp) return NULL; bp->cur_tab = ed->cur_tab; for (int ti = 0; ti < ed->tab_n; ti++) { - Tab* T = &ed->tabs[ti]; - int idx = tb_blueprint_add_tab(bp, T->name, T->is_composite); + int idx = tb_blueprint_add_tab(bp, ed->tabs[ti].name, ed->tabs[ti].is_composite); if (idx < 0) break; - TbBpTab* B = &bp->tabs[idx]; - B->comp_id = T->comp_id; - B->color_idx = T->color_idx; - B->ws_sx = T->ws_sx; B->ws_sy = T->ws_sy; - B->top_n = T->top_n; - for (int i = 0; i < T->top_n; i++) B->top[i] = T->top[i]; - B->group_n = T->group_n < TB_BP_MAX_GROUPS ? T->group_n : TB_BP_MAX_GROUPS; - for (int g = 0; g < B->group_n; g++) { - const WsGroup* G = &T->groups[g]; - B->groups[g] = (TbBpGroup){ G->x, G->y, G->w, G->h, G->color, "" }; - snprintf(B->groups[g].title, sizeof(B->groups[g].title), "%s", G->title); - } - for (int i = 0; i < MAX_WS; i++) { - EdBlock* b = &T->ws[i]; - if (!b->used) continue; - TbBpBlock* o = &B->blocks[i]; - o->used = true; - snprintf(o->type, sizeof(o->type), "%s", b->type_name); - o->x = b->x; o->y = b->y; - o->parent = b->parent; o->prel = b->prel; o->next = b->next; - for (int k = 0; k < MAX_MOUTHS; k++) o->sub[k] = b->sub[k]; - for (int s = 0; s < MAX_INPUTS; s++) { - o->args[s] = b->args[s]; - snprintf(o->in_text[s], sizeof(o->in_text[s]), "%s", b->in_text[s]); - } - snprintf(o->lit, sizeof(o->lit), "%s", b->lit_text); - } + tab_to_bp(&ed->tabs[ti], &bp->tabs[idx]); } for (int u = 0; u < ed->user_block_n && bp->user_block_n < TB_BP_MAX_UBLOCKS; u++) { @@ -2936,7 +2939,7 @@ static bool has_ext(const char* path, const char* ext) { return n > e && !strcasecmp(path + n - e, ext); } -static bool project_load(Ed* ed, const char* path) { +bool project_load(Ed* ed, const char* path) { if (has_ext(path, ".txt") || has_ext(path, ".sb") || has_ext(path, ".scratchblocks")) return sb_import_file(ed, path); /* notacao de texto do forum do Scratch */ char err[160] = ""; @@ -2953,7 +2956,7 @@ static bool project_load(Ed* ed, const char* path) { return true; } -static bool project_save(Ed* ed, const char* path) { +bool project_save(Ed* ed, const char* path) { TbBlueprint* bp = ed_to_blueprint(ed); bool ok = bp && tb_blueprint_save_file(bp, path, TB_BP_FMT_JSON, true); tb_blueprint_free(bp); @@ -2978,7 +2981,7 @@ static bool project_export(Ed* ed, const char* path, int fmt) { * Notacao de texto do forum do Scratch ("scratchblocks"): exportar a aba * atual / importar como aba nova (library tinyblocks-scratchblocks) * === */ -static void cleanup_ws(Ed* ed); +void cleanup_ws(Ed* ed); static int sb_shape(const char* type, void* ud) { Ed* ed = (Ed*)ud; @@ -3024,28 +3027,108 @@ static const char* sb_category(const char* type, void* ud) { /* Contexto: rotulos em portugues do editor + callbacks */ static TbSbContext sb_context(Ed* ed, TbSbLabel** labels_out) { size_t n = sizeof(s_specs) / sizeof(s_specs[0]); - TbSbLabel* L = calloc(n, sizeof(TbSbLabel)); + uint32_t nt = tb_rt_type_count(ed->rt); + TbSbLabel* L = calloc(n + nt, sizeof(TbSbLabel)); int k = 0; for (size_t i = 0; L && i < n; i++) { L[k].type = s_specs[i].type; L[k].label = s_specs[i].label; k++; } + for (uint32_t i = 0; L && i < nt; i++) { /* rotulos declarados pelas libraries */ + const TinyBlocks_TypeBlock* t = tb_rt_type_at(ed->rt, i); + if (!t || !t->label || spec_of(t->type_name)) continue; + L[k].type = t->type_name; + L[k].label = t->label; + k++; + } *labels_out = L; TbSbContext cx = { L, L ? k : 0, sb_shape, sb_slot_kind, sb_category, ed }; return cx; } +/* Pilha `head` da aba T (ou a aba inteira, head < 0) em scratchblocks. malloc */ +char* ed_scratchblocks_export(Ed* ed, const Tab* T, int head) { + TbBpTab* B = calloc(1, sizeof(TbBpTab)); + if (!B) return NULL; + tab_to_bp(T, B); + if (head >= 0) { B->top_n = 1; B->top[0] = head; } + TbSbLabel* labels = NULL; + TbSbContext cx = sb_context(ed, &labels); + char* txt = tb_scratchblocks_export(B, &cx); + free(labels); + free(B); + return txt; +} + +/* Texto em scratchblocks -> pilhas novas na aba T: a primeira com o canto em + * (x, y), as outras logo abaixo. Devolve quantas criou (-1 = nada / aba cheia) + * e as cabecas em heads (ate max). */ +int ed_scratchblocks_import(Ed* ed, Tab* T, const char* text, float x, float y, + int* heads, int max, char* warn, size_t warn_cap) { + TbBpTab* B = calloc(1, sizeof(TbBpTab)); + if (!B) return -1; + TbSbLabel* labels = NULL; + TbSbContext cx = sb_context(ed, &labels); + int n = tb_scratchblocks_import(text, B, &cx, warn, warn_cap); + free(labels); + if (n <= 0) { free(B); return -1; } + int map[TB_BP_MAX_WS]; + for (int i = 0; i < TB_BP_MAX_WS; i++) { + map[i] = -1; + if (!B->blocks[i].used) continue; + map[i] = blk_alloc(T); + if (map[i] < 0) { /* aba cheia: desfaz */ + for (int j = 0; j < i; j++) if (map[j] >= 0) T->ws[map[j]].used = false; + if (warn && warn_cap) snprintf(warn, warn_cap, "a aba esta cheia (%d blocos)", MAX_WS); + free(B); + return -1; + } + } +#define MAP(i) ((i) >= 0 && (i) < TB_BP_MAX_WS ? map[i] : -1) + for (int i = 0; i < TB_BP_MAX_WS; i++) { + const TbBpBlock* o = &B->blocks[i]; + if (!o->used) continue; + EdBlock* b = &T->ws[map[i]]; + snprintf(b->type_name, sizeof(b->type_name), "%s", o->type); + b->type = tb_type_block_find(ed->rt, b->type_name); + b->parent = MAP(o->parent); b->prel = o->parent >= 0 ? o->prel : REL_NONE; + b->next = MAP(o->next); + for (int k = 0; k < MAX_MOUTHS; k++) b->sub[k] = MAP(o->sub[k]); + for (int s2 = 0; s2 < MAX_INPUTS; s2++) { + b->args[s2] = MAP(o->args[s2]); + snprintf(b->in_text[s2], sizeof(b->in_text[s2]), "%s", o->in_text[s2]); + } + snprintf(b->lit_text, sizeof(b->lit_text), "%s", o->lit); + } +#undef MAP + int made = 0; + for (int t = 0; t < B->top_n; t++) { + int h = B->top[t] >= 0 && B->top[t] < TB_BP_MAX_WS ? map[B->top[t]] : -1; + if (h < 0) continue; + T->ws[h].x = x; T->ws[h].y = y; + top_add(T, h); + if (made < max && heads) heads[made] = h; + made++; + } + free(B); + layout_tab(T); /* empilha uma embaixo da outra */ + for (int k = 1; k < made && k < max && heads; k++) { + float x0, y0, x1, y1; + stack_bounds(T, heads[k - 1], &x0, &y0, &x1, &y1); + T->ws[heads[k]].y = y1 + 24.f; + layout_tab(T); + } + return made; +} + static void sb_export_file(Ed* ed, const char* path) { if (!tab_class(&CT)->blocks) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Só abas de blocos viram scratchblocks"); ed->hot_status_ok = false; return; } - TbBlueprint* bp = ed_to_blueprint(ed); - TbSbLabel* labels = NULL; - TbSbContext cx = sb_context(ed, &labels); - char* txt = bp ? tb_scratchblocks_export(&bp->tabs[ed->cur_tab], &cx) : NULL; + char* txt = ed_scratchblocks_export(ed, &CT, -1); FILE* f = txt ? fopen(path, "wb") : NULL; bool ok = f && fputs(txt, f) >= 0; if (f) fclose(f); @@ -3053,8 +3136,6 @@ static void sb_export_file(Ed* ed, const char* path) { : "Falha ao exportar: %.200s", path); ed->hot_status_ok = ok; free(txt); - free(labels); - tb_blueprint_free(bp); } static bool sb_import_text(Ed* ed, const char* text, const char* name); @@ -3134,12 +3215,7 @@ static void sbp_open(Ed* ed) { ed->hot_status_ok = false; return; } - TbBlueprint* bp = ed_to_blueprint(ed); - TbSbLabel* labels = NULL; - TbSbContext cx = sb_context(ed, &labels); - char* txt = bp ? tb_scratchblocks_export(&bp->tabs[ed->cur_tab], &cx) : NULL; - free(labels); - tb_blueprint_free(bp); + char* txt = ed_scratchblocks_export(ed, &CT, -1); if (!txt) return; free(ed->sbp_text); ed->sbp_text = txt; @@ -4759,7 +4835,7 @@ static void groups_render(Ed* ed, TinyBlocks_RenderableBlock* rb, float ox, floa } /* Limites de uma pilha (todos os blocos dela, ja com layout) */ -static void stack_bounds(Tab* T, int root, float* x0, float* y0, float* x1, float* y1) { +void stack_bounds(Tab* T, int root, float* x0, float* y0, float* x1, float* y1) { *x0 = *y0 = 1e9f; *x1 = *y1 = -1e9f; for (int i = 0; i < MAX_WS; i++) { EdBlock* b = &T->ws[i]; @@ -5819,7 +5895,7 @@ static void apply_snap(Ed* ed) { } } -static void cleanup_ws(Ed* ed) { +void cleanup_ws(Ed* ed) { Tab* T = &CT; layout_tab(T); float y = 24 + T->ws_sy; @@ -6993,6 +7069,9 @@ static bool ax_perform(void* user, const TinyBlocks_A11yTree* t, int node, const } } +void ed_type_text(Ed* ed, const char* text) { on_text(ed, text); } +void ed_press_key(Ed* ed, int scancode) { on_key(ed, scancode, false); } + static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) { g_active_ed = ed; if (from < 0) { @@ -7102,6 +7181,7 @@ static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) { if (from >= 0) return; /* o resto e uma vez por quadro (principal) */ input_feed(ed, evb); /* Sensores: mouse/teclado/toque/sensores do palco */ + ed_mcp_poll(ed); /* pedidos de agentes (servidor MCP), na thread do editor */ vm_frame(ed); /* scripts rodando (sempre / repita) avancam um quadro */ /* Hot reload: checa os .so a cada ~30 frames (~0,5 s). @@ -7370,6 +7450,7 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { tb_a11y_set_bridge(ed->ax_tree, &b); } } + ed_mcp_start(ed); ed->capture_view = -2; ed->tab_press = -1; ed->tabctx = -1; @@ -7448,6 +7529,7 @@ static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { for (int u = 0; u < ed->user_block_n; u++) free(ed->user_blocks[u].snap); tb_libman_shutdown(); tb_a11y_tree_free(ed->ax_tree); + ed_mcp_stop(ed); if (g_active_ed == ed) g_active_ed = NULL; free(ed); *(Ed**)self->userdata = NULL; diff --git a/libraries/tinyblocks-editor/src/tb_editor_mcp.c b/libraries/tinyblocks-editor/src/tb_editor_mcp.c new file mode 100644 index 0000000..12bb6f0 --- /dev/null +++ b/libraries/tinyblocks-editor/src/tb_editor_mcp.c @@ -0,0 +1,929 @@ +/* + * TinyBlocks - tb_editor_mcp.c + * O editor como servidor MCP: ferramentas para um agente ler e editar as + * pilhas de blocos (em scratchblocks ou bloco a bloco), rodar o programa, + * ler a saida e usar a interface pela arvore acessivel. + * + * Ids: um bloco e o indice dele no pool da aba; uma pilha e o id do bloco de + * cima. Posicoes (x, y) sao as da area de scripts, como no projeto salvo. + * As ferramentas rodam na thread do editor (ed_mcp_poll, a cada quadro). + */ +#include +#include +#include +#include + +#define MCP_PORT_DEFAULT 7811 +#define MCP_PORT_TRIES 10 + +/* -- JSON ----------------------------------------------------------------- */ +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); +} + +/* -- Argumentos comuns ------------------------------------------------------ */ +/* Aba: "tab" pelo nome ou pelo numero; sem "tab" = a aba atual */ +static int arg_tab(Ed* ed, TbMcpRequest* rq) { + const TinyBlocks_JsonValue* v = tb_mcp_req_arg(rq, "tab"); + if (!v || tb_json_kind(v) == TB_JSON_NULL) return ed->cur_tab; + if (tb_json_kind(v) == TB_JSON_NUMBER) { + int i = (int)tb_json_as_number(v, -1); + if (i >= 0 && i < ed->tab_n) return i; + tb_mcp_req_error(rq, "Aba %d nao existe (ha %d abas; veja get_editor)", i, ed->tab_n); + return -1; + } + const char* name = tb_json_as_string(v); + for (int i = 0; name && i < ed->tab_n; i++) if (!strcmp(ed->tabs[i].name, name)) return i; + tb_mcp_req_error(rq, "Aba \"%s\" nao existe (veja get_editor)", name ? name : "?"); + return -1; +} + +/* Aba de blocos (abas de codigo e imagem nao tem pilhas) */ +static Tab* arg_block_tab(Ed* ed, TbMcpRequest* rq, int* idx) { + int t = arg_tab(ed, rq); + if (t < 0) return NULL; + if (!tab_class(&ed->tabs[t])->blocks) { + tb_mcp_req_error(rq, "A aba \"%s\" nao e de blocos", ed->tabs[t].name); + return NULL; + } + if (idx) *idx = t; + return &ed->tabs[t]; +} + +static bool block_ok(Tab* T, int bi) { return bi >= 0 && bi < MAX_WS && T->ws[bi].used; } + +static int arg_block(TbMcpRequest* rq, Tab* T, const char* key) { + if (!tb_mcp_req_has(rq, key)) { tb_mcp_req_error(rq, "Falta o argumento \"%s\"", key); return -1; } + int bi = (int)tb_mcp_req_num(rq, key, -1); + if (!block_ok(T, bi)) { + tb_mcp_req_error(rq, "Bloco %d nao existe na aba \"%s\" (veja list_stacks)", bi, T->name); + return -1; + } + return bi; +} + +/* Campo de entrada pelo nome ("vezes") ou pelo numero (0, 1...) */ +static int input_index(const TinyBlocks_TypeBlock* t, const TinyBlocks_JsonValue* v) { + if (!t || !v) return -1; + int n = input_count(t); + if (tb_json_kind(v) == TB_JSON_NUMBER) { + int i = (int)tb_json_as_number(v, -1); + return i >= 0 && i < n ? i : -1; + } + const char* name = tb_json_as_string(v); + for (int i = 0; name && i < n; i++) + if (t->input_descs[i].name && !strcmp(t->input_descs[i].name, name)) return i; + if (name) { /* "2" tambem vale */ + char* end = NULL; + long i = strtol(name, &end, 10); + if (end && !*end && end != name && i >= 0 && i < n) return (int)i; + } + return -1; +} + +static const char* input_names(const TinyBlocks_TypeBlock* t, char* buf, size_t cap) { + size_t len = 0; + buf[0] = 0; + for (int i = 0; t && i < input_count(t); i++) { + int w = snprintf(buf + len, cap - len, "%s%d=%s", i ? ", " : "", i, + t->input_descs[i].name ? t->input_descs[i].name : "?"); + if (w < 0 || (size_t)w >= cap - len) break; + len += (size_t)w; + } + return buf[0] ? buf : "(nenhum)"; +} + +/* bi esta dentro da arvore de root (ele mesmo, encaixado ou abaixo)? */ +static bool in_tree(Tab* T, int root, int bi) { + for (int c = bi; c >= 0; c = T->ws[c].parent) if (c == root) return true; + return false; +} + +/* -- Descricao dos blocos ---------------------------------------------------- */ +static const char* shape_name(const TinyBlocks_TypeBlock* t) { + if (!t) return "desconhecido"; + if (is_cap(t)) return "c_tampa"; + switch (shape_of(t)) { + case SH_HAT: return "chapeu"; + case SH_C1: case SH_C2: case SH_C3: return "c"; + case SH_REPORTER: return "reporter"; + case SH_BOOL: return "booleano"; + default: return "comando"; + } +} + +static const char* rel_name(Tab* T, const EdBlock* b, char* buf, size_t cap) { + if (b->parent < 0) return "topo"; + if (b->prel == REL_NEXT) return "abaixo"; + if (b->prel >= REL_SUB0 && b->prel < REL_ARG0) { + snprintf(buf, cap, "boca %d", b->prel - REL_SUB0); + return buf; + } + const TinyBlocks_TypeBlock* pt = T->ws[b->parent].type; + int s = b->prel - REL_ARG0; + snprintf(buf, cap, "campo %s", pt && s < input_count(pt) && pt->input_descs[s].name ? pt->input_descs[s].name : "?"); + return buf; +} + +static void describe_tree(Tab* T, int bi, int depth, TinyBlocks_JsonValue* list, char** text, size_t* len, size_t* cap); + +static void text_add(char** text, size_t* len, size_t* cap, const char* fmt, ...) __attribute__((format(printf, 4, 5))); +static void text_add(char** text, size_t* len, size_t* cap, const char* fmt, ...) { + va_list ap; + va_start(ap, fmt); + char tmp[512]; + int n = vsnprintf(tmp, sizeof(tmp), fmt, ap); + va_end(ap); + if (n < 0) return; + if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1; + if (*len + (size_t)n + 1 > *cap) { + size_t c = *cap ? *cap * 2 : 1024; + while (c < *len + (size_t)n + 1) c *= 2; + char* t = realloc(*text, c); + if (!t) return; + *text = t; + *cap = c; + } + memcpy(*text + *len, tmp, (size_t)n + 1); + *len += (size_t)n; +} + +/* Um bloco e o que esta nele (reporteres e bocas) e abaixo dele */ +static void describe_tree(Tab* T, int bi, int depth, TinyBlocks_JsonValue* list, char** text, size_t* len, size_t* cap) { + for (int c = bi; c >= 0; c = T->ws[c].next) { + EdBlock* b = &T->ws[c]; + char label[TB_A11Y_NAME_MAX], rbuf[64]; + ax_block_label(T, c, label, sizeof(label), 0); + const char* rel = rel_name(T, b, rbuf, sizeof(rbuf)); + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "id", tb_json_number(c)); + jset(o, "type", tb_json_string(b->type_name)); + jset(o, "label", tb_json_string(label)); + jset(o, "shape", tb_json_string(shape_name(b->type))); + jset(o, "parent", tb_json_number(b->parent)); + jset(o, "relation", tb_json_string(rel)); + TinyBlocks_JsonValue* ins = tb_json_object(); + for (int s = 0; b->type && s < input_count(b->type); s++) { + const char* nm = b->type->input_descs[s].name ? b->type->input_descs[s].name : "?"; + if (b->args[s] >= 0) jset(ins, nm, tb_json_number(b->args[s])); /* id do reporter */ + else jset(ins, nm, tb_json_string(slot_src(b, s))); + } + jset(o, "inputs", ins); + jpush(list, o); + text_add(text, len, cap, "%*s[%d] %s (%s, %s)\n", depth * 2, "", c, label, b->type_name, rel); + for (int s = 0; s < MAX_INPUTS; s++) + if (b->args[s] >= 0) describe_tree(T, b->args[s], depth + 1, list, text, len, cap); + Shape sh = shape_of(b->type); + for (int k = 0; k < shape_mouths(sh); k++) + if (b->sub[k] >= 0) describe_tree(T, b->sub[k], depth + 1, list, text, len, cap); + if (shape_is_value(sh)) break; /* reporter nao tem "abaixo" */ + } +} + +static TinyBlocks_JsonValue* stack_json(Ed* ed, Tab* T, int head, char** text, size_t* len, size_t* cap) { + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "id", tb_json_number(head)); + jset(o, "x", tb_json_number(T->ws[head].x)); + jset(o, "y", tb_json_number(T->ws[head].y)); + char* sb = ed_scratchblocks_export(ed, T, head); + jset(o, "scratchblocks", tb_json_string(sb ? sb : "")); + TinyBlocks_JsonValue* blocks = tb_json_array(); + text_add(text, len, cap, "== pilha %d em (%.0f, %.0f)\n%s\n", head, T->ws[head].x, T->ws[head].y, sb ? sb : ""); + free(sb); + describe_tree(T, head, 0, blocks, text, len, cap); + jset(o, "blocks", blocks); + text_add(text, len, cap, "\n"); + return o; +} + +/* Pilhas de cima para baixo (como o scratchblocks e a bandeira as veem) */ +static int stacks_sorted(Tab* T, int* out) { + int n = 0; + for (int i = 0; i < T->top_n; i++) { + int bi = T->top[i], k = n++; + while (k > 0 && T->ws[out[k - 1]].y > T->ws[bi].y) { out[k] = out[k - 1]; k--; } + out[k] = bi; + } + return n; +} + +/* Um lugar livre: embaixo de tudo o que ja esta na aba */ +static void free_spot(Tab* T, float* x, float* y) { + float bottom = 40.f; + for (int i = 0; i < T->top_n; i++) { + float x0, y0, x1, y1; + stack_bounds(T, T->top[i], &x0, &y0, &x1, &y1); + if (y1 + 40.f > bottom) bottom = y1 + 40.f; + } + *x = 40.f; + *y = bottom; +} + +static void changed(Ed* ed, Tab* T) { + layout_tab(T); + (void)ed; +} + +/* == Ferramentas =============================================================== */ + +static void t_get_editor(void* user, TbMcpRequest* rq) { + Ed* ed = user; + TinyBlocks_JsonValue* o = tb_json_object(); + TinyBlocks_JsonValue* tabs = tb_json_array(); + tb_mcp_req_text(rq, "Abas:\n"); + for (int i = 0; i < ed->tab_n; i++) { + Tab* T = &ed->tabs[i]; + TinyBlocks_JsonValue* t = tb_json_object(); + jset(t, "index", tb_json_number(i)); + jset(t, "name", tb_json_string(T->name)); + jset(t, "kind", tb_json_string(tab_class(T)->name)); + jset(t, "stacks", tb_json_number(tab_class(T)->blocks ? T->top_n : 0)); + jset(t, "current", tb_json_bool(i == ed->cur_tab)); + jpush(tabs, t); + tb_mcp_req_text(rq, " %d. %s (%s%s)%s\n", i, T->name, tab_class(T)->name, + tab_class(T)->blocks ? "" : ", sem pilhas", i == ed->cur_tab ? " <- atual" : ""); + } + jset(o, "tabs", tabs); + jset(o, "current_tab", tb_json_number(ed->cur_tab)); + TinyBlocks_JsonValue* cats = tb_json_array(); + tb_mcp_req_text(rq, "Categorias:"); + for (int c = 0; c < ed->cat_n; c++) { + jpush(cats, tb_json_string(ed->cats[c].name)); + tb_mcp_req_text(rq, "%s %s", c ? "," : "", ed->cats[c].name); + } + jset(o, "categories", cats); + jset(o, "running", tb_json_bool(ed->vm_running)); + tb_mcp_req_text(rq, "\nRodando: %s\n", ed->vm_running ? "sim" : "nao"); + tb_mcp_req_structured(rq, o); +} + +static void t_list_block_types(void* user, TbMcpRequest* rq) { + Ed* ed = user; + const char* want_cat = tb_mcp_req_str(rq, "category", NULL); + const char* query = tb_mcp_req_str(rq, "query", NULL); + TinyBlocks_JsonValue* arr = tb_json_array(); + int shown = 0; + uint32_t n = tb_rt_type_count(ed->rt); + for (uint32_t i = 0; i < n; i++) { + const TinyBlocks_TypeBlock* t = tb_rt_type_at(ed->rt, i); + if (!t || !t->type_name || (t->flags & TB_TYPE_HIDDEN)) continue; + int c = cat_of(ed, t->type_name); + if (c < 0) continue; /* fora da paleta */ + const char* cat = ed->cats[c].name; + if (want_cat && strcmp(want_cat, cat)) continue; + const BlockSpec* sp = spec_of_type(t); + const char* label = sp && sp->label ? sp->label : t->type_name; + if (query && !strstr(t->type_name, query) && !strstr(label, query)) continue; + const TinyBlocks_BlockMeta* meta = tb_meta_find(t->type_name); + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "type", tb_json_string(t->type_name)); + jset(o, "label", tb_json_string(label)); + jset(o, "category", tb_json_string(cat)); + jset(o, "shape", tb_json_string(shape_name(t))); + TinyBlocks_JsonValue* ins = tb_json_array(); + for (int s = 0; s < input_count(t); s++) { + TinyBlocks_JsonValue* in = tb_json_object(); + jset(in, "name", tb_json_string(t->input_descs[s].name ? t->input_descs[s].name : "")); + TinyBlocks_ValueKind k = t->input_descs[s].expected_kind; + jset(in, "kind", tb_json_string(slot_is_bool(t, s) ? "booleano" : + (k == TB_VALUE_INTEGER || k == TB_VALUE_REAL) ? "numero" : "texto")); + jpush(ins, in); + } + jset(o, "inputs", ins); + if (meta && meta->doc) jset(o, "description", tb_json_string(meta->doc)); + jpush(arr, o); + char names[256]; + tb_mcp_req_text(rq, "%s | %s | %s | %s | campos: %s%s%s\n", cat, t->type_name, label, shape_name(t), + input_names(t, names, sizeof(names)), meta && meta->doc ? " | " : "", + meta && meta->doc ? meta->doc : ""); + shown++; + } + if (!shown) tb_mcp_req_text(rq, "Nenhum tipo de bloco com esses filtros (veja as categorias em get_editor)."); + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "types", arr); + tb_mcp_req_structured(rq, o); +} + +static void t_list_stacks(void* user, TbMcpRequest* rq) { + Ed* ed = user; + int ti; + Tab* T = arg_block_tab(ed, rq, &ti); + if (!T) return; + layout_tab(T); + int order[MAX_WS]; + int n = stacks_sorted(T, order); + char* text = NULL; + size_t len = 0, cap = 0; + text_add(&text, &len, &cap, "Aba %d \"%s\": %d pilha(s)\n\n", ti, T->name, n); + TinyBlocks_JsonValue* arr = tb_json_array(); + for (int i = 0; i < n; i++) jpush(arr, stack_json(ed, T, order[i], &text, &len, &cap)); + tb_mcp_req_text(rq, "%s", text ? text : ""); + free(text); + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "tab", tb_json_number(ti)); + jset(o, "stacks", arr); + tb_mcp_req_structured(rq, o); +} + +static void t_get_scratchblocks(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int head = -1; + if (tb_mcp_req_has(rq, "stack")) { + head = arg_block(rq, T, "stack"); + if (head < 0) return; + head = stack_root(T, head); + } + char* txt = ed_scratchblocks_export(ed, T, head); + tb_mcp_req_text(rq, "%s", txt && txt[0] ? txt : "(aba vazia)"); + free(txt); +} + +static void report_new_stacks(Ed* ed, TbMcpRequest* rq, Tab* T, const int* heads, int n, const char* warn) { + TinyBlocks_JsonValue* arr = tb_json_array(); + char* text = NULL; + size_t len = 0, cap = 0; + text_add(&text, &len, &cap, "%d pilha(s) na aba \"%s\"%s%s\n\n", n, T->name, + warn && warn[0] ? ". Aviso: " : "", warn && warn[0] ? warn : ""); + for (int i = 0; i < n; i++) jpush(arr, stack_json(ed, T, heads[i], &text, &len, &cap)); + tb_mcp_req_text(rq, "%s", text ? text : ""); + free(text); + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "stacks", arr); + if (warn && warn[0]) jset(o, "warning", tb_json_string(warn)); + tb_mcp_req_structured(rq, o); +} + +static void t_add_scratchblocks(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + const char* code = tb_mcp_req_str(rq, "code", NULL); + if (!code || !code[0]) { tb_mcp_req_error(rq, "Falta o argumento \"code\" (texto em scratchblocks)"); return; } + float x, y; + free_spot(T, &x, &y); + x = (float)tb_mcp_req_num(rq, "x", x); + y = (float)tb_mcp_req_num(rq, "y", y); + int heads[64]; + char warn[200] = ""; + int n = ed_scratchblocks_import(ed, T, code, x, y, heads, 64, warn, sizeof(warn)); + if (n <= 0) { + tb_mcp_req_error(rq, "Nenhuma pilha reconhecida%s%s. Use a notacao do forum do Scratch, com os " + "rotulos de list_block_types (ex.: \"quando a bandeira for clicado\" / \"diga [oi]\").", + warn[0] ? ": " : "", warn); + return; + } + changed(ed, T); + report_new_stacks(ed, rq, T, heads, n < 64 ? n : 64, warn); +} + +static void t_replace_stack(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int head = arg_block(rq, T, "stack"); + if (head < 0) return; + head = stack_root(T, head); + const char* code = tb_mcp_req_str(rq, "code", NULL); + if (!code || !code[0]) { tb_mcp_req_error(rq, "Falta o argumento \"code\" (texto em scratchblocks)"); return; } + float x = T->ws[head].x, y = T->ws[head].y; + /* importa primeiro: se o codigo nao serve, a pilha antiga fica */ + int heads[64]; + char warn[200] = ""; + int n = ed_scratchblocks_import(ed, T, code, x, y, heads, 64, warn, sizeof(warn)); + if (n <= 0) { + tb_mcp_req_error(rq, "O codigo novo nao virou nenhuma pilha%s%s; a pilha %d ficou como estava", + warn[0] ? ": " : "", warn, head); + return; + } + free_tree(ed, T, head); + changed(ed, T); + report_new_stacks(ed, rq, T, heads, n < 64 ? n : 64, warn); +} + +static void t_delete_stack(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int head = arg_block(rq, T, "stack"); + if (head < 0) return; + head = stack_root(T, head); + char label[TB_A11Y_NAME_MAX]; + ax_block_label(T, head, label, sizeof(label), 0); + free_tree(ed, T, head); + changed(ed, T); + tb_mcp_req_text(rq, "Pilha %d (\"%s\") apagada", head, label); +} + +static void t_move_stack(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int head = arg_block(rq, T, "stack"); + if (head < 0) return; + head = stack_root(T, head); + if (!tb_mcp_req_has(rq, "x") || !tb_mcp_req_has(rq, "y")) { tb_mcp_req_error(rq, "Faltam x e y"); return; } + T->ws[head].x = (float)tb_mcp_req_num(rq, "x", 0); + T->ws[head].y = (float)tb_mcp_req_num(rq, "y", 0); + top_add(T, head); + changed(ed, T); + tb_mcp_req_text(rq, "Pilha %d em (%.0f, %.0f)", head, T->ws[head].x, T->ws[head].y); +} + +/* Coloca a pilha solta bi (ja de topo) conforme os argumentos: + * below=id embaixo do bloco id (o que estava embaixo vai depois) + * into=id, input=n no campo n do bloco id (bi precisa ser reporter) + * into=id, mouth=k no comeco da boca k do bloco C id + * x, y solta na area (padrao: um lugar livre) */ +static bool place(TbMcpRequest* rq, Tab* T, int bi) { + Shape sh = shape_of(T->ws[bi].type); + if (tb_mcp_req_has(rq, "below")) { + int at = arg_block(rq, T, "below"); + if (at < 0) return false; + if (in_tree(T, bi, at)) { tb_mcp_req_error(rq, "Nao da para encaixar um bloco nele mesmo"); return false; } + Shape ts = shape_of(T->ws[at].type); + if (shape_is_value(sh) || shape_is_value(ts)) { + tb_mcp_req_error(rq, "Reporteres nao empilham; use into + input"); return false; + } + if (is_cap(T->ws[at].type)) { tb_mcp_req_error(rq, "Nada encaixa embaixo do bloco %d", at); return false; } + if (sh == SH_HAT) { tb_mcp_req_error(rq, "Chapeus so ficam no topo de uma pilha"); return false; } + attach_insert(T, at, REL_NEXT, bi); + return true; + } + if (tb_mcp_req_has(rq, "into")) { + int at = arg_block(rq, T, "into"); + if (at < 0) return false; + if (in_tree(T, bi, at)) { tb_mcp_req_error(rq, "Nao da para encaixar um bloco nele mesmo"); return false; } + const TinyBlocks_TypeBlock* tt = T->ws[at].type; + if (tb_mcp_req_has(rq, "mouth")) { + int k = (int)tb_mcp_req_num(rq, "mouth", 0); + if (k < 0 || k >= shape_mouths(shape_of(tt))) { + tb_mcp_req_error(rq, "O bloco %d tem %d boca(s)", at, shape_mouths(shape_of(tt))); + return false; + } + if (shape_is_value(sh) || sh == SH_HAT) { tb_mcp_req_error(rq, "Na boca so entram comandos"); return false; } + attach_insert(T, at, REL_SUB0 + k, bi); + return true; + } + int s = input_index(tt, tb_mcp_req_arg(rq, "input")); + if (s < 0) { + char names[256]; + tb_mcp_req_error(rq, "Campo invalido para o bloco %d; campos: %s (ou use mouth para blocos C)", + at, input_names(tt, names, sizeof(names))); + return false; + } + if (!shape_is_value(sh)) { tb_mcp_req_error(rq, "So reporteres e booleanos entram em campos"); return false; } + if (slot_is_bool(tt, s) != (sh == SH_BOOL)) { + tb_mcp_req_error(rq, slot_is_bool(tt, s) ? "Esse campo e booleano: so blocos <...> entram" + : "Esse campo nao aceita booleanos"); + return false; + } + attach_arg(T, at, s, bi); + return true; + } + float x, y; + free_spot(T, &x, &y); + T->ws[bi].x = (float)tb_mcp_req_num(rq, "x", x); + T->ws[bi].y = (float)tb_mcp_req_num(rq, "y", y); + top_add(T, bi); + return true; +} + +/* inputs = {"campo": valor} ou [valor, valor...] */ +static bool set_inputs(TbMcpRequest* rq, Tab* T, int bi) { + const TinyBlocks_JsonValue* ins = tb_mcp_req_arg(rq, "inputs"); + if (!ins || tb_json_kind(ins) == TB_JSON_NULL) return true; + EdBlock* b = &T->ws[bi]; + bool arr = tb_json_kind(ins) == TB_JSON_ARRAY; + uint32_t n = arr ? tb_json_array_length(ins) : tb_json_object_length(ins); + for (uint32_t i = 0; i < n; i++) { + TinyBlocks_JsonValue* key = arr ? tb_json_number(i) : tb_json_string(tb_json_object_key_at(ins, i)); + TinyBlocks_JsonValue* val = arr ? tb_json_array_get(ins, i) : tb_json_object_get(ins, tb_json_object_key_at(ins, i)); + int s = input_index(b->type, key); + bool ok = s >= 0 && b->args[s] < 0; + if (ok) { + char buf[64]; + if (tb_json_kind(val) == TB_JSON_STRING) snprintf(buf, sizeof(buf), "%s", tb_json_as_string(val)); + else { + char* js = tb_json_stringify(val); + snprintf(buf, sizeof(buf), "%s", js ? js : ""); + free(js); + } + snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", buf); + } else { + char names[256]; + if (s >= 0) tb_mcp_req_error(rq, "O campo %d do bloco %d tem um reporter encaixado (bloco %d); " + "mova ou apague o reporter antes", s, bi, b->args[s]); + else tb_mcp_req_error(rq, "Campo desconhecido para %s; campos: %s", b->type_name, + input_names(b->type, names, sizeof(names))); + } + tb_json_release(key); + tb_json_release(val); + if (!ok) return false; + } + return true; +} + +static void report_block(Ed* ed, TbMcpRequest* rq, Tab* T, int bi, const char* what) { + layout_tab(T); + int root = stack_root(T, bi); + char label[TB_A11Y_NAME_MAX]; + ax_block_label(T, bi, label, sizeof(label), 0); + char* sb = ed_scratchblocks_export(ed, T, root); + tb_mcp_req_text(rq, "%s bloco %d \"%s\" na pilha %d:\n%s", what, bi, label, root, sb ? sb : ""); + free(sb); + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "block", tb_json_number(bi)); + jset(o, "stack", tb_json_number(root)); + jset(o, "label", tb_json_string(label)); + tb_mcp_req_structured(rq, o); +} + +static void t_add_block(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + const char* type = tb_mcp_req_str(rq, "type", NULL); + TinyBlocks_TypeBlock* t = type ? tb_type_block_find(ed->rt, type) : NULL; + if (!t) { tb_mcp_req_error(rq, "Tipo de bloco \"%s\" nao existe (veja list_block_types)", type ? type : ""); return; } + int bi = blk_new(T, t); + if (bi < 0) { tb_mcp_req_error(rq, "A aba esta cheia (%d blocos)", MAX_WS); return; } + top_add(T, bi); + if (!set_inputs(rq, T, bi) || !place(rq, T, bi)) { free_tree(ed, T, bi); layout_tab(T); return; } + changed(ed, T); + report_block(ed, rq, T, bi, "Criado o"); +} + +static void t_move_block(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int bi = arg_block(rq, T, "block"); + if (bi < 0) return; + int parent = T->ws[bi].parent, prel = T->ws[bi].prel; + float ox = T->ws[bi].x, oy = T->ws[bi].y; + int below = -1; /* alone: os de baixo ficam (sobem um lugar) */ + if (tb_mcp_req_bool(rq, "alone", false) && !shape_is_value(shape_of(T->ws[bi].type)) && T->ws[bi].next >= 0) { + below = T->ws[bi].next; + blk_link(T, bi, REL_NEXT, -1); + T->ws[below].parent = -1; + T->ws[below].prel = REL_NONE; + if (parent >= 0) blk_link(T, parent, prel, below); /* toma o lugar de bi */ + else { T->ws[below].x = ox; T->ws[below].y = oy; top_add(T, below); } + T->ws[bi].parent = -1; + T->ws[bi].prel = REL_NONE; + top_add(T, bi); + } + detach(T, bi); /* sai com os blocos de baixo, como ao arrastar */ + if (!place(rq, T, bi)) { /* nao deu: volta para onde estava */ + top_remove(T, bi); + if (below >= 0 && parent < 0) top_remove(T, below); + if (parent >= 0 && prel >= REL_ARG0) blk_link(T, parent, prel, bi); + else if (parent >= 0) attach_insert(T, parent, prel, bi); /* o que estava ali vai embaixo */ + else { + T->ws[bi].x = ox; T->ws[bi].y = oy; + top_add(T, bi); + if (below >= 0) blk_link(T, bi, REL_NEXT, below); + } + layout_tab(T); + return; + } + changed(ed, T); + report_block(ed, rq, T, bi, "Movido o"); +} + +static void t_delete_block(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int bi = arg_block(rq, T, "block"); + if (bi < 0) return; + char label[TB_A11Y_NAME_MAX]; + ax_block_label(T, bi, label, sizeof(label), 0); + if (tb_mcp_req_bool(rq, "with_below", false)) { + if (T->ws[bi].parent >= 0) detach(T, bi); + free_tree(ed, T, bi); + } else { + delete_heal(ed, T, bi); + } + changed(ed, T); + tb_mcp_req_text(rq, "Bloco %d (\"%s\") apagado", bi, label); +} + +static void t_set_inputs(void* user, TbMcpRequest* rq) { + Ed* ed = user; + Tab* T = arg_block_tab(ed, rq, NULL); + if (!T) return; + int bi = arg_block(rq, T, "block"); + if (bi < 0) return; + if (!tb_mcp_req_has(rq, "inputs")) { tb_mcp_req_error(rq, "Falta \"inputs\", como {\"vezes\": 10}"); return; } + if (!set_inputs(rq, T, bi)) return; + changed(ed, T); + report_block(ed, rq, T, bi, "Atualizado o"); +} + +static void output_report(Ed* ed, TbMcpRequest* rq) { + TinyBlocks_JsonValue* o = tb_json_object(); + jset(o, "running", tb_json_bool(ed->vm_running)); + jset(o, "console", tb_json_string(ed->stage_buf)); + TinyBlocks_JsonValue* vars = tb_json_object(); + tb_mcp_req_text(rq, "Rodando: %s\nSaida:\n%s\n", ed->vm_running ? "sim" : "nao", + ed->stage_buf[0] ? ed->stage_buf : "(vazia)"); + if (tb_variables_count() > 0) tb_mcp_req_text(rq, "Variaveis:\n"); + for (int v = 0; v < tb_variables_count(); v++) { + const TinyBlocks_Value* vv = tb_variables_value(v); + char val[128] = ""; + if (vv) tb_value_to_text(*vv, val, sizeof(val)); + jset(vars, tb_variables_name(v), tb_json_string(val)); + tb_mcp_req_text(rq, " %s = %s\n", tb_variables_name(v), val); + } + jset(o, "variables", vars); + tb_mcp_req_structured(rq, o); +} + +static void t_run(void* user, TbMcpRequest* rq) { + Ed* ed = user; + int ti; + Tab* T = arg_block_tab(ed, rq, &ti); + if (!T) return; + if (ti != ed->cur_tab) tab_select(ed, ti); + if (tb_mcp_req_has(rq, "stack")) { + int bi = arg_block(rq, T, "stack"); + if (bi < 0) return; + run_click(ed, bi); + } else { + run_flag(ed); + } + tb_mcp_req_text(rq, "Iniciado. Os scripts rodam a cada quadro do editor: chame get_output para ver a saida " + "(e stop para parar um \"sempre\").\n"); + output_report(ed, rq); +} + +static void t_stop(void* user, TbMcpRequest* rq) { + Ed* ed = user; + vm_stop(ed); + tb_mcp_req_text(rq, "Parado.\n"); + output_report(ed, rq); +} + +static void t_get_output(void* user, TbMcpRequest* rq) { output_report(user, rq); } + +static void t_new_tab(void* user, TbMcpRequest* rq) { + Ed* ed = user; + const char* name = tb_mcp_req_str(rq, "name", ""); + if (!tab_new_kind(ed, name, false, TK_BLOCKS)) { tb_mcp_req_error(rq, "%s", ed->hot_status); return; } + tb_mcp_req_text(rq, "Aba %d \"%s\" criada e selecionada", ed->cur_tab, CT.name); +} + +static void t_select_tab(void* user, TbMcpRequest* rq) { + Ed* ed = user; + if (!tb_mcp_req_has(rq, "tab")) { tb_mcp_req_error(rq, "Falta \"tab\" (nome ou numero)"); return; } + int t = arg_tab(ed, rq); + if (t < 0) return; + tab_select(ed, t); + tb_mcp_req_text(rq, "Aba %d \"%s\" selecionada", t, CT.name); +} + +static void t_save_project(void* user, TbMcpRequest* rq) { + Ed* ed = user; + const char* path = tb_mcp_req_str(rq, "path", NULL); + if (!path || !path[0]) { tb_mcp_req_error(rq, "Falta \"path\" (arquivo .json)"); return; } + if (project_save(ed, path)) tb_mcp_req_text(rq, "%s", ed->hot_status); + else tb_mcp_req_error(rq, "%s", ed->hot_status); +} + +static void t_open_project(void* user, TbMcpRequest* rq) { + Ed* ed = user; + const char* path = tb_mcp_req_str(rq, "path", NULL); + if (!path || !path[0]) { tb_mcp_req_error(rq, "Falta \"path\" (arquivo .json)"); return; } + if (project_load(ed, path)) tb_mcp_req_text(rq, "%s", ed->hot_status); + else tb_mcp_req_error(rq, "%s", ed->hot_status); +} + +/* -- Interface pela arvore acessivel ------------------------------------------ */ +static TinyBlocks_A11yRole role_by_name(const char* s) { + for (int r = 1; s && r < TB_A11Y_ROLE_COUNT; r++) + if (!strcmp(tb_a11y_role_name((TinyBlocks_A11yRole)r), s)) return (TinyBlocks_A11yRole)r; + return TB_A11Y_NONE; +} + +static int ui_find(Ed* ed, TbMcpRequest* rq, const char* prefix) { + char k[32]; + snprintf(k, sizeof(k), "%srole", prefix); + const char* role_s = tb_mcp_req_str(rq, k, NULL); + snprintf(k, sizeof(k), "%sname", prefix); + const char* name = tb_mcp_req_str(rq, k, NULL); + snprintf(k, sizeof(k), "%swithin", prefix); + const char* within = tb_mcp_req_str(rq, k, NULL); + TinyBlocks_A11yRole role = role_by_name(role_s); + if (role_s && role == TB_A11Y_NONE) { tb_mcp_req_error(rq, "Papel \"%s\" desconhecido (ex.: botão, aba, bloco)", role_s); return -1; } + int from = 0; + if (within) { + from = tb_a11y_find(ed->ax_tree, 0, TB_A11Y_NONE, within, 0); + if (from < 0) { tb_mcp_req_error(rq, "Nao achei \"%s\" na interface (veja ui_tree)", within); return -1; } + } + int n = tb_a11y_find(ed->ax_tree, from, role, name, 0); + if (n < 0) n = name ? tb_a11y_find_part(ed->ax_tree, from, role, name, 0) : -1; + if (n < 0) tb_mcp_req_error(rq, "Nao achei %s \"%s\" na interface (veja ui_tree)", role_s ? role_s : "componente", + name ? name : ""); + return n; +} + +static void t_ui_tree(void* user, TbMcpRequest* rq) { + Ed* ed = user; + if (!ed->ax_tree || !tb_a11y_count(ed->ax_tree)) { tb_mcp_req_error(rq, "A arvore acessivel esta desligada"); return; } + int from = 0; + const char* within = tb_mcp_req_str(rq, "within", NULL); + if (within && (from = tb_a11y_find(ed->ax_tree, 0, TB_A11Y_NONE, within, 0)) < 0) { + tb_mcp_req_error(rq, "Nao achei \"%s\" na interface", within); + return; + } + char* buf = NULL; + size_t len = 0; + FILE* f = open_memstream(&buf, &len); + if (!f) { tb_mcp_req_error(rq, "sem memoria"); return; } + tb_a11y_dump(ed->ax_tree, from, f); + fclose(f); + tb_mcp_req_text(rq, "%s", buf ? buf : ""); + free(buf); +} + +static void t_ui_action(void* user, TbMcpRequest* rq) { + Ed* ed = user; + int n = ui_find(ed, rq, ""); + if (n < 0) return; + const char* act = tb_mcp_req_str(rq, "action", "activate"); + bool ok; + char d[300]; + tb_a11y_describe(ed->ax_tree, n, d, sizeof(d)); + if (!strcmp(act, "drop")) { + int to = ui_find(ed, rq, "target_"); + if (to < 0) return; + ok = tb_a11y_drop(ed->ax_tree, n, to); + } else { + TinyBlocks_A11yAction a = !strcmp(act, "menu") ? TB_A11Y_ACT_MENU : !strcmp(act, "edit") ? TB_A11Y_ACT_EDIT + : TB_A11Y_ACT_ACTIVATE; + ok = tb_a11y_do_action(ed->ax_tree, n, a); + } + if (ok) tb_mcp_req_text(rq, "Feito: %s em \"%s\". A interface muda no proximo quadro (ui_tree).", act, d); + else tb_mcp_req_error(rq, "\"%s\" nao aceita a acao %s", d, act); +} + +static void t_ui_type(void* user, TbMcpRequest* rq) { + Ed* ed = user; + const char* text = tb_mcp_req_str(rq, "text", ""); + const char* key = tb_mcp_req_str(rq, "key", NULL); + if (text[0]) ed_type_text(ed, text); + if (key) { + static const struct { const char* name; int sc; } keys[] = { + {"enter", TB_KEY_RETURN}, {"escape", TB_KEY_ESCAPE}, {"backspace", TB_KEY_BACKSPACE}, + {"delete", TB_KEY_DELETE}, {"tab", TB_KEY_TAB}, + }; + int sc = 0; + for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) if (!strcmp(keys[i].name, key)) sc = keys[i].sc; + if (!sc) { tb_mcp_req_error(rq, "Tecla \"%s\" desconhecida (enter, escape, backspace, delete, tab)", key); return; } + ed_press_key(ed, sc); + } + tb_mcp_req_text(rq, "Digitado no componente com o foco."); +} + +/* == Tabela ================================================================== */ +#define TAB_ARG "\"tab\":{\"description\":\"Aba (nome ou numero); padrao: a atual\",\"type\":[\"string\",\"integer\"]}" +#define PLACE_ARGS \ + "\"x\":{\"type\":\"number\",\"description\":\"Posicao na area de scripts (padrao: um lugar livre)\"}," \ + "\"y\":{\"type\":\"number\"}," \ + "\"below\":{\"type\":\"integer\",\"description\":\"Encaixa embaixo deste bloco\"}," \ + "\"into\":{\"type\":\"integer\",\"description\":\"Bloco que recebe: num campo (input) ou numa boca (mouth)\"}," \ + "\"input\":{\"type\":[\"string\",\"integer\"],\"description\":\"Campo do bloco into (nome ou numero)\"}," \ + "\"mouth\":{\"type\":\"integer\",\"description\":\"Boca do bloco C into (0 = primeira)\"}" +#define INPUTS_ARG "\"inputs\":{\"type\":[\"object\",\"array\"],\"description\":\"Valores dos campos: {\\\"vezes\\\": 10} ou [10]\"}" + +static const TbMcpTool s_tools[] = { + { "get_editor", "Estado do editor", + "Abas (numero, nome, tipo, qual e a atual), categorias da paleta e se ha scripts rodando.", + "{\"type\":\"object\",\"additionalProperties\":false}", TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, t_get_editor }, + { "list_block_types", "Tipos de bloco", + "Blocos da paleta: tipo, rotulo (o texto usado em scratchblocks), categoria, forma e campos. " + "Filtre por categoria ou por um trecho do nome.", + "{\"type\":\"object\",\"properties\":{\"category\":{\"type\":\"string\"},\"query\":{\"type\":\"string\"}}}", + TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, t_list_block_types }, + { "list_stacks", "Pilhas da aba", + "Cada pilha da aba: id, posicao, o codigo em scratchblocks e a lista dos blocos com id, rotulo, " + "relacao (abaixo, boca k, campo x) e campos. Use os ids nas outras ferramentas.", + "{\"type\":\"object\",\"properties\":{" TAB_ARG "}}", TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, t_list_stacks }, + { "get_scratchblocks", "Pilha em scratchblocks", + "Converte uma pilha (ou a aba inteira, sem stack) para a notacao do forum do Scratch.", + "{\"type\":\"object\",\"properties\":{" TAB_ARG ",\"stack\":{\"type\":\"integer\"}}}", + TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, t_get_scratchblocks }, + { "add_scratchblocks", "Adicionar pilhas (scratchblocks)", + "Cria pilhas a partir de codigo em scratchblocks (uma pilha por bloco de linhas separado por linha vazia; " + "C fecha com \"end\"). Aceita os rotulos em ingles do Scratch e os de list_block_types.", + "{\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"string\"}," TAB_ARG "," + "\"x\":{\"type\":\"number\"},\"y\":{\"type\":\"number\"}},\"required\":[\"code\"]}", 0, t_add_scratchblocks }, + { "replace_stack", "Trocar uma pilha", + "Substitui a pilha pelo codigo em scratchblocks, no mesmo lugar. Se o codigo nao virar nenhuma pilha, nada muda.", + "{\"type\":\"object\",\"properties\":{\"stack\":{\"type\":\"integer\"},\"code\":{\"type\":\"string\"}," TAB_ARG "}," + "\"required\":[\"stack\",\"code\"]}", TB_MCP_DESTRUCTIVE, t_replace_stack }, + { "delete_stack", "Apagar uma pilha", "Apaga a pilha inteira.", + "{\"type\":\"object\",\"properties\":{\"stack\":{\"type\":\"integer\"}," TAB_ARG "},\"required\":[\"stack\"]}", + TB_MCP_DESTRUCTIVE | TB_MCP_IDEMPOTENT, t_delete_stack }, + { "move_stack", "Mover uma pilha", "Leva a pilha para (x, y) na area de scripts.", + "{\"type\":\"object\",\"properties\":{\"stack\":{\"type\":\"integer\"},\"x\":{\"type\":\"number\"}," + "\"y\":{\"type\":\"number\"}," TAB_ARG "},\"required\":[\"stack\",\"x\",\"y\"]}", TB_MCP_IDEMPOTENT, t_move_stack }, + { "add_block", "Adicionar um bloco", + "Cria um bloco do tipo dado (veja list_block_types), com os campos, solto (x, y) ou encaixado: " + "embaixo de outro (below), num campo (into + input) ou numa boca de bloco C (into + mouth).", + "{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\"}," INPUTS_ARG "," PLACE_ARGS "," TAB_ARG "}," + "\"required\":[\"type\"]}", 0, t_add_block }, + { "move_block", "Mover um bloco", + "Tira o bloco (com os que estao embaixo dele, como ao arrastar; alone = true leva so ele e os de baixo " + "sobem) e o coloca solto ou encaixado.", + "{\"type\":\"object\",\"properties\":{\"block\":{\"type\":\"integer\"},\"alone\":{\"type\":\"boolean\"}," + PLACE_ARGS "," TAB_ARG "}," + "\"required\":[\"block\"]}", 0, t_move_block }, + { "delete_block", "Apagar um bloco", + "Apaga o bloco (com o que esta encaixado nele); os de baixo sobem. with_below = true apaga tambem os de baixo.", + "{\"type\":\"object\",\"properties\":{\"block\":{\"type\":\"integer\"},\"with_below\":{\"type\":\"boolean\"}," + TAB_ARG "},\"required\":[\"block\"]}", TB_MCP_DESTRUCTIVE, t_delete_block }, + { "set_inputs", "Mudar campos de um bloco", "Escreve valores nos campos vazios do bloco.", + "{\"type\":\"object\",\"properties\":{\"block\":{\"type\":\"integer\"}," INPUTS_ARG "," TAB_ARG "}," + "\"required\":[\"block\",\"inputs\"]}", TB_MCP_IDEMPOTENT, t_set_inputs }, + { "run", "Rodar", + "Sem stack: a bandeira verde (todos os \"quando a bandeira for clicado\"). Com stack: roda aquela pilha. " + "Os scripts seguem rodando nos quadros seguintes: veja get_output.", + "{\"type\":\"object\",\"properties\":{\"stack\":{\"type\":\"integer\"}," TAB_ARG "}}", 0, t_run }, + { "stop", "Parar", "O botao vermelho: para todos os scripts.", + "{\"type\":\"object\",\"additionalProperties\":false}", TB_MCP_IDEMPOTENT, t_stop }, + { "get_output", "Saida", "O que os scripts escreveram (console), as variaveis e se ainda ha script rodando.", + "{\"type\":\"object\",\"additionalProperties\":false}", TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, t_get_output }, + { "new_tab", "Nova aba", "Cria uma aba de blocos em branco e a seleciona.", + "{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}}}", 0, t_new_tab }, + { "select_tab", "Selecionar aba", "Mostra a aba no editor.", + "{\"type\":\"object\",\"properties\":{" TAB_ARG "},\"required\":[\"tab\"]}", TB_MCP_IDEMPOTENT, t_select_tab }, + { "save_project", "Salvar projeto", "Salva o projeto inteiro num arquivo .json (sobrescreve).", + "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"}},\"required\":[\"path\"]}", + TB_MCP_DESTRUCTIVE | TB_MCP_IDEMPOTENT, t_save_project }, + { "open_project", "Abrir projeto", + "Abre um projeto .json (ou .txt em scratchblocks). Substitui o que esta aberto.", + "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"}},\"required\":[\"path\"]}", + TB_MCP_DESTRUCTIVE, t_open_project }, + { "ui_tree", "Interface (arvore acessivel)", + "A interface do editor como arvore: papel, nome, valor, estados e retangulo de cada componente. " + "within = nome de um componente para ver so a parte dele.", + "{\"type\":\"object\",\"properties\":{\"within\":{\"type\":\"string\"}}}", + TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, t_ui_tree }, + { "ui_action", "Usar a interface", + "Age num componente achado por papel e nome (como em ui_tree): activate (clicar), menu, edit, ou drop " + "(arrastar ate target_role/target_name).", + "{\"type\":\"object\",\"properties\":{\"role\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"}," + "\"within\":{\"type\":\"string\"},\"action\":{\"type\":\"string\",\"enum\":[\"activate\",\"menu\",\"edit\",\"drop\"]}," + "\"target_role\":{\"type\":\"string\"},\"target_name\":{\"type\":\"string\"},\"target_within\":{\"type\":\"string\"}}," + "\"required\":[\"name\"]}", 0, t_ui_action }, + { "ui_type", "Digitar", "Digita texto no componente com o foco e/ou aperta uma tecla (enter, escape...).", + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},\"key\":{\"type\":\"string\"}}}", 0, t_ui_type }, +}; + +#define INSTRUCTIONS \ + "TinyBlocks: editor de blocos estilo Scratch. Leia as pilhas com list_stacks (codigo em scratchblocks + " \ + "ids dos blocos) e edite com add_scratchblocks / replace_stack (codigo inteiro) ou add_block / move_block / " \ + "set_inputs / delete_block (bloco a bloco). Os rotulos aceitos estao em list_block_types. Rode com run e " \ + "leia o resultado com get_output. Posicoes (x, y) sao da area de scripts; ids valem dentro de uma aba." + +/* O servidor sempre existe (as ferramentas atendem sem transporte nos testes); + * o HTTP escuta em 127.0.0.1:TINYBLOCKS_MCP_PORT (padrao 7811; 0 = nao escuta) */ +void ed_mcp_start(Ed* ed) { + ed->mcp = tb_mcp_server_new("tinyblocks-editor", "1.0.0", INSTRUCTIONS); + if (!ed->mcp) return; + for (size_t i = 0; i < sizeof(s_tools) / sizeof(s_tools[0]); i++) tb_mcp_server_add_tool(ed->mcp, &s_tools[i], ed); + const char* env = getenv("TINYBLOCKS_MCP_PORT"); + int port = env && env[0] ? atoi(env) : MCP_PORT_DEFAULT; + if (port <= 0) return; + bool ok = false; + for (int k = 0; k < MCP_PORT_TRIES && !ok; k++) ok = tb_mcp_server_listen(ed->mcp, port + k); + if (ok) fprintf(stderr, "[tinyblocks] servidor MCP em http://127.0.0.1:%d/mcp\n", tb_mcp_server_port(ed->mcp)); + else fprintf(stderr, "[tinyblocks] servidor MCP: nenhuma porta livre a partir de %d\n", port); +} + +void ed_mcp_poll(Ed* ed) { + if (ed->mcp) tb_mcp_server_poll(ed->mcp); +} + +void ed_mcp_stop(Ed* ed) { + tb_mcp_server_free(ed->mcp); + ed->mcp = NULL; +} + +/* Para testes: o servidor do editor (atende sem transporte) */ +TB_API struct TbMcpServer* tb_editor_mcp_server(TinyBlocks_Block* scene) { + if (!scene || !scene->userdata) return NULL; + Ed* ed = *(Ed**)scene->userdata; + return ed ? ed->mcp : NULL; +} diff --git a/libraries/tinyblocks-mcp-server/Makefile b/libraries/tinyblocks-mcp-server/Makefile new file mode 100644 index 0000000..45b1da1 --- /dev/null +++ b/libraries/tinyblocks-mcp-server/Makefile @@ -0,0 +1,30 @@ +# Makefile da library mcp-server (servidor MCP em C: protocolo, HTTP e stdio) +# Constroi build/libtinyblocks-mcp-server.a e build/libtinyblocks-mcp-server.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -DTB_MCP_SERVER_PRIVATE_API -I../../include -Iinclude + +HDRS := include/tb_mcp_server.h include/tb_mcp_server_internal.h +OBJ := $(BUILD)/tb_mcp_server.o $(BUILD)/tb_mcp_http.o +LIB_A := $(BUILD)/libtinyblocks-mcp-server.a +LIB_SO := $(BUILD)/libtinyblocks-mcp-server.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/%.o: src/%.c $(HDRS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-mcp-server/include/tb_mcp_server.h b/libraries/tinyblocks-mcp-server/include/tb_mcp_server.h new file mode 100644 index 0000000..7e426ac --- /dev/null +++ b/libraries/tinyblocks-mcp-server/include/tb_mcp_server.h @@ -0,0 +1,105 @@ +/* + * TinyBlocks - tb_mcp_server.h + * Servidor MCP (Model Context Protocol) em C, sem dependencias alem do core. + * + * Fala as duas eras do protocolo ("dual-era"): + * - moderna (2026-07-28): sem handshake; cada pedido traz em _meta a versao + * e as capacidades do cliente; server/discover; resultType nos resultados; + * no HTTP, os cabecalhos MCP-Protocol-Version / Mcp-Method / Mcp-Name sao + * conferidos com o corpo; + * - antiga (2025-11-25 e anteriores): initialize + notifications/initialized. + * O servidor nao guarda estado de sessao: cada pedido e atendido sozinho. + * + * Ferramentas sao uma interface: nome, descricao, esquema dos argumentos + * (JSON) e a funcao que atende. Exemplo: + * + * static void soma(void* user, TbMcpRequest* rq) { + * double a = tb_mcp_req_num(rq, "a", 0), b = tb_mcp_req_num(rq, "b", 0); + * tb_mcp_req_text(rq, "%g", a + b); + * } + * static const TbMcpTool t = { "soma", "Soma", "Soma a e b", + * "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"number\"}," + * "\"b\":{\"type\":\"number\"}},\"required\":[\"a\",\"b\"]}", + * TB_MCP_READ_ONLY, soma }; + * tb_mcp_server_add_tool(srv, &t, NULL); + * + * Transportes: HTTP ("Streamable HTTP", so em 127.0.0.1, sem bloquear: chame + * tb_mcp_server_poll a cada quadro, na thread que pode mexer no estado) e + * stdio (tb_mcp_server_serve_stdio, bloqueante). tb_mcp_server_handle atende + * um pedido JSON-RPC sem transporte nenhum (testes). + */ +#ifndef TINYBLOCKS_MCP_SERVER_H +#define TINYBLOCKS_MCP_SERVER_H + +#include +#include +#include +#include + +#define TB_MCP_PROTOCOL_MODERN "2026-07-28" + +typedef struct TbMcpServer TbMcpServer; +typedef struct TbMcpRequest TbMcpRequest; + +/* Dicas de comportamento (annotations da ferramenta) */ +enum { + TB_MCP_READ_ONLY = 1u << 0, /* nao muda nada */ + TB_MCP_DESTRUCTIVE = 1u << 1, /* pode apagar/sobrescrever */ + TB_MCP_IDEMPOTENT = 1u << 2, /* repetir com os mesmos args = 1 vez */ +}; + +typedef struct TbMcpTool { + const char* name; /* [A-Za-z0-9_.-] */ + const char* title; /* nome para mostrar */ + const char* description; + const char* input_schema; /* JSON Schema (texto) dos argumentos */ + unsigned hints; /* TB_MCP_* */ + void (*call)(void* user, TbMcpRequest* rq); +} TbMcpTool; + +/* -- Servidor ------------------------------------------------------------- */ +TB_API TbMcpServer* tb_mcp_server_new(const char* name, const char* version, const char* instructions); +TB_API void tb_mcp_server_free(TbMcpServer* s); +/* A ferramenta (e as strings dela) precisam viver enquanto o servidor viver */ +TB_API bool tb_mcp_server_add_tool(TbMcpServer* s, const TbMcpTool* tool, void* user); +TB_API int tb_mcp_server_tool_count(const TbMcpServer* s); + +/* Cabecalhos HTTP relevantes de um pedido (NULL = ausente / nao e HTTP) */ +typedef struct TbMcpHttpHeaders { + const char* protocol_version; /* MCP-Protocol-Version */ + const char* method; /* Mcp-Method */ + const char* name; /* Mcp-Name */ +} TbMcpHttpHeaders; + +/* Atende um pedido JSON-RPC. Devolve a resposta (malloc) ou NULL para + * notificacao; *http_status recebe o status HTTP correspondente (200, 202, + * 400, 404...). `h` = NULL fora do HTTP. */ +TB_API char* tb_mcp_server_handle(TbMcpServer* s, const char* body, const TbMcpHttpHeaders* h, + int* http_status); + +/* -- HTTP (Streamable HTTP, endpoint /mcp) -------------------------------- */ +/* Escuta em 127.0.0.1:port (0 = porta livre). Falso se nao conseguiu. */ +TB_API bool tb_mcp_server_listen(TbMcpServer* s, int port); +TB_API int tb_mcp_server_port(const TbMcpServer* s); /* 0 = nao escuta */ +/* Aceita, le e responde o que estiver pronto, sem bloquear. Devolve quantos + * pedidos atendeu. */ +TB_API int tb_mcp_server_poll(TbMcpServer* s); + +/* -- stdio: uma mensagem JSON por linha, ate o fim da entrada ------------- */ +TB_API int tb_mcp_server_serve_stdio(TbMcpServer* s, FILE* in, FILE* out); + +/* -- Dentro de uma ferramenta --------------------------------------------- */ +/* Argumentos (emprestados; NULL se ausente) */ +TB_API const TinyBlocks_JsonValue* tb_mcp_req_args(TbMcpRequest* rq); +TB_API const TinyBlocks_JsonValue* tb_mcp_req_arg (TbMcpRequest* rq, const char* key); +TB_API bool tb_mcp_req_has(TbMcpRequest* rq, const char* key); +TB_API const char* tb_mcp_req_str(TbMcpRequest* rq, const char* key, const char* def); +TB_API double tb_mcp_req_num(TbMcpRequest* rq, const char* key, double def); +TB_API bool tb_mcp_req_bool(TbMcpRequest* rq, const char* key, bool def); +/* Resultado: texto (acumula), erro da ferramenta (isError, o modelo pode + * corrigir e tentar de novo) e conteudo estruturado (fica com a referencia) */ +TB_API void tb_mcp_req_text (TbMcpRequest* rq, const char* fmt, ...) __attribute__((format(printf, 2, 3))); +TB_API void tb_mcp_req_error(TbMcpRequest* rq, const char* fmt, ...) __attribute__((format(printf, 2, 3))); +TB_API void tb_mcp_req_structured(TbMcpRequest* rq, TinyBlocks_JsonValue* value); + +#endif /* TINYBLOCKS_MCP_SERVER_H */ diff --git a/libraries/tinyblocks-mcp-server/include/tb_mcp_server_internal.h b/libraries/tinyblocks-mcp-server/include/tb_mcp_server_internal.h new file mode 100644 index 0000000..803bbf4 --- /dev/null +++ b/libraries/tinyblocks-mcp-server/include/tb_mcp_server_internal.h @@ -0,0 +1,40 @@ +/* + * TinyBlocks - tb_mcp_server_internal.h + * API privada da tinyblocks-mcp-server: o struct do servidor, dividido entre + * o protocolo (tb_mcp_server.c) e o transporte HTTP (tb_mcp_http.c). + */ +#ifndef TINYBLOCKS_MCP_SERVER_INTERNAL_H +#define TINYBLOCKS_MCP_SERVER_INTERNAL_H + +#ifndef TB_MCP_SERVER_PRIVATE_API +# error "API privada da tinyblocks-mcp-server: inclua tb_mcp_server.h (ou compile com -DTB_MCP_SERVER_PRIVATE_API)" +#endif + +#include "tb_mcp_server.h" + +/* Conexao HTTP em andamento (lida aos poucos, sem bloquear) */ +typedef struct TbMcpConn { + int fd; + char* buf; + size_t len, cap; + unsigned since_ms; /* para largar conexao parada */ +} TbMcpConn; + +#define TB_MCP_MAX_CONNS 16 + +struct TbMcpServer { + char* name; + char* version; + char* instructions; + struct { const TbMcpTool* tool; void* user; }* tools; + int tool_n, tool_cap; + + int listen_fd; /* -1 = nao escuta */ + int port; + TbMcpConn conns[TB_MCP_MAX_CONNS]; + int conn_n; +}; + +void tb_mcp_http_close(TbMcpServer* s); + +#endif /* TINYBLOCKS_MCP_SERVER_INTERNAL_H */ diff --git a/libraries/tinyblocks-mcp-server/library.toml b/libraries/tinyblocks-mcp-server/library.toml new file mode 100644 index 0000000..75d052b --- /dev/null +++ b/libraries/tinyblocks-mcp-server/library.toml @@ -0,0 +1,19 @@ +# Metadados da library mcp-server. Lido pela UI/build sem recompilar o .so. +# Nao tem blocos: e o servidor MCP (protocolo + HTTP + stdio) que o editor usa +# para ser controlado por agentes; por isso e privada. +[library] +name = "tinyblocks-mcp-server" +private = true +version = "1.0.0" +category = "MCP" +description = "Servidor MCP em C (2026-07-28 e anteriores; HTTP local e stdio)" +color = [233, 30, 99, 255] +dark = [194, 24, 91, 255] + +[build] +sources = ["src/tb_mcp_server.c", "src/tb_mcp_http.c"] +includes = ["include"] +defines = ["TB_MCP_SERVER_PRIVATE_API"] +shared = "build/libtinyblocks-mcp-server.so" +static = "build/libtinyblocks-mcp-server.a" +depends = [] diff --git a/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c b/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c new file mode 100644 index 0000000..269cb9d --- /dev/null +++ b/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c @@ -0,0 +1,218 @@ +/* + * TinyBlocks - tb_mcp_http.c + * Transporte "Streamable HTTP" do servidor MCP: um endpoint POST /mcp, so em + * 127.0.0.1, sem bloquear (tb_mcp_server_poll a cada quadro). Cada pedido e + * uma conexao: le cabecalhos + corpo (Content-Length), responde JSON, fecha. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tb_mcp_server_internal.h" + +#define MAX_REQUEST (4u << 20) /* 4 MiB por pedido */ +#define CONN_TIMEOUT 5000u /* ms sem completar o pedido: larga */ + +static unsigned now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (unsigned)(ts.tv_sec * 1000u + (unsigned)(ts.tv_nsec / 1000000)); +} + +static void set_nonblock(int fd) { + int fl = fcntl(fd, F_GETFL, 0); + if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); +} + +bool tb_mcp_server_listen(TbMcpServer* s, int port) { + if (!s) return false; + tb_mcp_http_close(s); + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) return false; + int one = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + struct sockaddr_in a; + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_port = htons((unsigned short)port); + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* so a propria maquina */ + if (bind(fd, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(fd, 16) != 0) { close(fd); return false; } + socklen_t al = sizeof(a); + getsockname(fd, (struct sockaddr*)&a, &al); + set_nonblock(fd); + s->listen_fd = fd; + s->port = ntohs(a.sin_port); + return true; +} + +int tb_mcp_server_port(const TbMcpServer* s) { return s && s->listen_fd >= 0 ? s->port : 0; } + +static void conn_drop(TbMcpServer* s, int i) { + close(s->conns[i].fd); + free(s->conns[i].buf); + s->conns[i] = s->conns[--s->conn_n]; +} + +void tb_mcp_http_close(TbMcpServer* s) { + while (s->conn_n > 0) conn_drop(s, 0); + if (s->listen_fd >= 0) close(s->listen_fd); + s->listen_fd = -1; + s->port = 0; +} + +/* Valor de um cabecalho (nome sem diferenciar maiusculas); copia em out */ +static bool header(const char* head, size_t head_len, const char* name, char* out, size_t cap) { + size_t nl = strlen(name); + const char* p = head; + const char* end = head + head_len; + while (p < end) { + const char* eol = memchr(p, '\n', (size_t)(end - p)); + if (!eol) eol = end; + if ((size_t)(eol - p) > nl && !strncasecmp(p, name, nl) && p[nl] == ':') { + const char* v = p + nl + 1; + while (v < eol && (*v == ' ' || *v == '\t')) v++; + const char* ve = eol; + while (ve > v && (ve[-1] == '\r' || ve[-1] == ' ')) ve--; + size_t n = (size_t)(ve - v) < cap - 1 ? (size_t)(ve - v) : cap - 1; + memcpy(out, v, n); + out[n] = 0; + return true; + } + p = eol + 1; + } + return false; +} + +static void send_all(int fd, const char* data, size_t n) { + int fl = fcntl(fd, F_GETFL, 0); /* a resposta sai inteira */ + if (fl >= 0) fcntl(fd, F_SETFL, fl & ~O_NONBLOCK); + while (n > 0) { + ssize_t w = send(fd, data, n, MSG_NOSIGNAL); + if (w <= 0) { if (w < 0 && errno == EINTR) continue; return; } + data += w; + n -= (size_t)w; + } +} + +static void respond(int fd, int status, const char* body) { + const char* reason = status == 200 ? "OK" : status == 202 ? "Accepted" : status == 400 ? "Bad Request" : + status == 403 ? "Forbidden" : status == 404 ? "Not Found" : + status == 405 ? "Method Not Allowed" : status == 413 ? "Payload Too Large" : "Error"; + size_t bl = body ? strlen(body) : 0; + char head[256]; + int hn = snprintf(head, sizeof(head), + "HTTP/1.1 %d %s\r\n%sContent-Length: %zu\r\nConnection: close\r\n%s\r\n", + status, reason, body ? "Content-Type: application/json\r\n" : "", bl, + status == 405 ? "Allow: POST\r\n" : ""); + send_all(fd, head, (size_t)hn); + if (bl) send_all(fd, body, bl); +} + +/* Origin presente precisa ser desta maquina (contra DNS rebinding) */ +static bool origin_ok(const char* o) { + if (!o || !o[0] || !strcmp(o, "null")) return true; + const char* h = strstr(o, "://"); + if (!h) return false; + h += 3; + static const char* local[] = { "localhost", "127.0.0.1", "[::1]" }; + for (size_t i = 0; i < sizeof(local) / sizeof(local[0]); i++) { + size_t n = strlen(local[i]); + if (!strncmp(h, local[i], n) && (h[n] == 0 || h[n] == ':' || h[n] == '/')) return true; + } + return false; +} + +/* Pedido completo? (cabecalhos + corpo). -1 = invalido / grande demais */ +static int request_ready(TbMcpConn* c, size_t* head_len, size_t* body_len) { + char* sep = NULL; + for (size_t i = 0; i + 3 < c->len; i++) + if (!memcmp(c->buf + i, "\r\n\r\n", 4)) { sep = c->buf + i; break; } + if (!sep) return c->len > 65536 ? -1 : 0; + *head_len = (size_t)(sep - c->buf); + char v[32]; + size_t cl = header(c->buf, *head_len, "Content-Length", v, sizeof(v)) ? strtoul(v, NULL, 10) : 0; + if (cl > MAX_REQUEST) return -1; + *body_len = cl; + return c->len >= *head_len + 4 + cl ? 1 : 0; +} + +static void serve(TbMcpServer* s, TbMcpConn* c, size_t head_len, size_t body_len) { + char* head = c->buf; + head[head_len] = 0; + char method[8] = "", path[128] = ""; + sscanf(head, "%7s %127s", method, path); + char* q = strchr(path, '?'); + if (q) *q = 0; + char origin[256] = ""; + header(head, head_len, "Origin", origin, sizeof(origin)); + if (!origin_ok(origin)) { + respond(c->fd, 403, "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32600,\"message\":\"Origin nao permitido\"}}"); + return; + } + if (strcmp(path, "/mcp") != 0) { respond(c->fd, 404, "{\"error\":\"o endpoint MCP e /mcp\"}"); return; } + if (strcmp(method, "POST") != 0) { respond(c->fd, 405, NULL); return; } /* sem stream GET nem sessao */ + + char ver[64] = "", mmethod[128] = "", mname[512] = ""; + TbMcpHttpHeaders h = { + header(head, head_len, "MCP-Protocol-Version", ver, sizeof(ver)) ? ver : NULL, + header(head, head_len, "Mcp-Method", mmethod, sizeof(mmethod)) ? mmethod : NULL, + header(head, head_len, "Mcp-Name", mname, sizeof(mname)) ? mname : NULL, + }; + char* body = malloc(body_len + 1); + if (!body) { respond(c->fd, 413, NULL); return; } + memcpy(body, c->buf + head_len + 4, body_len); + body[body_len] = 0; + int status = 200; + char* resp = tb_mcp_server_handle(s, body, &h, &status); + free(body); + respond(c->fd, resp ? status : 202, resp); + free(resp); +} + +int tb_mcp_server_poll(TbMcpServer* s) { + if (!s || s->listen_fd < 0) return 0; + for (;;) { /* conexoes novas */ + int fd = accept(s->listen_fd, NULL, NULL); + if (fd < 0) break; + if (s->conn_n >= TB_MCP_MAX_CONNS) { close(fd); continue; } + set_nonblock(fd); + TbMcpConn* c = &s->conns[s->conn_n++]; + memset(c, 0, sizeof(*c)); + c->fd = fd; + c->since_ms = now_ms(); + } + int served = 0; + unsigned now = now_ms(); + for (int i = s->conn_n - 1; i >= 0; i--) { + TbMcpConn* c = &s->conns[i]; + bool closed = false; + for (;;) { + if (c->len + 4096 + 1 > c->cap) { + size_t cap = c->cap ? c->cap * 2 : 8192; + char* nb = realloc(c->buf, cap); + if (!nb) { closed = true; break; } + c->buf = nb; + c->cap = cap; + } + ssize_t r = recv(c->fd, c->buf + c->len, c->cap - c->len - 1, 0); + if (r > 0) { c->len += (size_t)r; continue; } + if (r == 0) closed = true; + else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) closed = true; + break; + } + size_t hl = 0, bl = 0; + int ready = c->buf ? request_ready(c, &hl, &bl) : 0; + if (ready > 0) { serve(s, c, hl, bl); served++; conn_drop(s, i); continue; } + if (ready < 0) { respond(c->fd, 413, NULL); conn_drop(s, i); continue; } + if (closed || now - c->since_ms > CONN_TIMEOUT) conn_drop(s, i); + } + return served; +} diff --git a/libraries/tinyblocks-mcp-server/src/tb_mcp_server.c b/libraries/tinyblocks-mcp-server/src/tb_mcp_server.c new file mode 100644 index 0000000..5760d07 --- /dev/null +++ b/libraries/tinyblocks-mcp-server/src/tb_mcp_server.c @@ -0,0 +1,462 @@ +/* + * TinyBlocks - tb_mcp_server.c + * Protocolo MCP do lado do servidor (ver tb_mcp_server.h): JSON-RPC, as duas + * eras do protocolo, ferramentas e o transporte stdio. O HTTP fica em + * tb_mcp_http.c. + */ +#define _POSIX_C_SOURCE 200809L +#include +#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; +} diff --git a/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h b/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h index 097148c..fad193d 100644 --- a/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h +++ b/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h @@ -7,8 +7,9 @@ * 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. + * Fala as duas eras do protocolo: a moderna (2026-07-28, sem handshake) e a + * antiga (initialize), descobrindo qual o servidor usa. Uma conexao por + * endereco fica aberta entre as chamadas; tb_mcp_deinit fecha todas. */ #ifndef TINYBLOCKS_MCP_H #define TINYBLOCKS_MCP_H @@ -29,6 +30,7 @@ TB_MCP_API void tb_mcp_deinit(void); * 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_protocol(const char* url, bool* ok); /* "moderna (2026-07-28)" */ 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, diff --git a/libraries/tinyblocks-mcp/src/tb_mcp.c b/libraries/tinyblocks-mcp/src/tb_mcp.c index 15cb759..974549d 100644 --- a/libraries/tinyblocks-mcp/src/tb_mcp.c +++ b/libraries/tinyblocks-mcp/src/tb_mcp.c @@ -104,6 +104,10 @@ 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_protocol(const char* url, bool* ok) { + const char* a[] = { url }; + return py_call("_tbmcp_era", 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); diff --git a/libraries/tinyblocks-mcp/src/tb_mcp.py b/libraries/tinyblocks-mcp/src/tb_mcp.py index 088a697..49e804d 100644 --- a/libraries/tinyblocks-mcp/src/tb_mcp.py +++ b/libraries/tinyblocks-mcp/src/tb_mcp.py @@ -8,18 +8,30 @@ # 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). +# Protocolo nas duas eras: a moderna (2026-07-28: sem handshake, cada pedido +# leva versao e capacidades em _meta) e a antiga (initialize). A era do +# servidor e descoberta uma vez (stdio: sonda com server/discover; HTTP: +# pedido moderno, e cai para o initialize se a resposta nao for um erro +# moderno). Uma conexao por URL fica aberta entre as chamadas. As funcoes +# publicas devolvem texto com um prefixo: "+" sucesso, "!" erro (o C +# transforma em erro do TinyBlocks). import json as _tbmcp_json -_TBMCP_PROTOCOL = "2025-06-18" +_TBMCP_MODERN = "2026-07-28" +_TBMCP_LEGACY = "2025-11-25" _TBMCP_TIMEOUT = 30.0 +_TBMCP_PROBE_TIMEOUT = 5.0 +_TBMCP_CLIENT = {"name": "tinyblocks", "version": "1.0.0"} +# erros que so um servidor moderno manda (HeaderMismatch, capacidade, versao) +_TBMCP_MODERN_ERRORS = (-32020, -32021, -32022) class _TbMcpError(Exception): - pass + def __init__(self, text, code=None, data=None): + Exception.__init__(self, text) + self.code = code + self.data = data def _tbmcp_result(msg): @@ -29,8 +41,18 @@ def _tbmcp_result(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", {}) + raise _TbMcpError(text if code is None else "%s (codigo %s)" % (text, code), + code, err.get("data") if isinstance(err, dict) else None) + res = msg.get("result", {}) + if isinstance(res, dict) and res.get("resultType", "complete") == "input_required": + raise _TbMcpError("o servidor pediu informacoes extras (input_required), que este cliente nao suporta") + return res + + +def _tbmcp_meta(): + return {"io.modelcontextprotocol/protocolVersion": _TBMCP_MODERN, + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": _TBMCP_CLIENT} def _tbmcp_error_reply(req_id, code, text): @@ -102,12 +124,12 @@ class _TbMcpStdio: def notify(self, method, params): self._send({"jsonrpc": "2.0", "method": method, "params": params}) - def request(self, method, params): + def request(self, method, params, timeout=_TBMCP_TIMEOUT): 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 + deadline = time.monotonic() + timeout while True: line = self._readline(deadline).strip() if not line: @@ -146,41 +168,57 @@ class _TbMcpStdio: pass +def _tbmcp_header_value(v): + """Valor de cabecalho: ASCII visivel como esta; o resto em =?base64?...?=""" + import base64 + plain = all(0x20 <= ord(c) < 0x7f for c in v) and v == v.strip() and \ + not (v.startswith("=?base64?") and v.endswith("?=")) + return v if plain else "=?base64?" + base64.b64encode(v.encode("utf-8")).decode("ascii") + "?=" + + class _TbMcpHttp: def __init__(self, url): self.url = url self.session = None self.proto = None + self.modern = False self.next_id = 1 def alive(self): return True - def _headers(self): + def _headers(self, obj): h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} - if self.session: + if self.session and not self.modern: h["Mcp-Session-Id"] = self.session if self.proto: h["MCP-Protocol-Version"] = self.proto + if self.modern and isinstance(obj, dict) and "method" in obj: + h["Mcp-Method"] = obj["method"] + p = obj.get("params") or {} + name = p.get("name", p.get("uri")) if obj["method"] in ("tools/call", "resources/read", "prompts/get") else None + if isinstance(name, str): + h["Mcp-Name"] = _tbmcp_header_value(name) 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) + req = urllib.request.Request(self.url, data=data, headers=self._headers(obj), method=method) try: return urllib.request.urlopen(req, timeout=_TBMCP_TIMEOUT) except urllib.error.HTTPError as e: - detail = "" + detail, code, data = "", None, None 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", "")) + code, data = body["error"].get("code"), body["error"].get("data") except Exception: pass - if e.code == 404 and self.session: + if e.code == 404 and self.session and not self.modern: raise _TbMcpError("sessao expirada (HTTP 404)") - raise _TbMcpError("HTTP %d %s%s" % (e.code, e.reason, detail)) + raise _TbMcpError("HTTP %d %s%s" % (e.code, e.reason, detail), code, data) except urllib.error.URLError as e: raise _TbMcpError("nao consegui conectar em %s: %s" % (self.url, e.reason)) except OSError as e: @@ -240,13 +278,13 @@ class _TbMcpHttp: def notify(self, method, params): self._post({"jsonrpc": "2.0", "method": method, "params": params}, None) - def request(self, method, params): + def request(self, method, params, timeout=None): 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: + if not self.session or self.modern: return try: self._open(None, "DELETE").close() @@ -257,28 +295,70 @@ class _TbMcpHttp: class _TbMcpSession: def __init__(self, url): if url.startswith("stdio://"): - self.t = _TbMcpStdio(url[len("stdio://"):]) + self.cmd = url[len("stdio://"):] + self.t = _TbMcpStdio(self.cmd) elif url.startswith("http://") or url.startswith("https://"): + self.cmd = None self.t = _TbMcpHttp(url) else: raise _TbMcpError("endereco invalido (use stdio://comando ou http://...): %s" % url) + self.modern = False + self.info = {} 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", {}) + if not self._probe_modern(): + if self.cmd is not None and not self.t.alive(): # a sonda derrubou um servidor antigo + self.t.close() + self.t = _TbMcpStdio(self.cmd) + self._legacy_init() except Exception: self.t.close() raise + def _probe_modern(self): + """server/discover com _meta moderno: sucesso ou erro moderno = servidor moderno.""" + if self.cmd is None: + self.t.modern = True + self.t.proto = _TBMCP_MODERN + try: + res = _tbmcp_result(self.t.request("server/discover", {"_meta": _tbmcp_meta()}, + timeout=_TBMCP_PROBE_TIMEOUT)) + except _TbMcpError as e: + self.t.modern = False + self.t.proto = None + if e.code in _TBMCP_MODERN_ERRORS: + sup = (e.data or {}).get("supported", []) if isinstance(e.data, dict) else [] + raise _TbMcpError("o servidor so fala as versoes %s do MCP" % ", ".join(sup) if sup else str(e)) + return False + if _TBMCP_MODERN not in (res.get("supportedVersions") or []): + self.t.modern = False + self.t.proto = None + return False + self.modern = True + self.t.modern = True + self.t.proto = _TBMCP_MODERN + meta = res.get("_meta") or {} + self.info = meta.get("io.modelcontextprotocol/serverInfo") or {} + return True + + def _legacy_init(self): + res = _tbmcp_result(self.t.request("initialize", { + "protocolVersion": _TBMCP_LEGACY, + "capabilities": {}, + "clientInfo": _TBMCP_CLIENT, + })) + self.info = res.get("serverInfo", {}) or {} + self.t.proto = res.get("protocolVersion") or _TBMCP_LEGACY + self.t.notify("notifications/initialized", {}) + def alive(self): return self.t.alive() def call(self, method, params): + if self.modern: + if method == "ping": # a era moderna nao tem ping + method = "server/discover" + params = dict(params) + params["_meta"] = _tbmcp_meta() return _tbmcp_result(self.t.request(method, params)) def close(self): @@ -359,6 +439,12 @@ def _tbmcp_server(url): return ("%s %s" % (info.get("name", "?"), info.get("version", ""))).strip() +@_tbmcp_api +def _tbmcp_era(url): + s = _tbmcp_session(url.strip()) + return "moderna (%s)" % _TBMCP_MODERN if s.modern else "antiga (%s)" % (s.t.proto or "?") + + def _tbmcp_all_tools(url): tools, cursor = [], None for _ in range(100): # paginas diff --git a/tests/editor_harness.c b/tests/editor_harness.c index e5dc288..9e802e0 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -24,6 +24,7 @@ #include #include #include +#include static TinyBlocks* rt; static TinyBlocks_Block *ev, *scene; @@ -138,6 +139,51 @@ static bool ax_do(int n, TinyBlocks_A11yAction a) { frame(x, y, 0, 0, 0, 0, NULL); return ok; } +/* == Servidor MCP do editor: chama uma ferramenta (era moderna, sem rede) === + * Devolve o texto do resultado (malloc); *err = isError; *sc = structuredContent + * (referencia nova, ou NULL) */ +static char* mcp(const char* tool, const char* args, bool* err, TinyBlocks_JsonValue** sc) { + char* req = malloc(strlen(args) + 512); + sprintf(req, "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/call\",\"params\":{\"name\":\"%s\"," + "\"arguments\":%s,\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"," + "\"io.modelcontextprotocol/clientCapabilities\":{}}}}", tool, args); + int st = 0; + char* resp = tb_mcp_server_handle(tb_editor_mcp_server(scene), req, NULL, &st); + free(req); + TinyBlocks_JsonValue* r = resp ? tb_json_parse(resp, NULL, 0) : NULL; + free(resp); + TinyBlocks_JsonValue* res = r ? tb_json_object_get(r, "result") : NULL; + TinyBlocks_JsonValue* ie = res ? tb_json_object_get(res, "isError") : NULL; + TinyBlocks_JsonValue* content = res ? tb_json_object_get(res, "content") : NULL; + TinyBlocks_JsonValue* first = content ? tb_json_array_get(content, 0) : NULL; + TinyBlocks_JsonValue* text = first ? tb_json_object_get(first, "text") : NULL; + if (err) *err = !res || tb_json_as_bool(ie, false); + if (sc) *sc = res ? tb_json_object_get(res, "structuredContent") : NULL; + char* out = strdup(text && tb_json_as_string(text) ? tb_json_as_string(text) : ""); + tb_json_release(text); tb_json_release(first); tb_json_release(content); + tb_json_release(ie); tb_json_release(res); tb_json_release(r); + frame(0, 0, 0, 0, 0, 0, NULL); /* a interface mostra o que mudou */ + return out; +} +/* Numero num caminho do structuredContent: "stacks.0.id" */ +static double sc_num(const TinyBlocks_JsonValue* v, const char* path) { + char key[64]; + TinyBlocks_JsonValue* cur = (TinyBlocks_JsonValue*)v; + if (cur) tb_json_retain(cur); + while (cur && *path) { + size_t n = strcspn(path, "."); + snprintf(key, sizeof(key), "%.*s", (int)n, path); + TinyBlocks_JsonValue* nx = tb_json_kind(cur) == TB_JSON_ARRAY ? tb_json_array_get(cur, (uint32_t)atoi(key)) + : tb_json_object_get(cur, key); + tb_json_release(cur); + cur = nx; + path += n + (path[n] == '.'); + } + double d = cur ? tb_json_as_number(cur, -1) : -1; + tb_json_release(cur); + return d; +} + /* Arrastar e soltar pela arvore (o editor decide o encaixe pelo papel do destino) */ static bool ax_drop(int src, int dst) { if (src < 0 || dst < 0) { printf("FAIL soltar: origem %d, destino %d\n", src, dst); fails++; return false; } @@ -232,6 +278,7 @@ static bool drawn_text(int node, const char* sub) { int main(void) { /* configurações isoladas: o harness não lê nem grava o ~/.config real */ setenv("XDG_CONFIG_HOME", "/tmp/tb_harness_cfg", 1); + setenv("TINYBLOCKS_MCP_PORT", "0", 1); /* o servidor MCP atende sem rede (cenario 29) */ unsetenv("TINYBLOCKS_SETTINGS"); remove("/tmp/tb_harness_cfg/tinyblocks/settings.csv"); tinyblocks_init(&rt, NULL); @@ -1138,6 +1185,140 @@ int main(void) { } } + /* 29. Servidor MCP do editor: um agente edita as pilhas por codigo */ + { + bool err; + TinyBlocks_JsonValue* sc = NULL; + char* t; + TinyBlocks_JsonValue* tl = NULL; + { + int st = 0; + char* r = tb_mcp_server_handle(tb_editor_mcp_server(scene), + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":{" + "\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}", + NULL, &st); + CHECK(r && strstr(r, "\"add_scratchblocks\"") && strstr(r, "\"replace_stack\"") && strstr(r, "\"move_block\"") && + strstr(r, "\"ui_action\""), "mcp: o editor lista as ferramentas"); + free(r); + } + (void)tl; + t = mcp("new_tab", "{\"name\":\"Agente\"}", &err, NULL); + CHECK(!err && (N(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, "Agente"))->states & TB_A11Y_SELECTED), + "mcp: new_tab cria e seleciona a aba"); + free(t); + + t = mcp("add_scratchblocks", "{\"code\":\"when flag clicked\\nset [x v] to (0)\\nrepeat (3)\\n" + "change [x v] by (1)\\nend\\nsay (x)\\n\",\"x\":40,\"y\":40}", &err, &sc); + int stack = (int)sc_num(sc, "stacks.0.id"); + tb_json_release(sc); + CHECK(!err && stack >= 0 && ax_in(ws(), TB_A11Y_LIST, "Pilha: quando a bandeira for clicado") >= 0 && + ws_block("repita (3) vezes", 0) >= 0, "mcp: add_scratchblocks cria a pilha (aparece na aba)"); + free(t); + + t = mcp("list_stacks", "{}", &err, &sc); + CHECK(!err && strstr(t, "repeat (3)") && strstr(t, "repita (3) vezes") && sc_num(sc, "stacks.0.id") == stack, + "mcp: list_stacks mostra o código e os blocos com ids"); + /* acha o id do "repita" na lista de blocos */ + int rep_id = -1; + for (int i = 0; i < 20; i++) { + char path[32]; + snprintf(path, sizeof(path), "stacks.0.blocks.%d.id", i); + int id = (int)sc_num(sc, path); + if (id < 0) break; + TinyBlocks_JsonValue* stks = tb_json_object_get(sc, "stacks"); + TinyBlocks_JsonValue* st0 = tb_json_array_get(stks, 0); + TinyBlocks_JsonValue* bl = tb_json_object_get(st0, "blocks"); + TinyBlocks_JsonValue* b = tb_json_array_get(bl, (uint32_t)i); + TinyBlocks_JsonValue* ty = tb_json_object_get(b, "type"); + if (ty && !strcmp(tb_json_as_string(ty), "Control.Repeat")) rep_id = id; + tb_json_release(ty); tb_json_release(b); tb_json_release(bl); tb_json_release(st0); tb_json_release(stks); + } + tb_json_release(sc); + free(t); + CHECK(rep_id >= 0, "mcp: o id do repita está na lista"); + + t = mcp("run", "{}", &err, NULL); + free(t); + for (int i = 0; i < 5; i++) frame(0, 0, 0, 0, 0, 0, NULL); + t = mcp("get_output", "{}", &err, NULL); + CHECK(!err && strstr(t, "Saida:\n3"), "mcp: run + get_output (a pilha escreve 3)"); + free(t); + + char args[256]; + snprintf(args, sizeof(args), "{\"block\":%d,\"inputs\":{\"vezes\":5}}", rep_id); + t = mcp("set_inputs", args, &err, NULL); + CHECK(!err && strstr(t, "repeat (5)") && ws_block("repita (5) vezes", 0) >= 0, "mcp: set_inputs muda o campo"); + free(t); + + snprintf(args, sizeof(args), "{\"type\":\"IO.Print\",\"inputs\":{\"0\":\"fim\"},\"below\":%d}", rep_id); + t = mcp("add_block", args, &err, &sc); + int fim = (int)sc_num(sc, "block"); + tb_json_release(sc); + CHECK(!err && fim >= 0 && strstr(t, "say [fim]"), "mcp: add_block encaixa embaixo do repita"); + free(t); + + snprintf(args, sizeof(args), "{\"block\":%d,\"into\":%d,\"mouth\":0,\"alone\":true}", fim, rep_id); + t = mcp("move_block", args, &err, NULL); + CHECK(!err && strstr(t, "repeat (5)\n say [fim]\n change [x v] by (1)\nend\nsay (x)"), + "mcp: move_block (alone) põe só o bloco no começo da boca"); + free(t); + snprintf(args, sizeof(args), "{\"block\":%d,\"below\":%d,\"alone\":true}", fim, rep_id); + t = mcp("move_block", args, &err, NULL); + CHECK(!err && strstr(t, "repeat (5)\n change [x v] by (1)\nend\nsay [fim]\nsay (x)"), + "mcp: move_block encaixa embaixo (o que estava ali vai depois)"); + free(t); + + t = mcp("move_block", "{\"block\":9999,\"x\":0,\"y\":0}", &err, NULL); + CHECK(err && strstr(t, "nao existe"), "mcp: bloco inexistente vira erro da ferramenta"); + free(t); + snprintf(args, sizeof(args), "{\"block\":%d,\"below\":%d}", rep_id, fim); + t = mcp("move_block", args, &err, NULL); + CHECK(err && strstr(t, "nele mesmo"), "mcp: não encaixa um bloco dentro dele mesmo"); + free(t); + t = mcp("add_block", "{\"type\":\"Nao.Existe\"}", &err, NULL); + CHECK(err && strstr(t, "list_block_types"), "mcp: tipo desconhecido sugere list_block_types"); + free(t); + + snprintf(args, sizeof(args), "{\"stack\":%d}", stack); + t = mcp("get_scratchblocks", args, &err, NULL); + CHECK(!err && strstr(t, "when flag clicked") && strstr(t, "repeat (5)"), "mcp: get_scratchblocks de uma pilha"); + free(t); + + snprintf(args, sizeof(args), "{\"stack\":%d,\"x\":300,\"y\":200}", stack); + float y_before = N(ax_in(ws(), TB_A11Y_LIST, "Pilha: quando a bandeira for clicado"))->y; + t = mcp("move_stack", args, &err, NULL); + CHECK(!err && N(ax_in(ws(), TB_A11Y_LIST, "Pilha: quando a bandeira for clicado"))->y > y_before, + "mcp: move_stack leva a pilha (a interface acompanha)"); + free(t); + + snprintf(args, sizeof(args), "{\"stack\":%d,\"code\":\"when flag clicked\\nsay [trocado]\\n\"}", stack); + t = mcp("replace_stack", args, &err, &sc); + int stack2 = (int)sc_num(sc, "stacks.0.id"); + tb_json_release(sc); + CHECK(!err && ws_block("repita", 0) < 0 && ws_block("escreva (trocado)", 0) >= 0, "mcp: replace_stack troca o código"); + free(t); + snprintf(args, sizeof(args), "{\"stack\":%d,\"code\":\"isso nao e scratchblocks\"}", stack2); + t = mcp("replace_stack", args, &err, NULL); + CHECK(err && ws_block("escreva (trocado)", 0) >= 0, "mcp: código inválido não apaga a pilha"); + free(t); + + snprintf(args, sizeof(args), "{\"stack\":%d}", stack2); + t = mcp("delete_stack", args, &err, NULL); + CHECK(!err && ax_in(ws(), TB_A11Y_LIST, NULL) < 0, "mcp: delete_stack apaga a pilha"); + free(t); + + /* a interface pela arvore acessivel */ + t = mcp("ui_action", "{\"role\":\"botão\",\"name\":\"Config\"}", &err, NULL); + CHECK(!err && ax_in(0, TB_A11Y_DIALOG, "Configurações") >= 0, "mcp: ui_action clica no botão Config"); + free(t); + t = mcp("ui_tree", "{\"within\":\"Configurações\"}", &err, NULL); + CHECK(!err && strstr(t, "Configurações, diálogo") && strstr(t, "Voltar, botão"), "mcp: ui_tree mostra o diálogo"); + free(t); + t = mcp("ui_type", "{\"key\":\"escape\"}", &err, NULL); + CHECK(!err && ax_in(0, TB_A11Y_DIALOG, "Configurações") < 0, "mcp: ui_type aperta Esc e fecha"); + free(t); + } + tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); return fails != 0; diff --git a/tests/mcp_server_test.c b/tests/mcp_server_test.c new file mode 100644 index 0000000..3a88e6f --- /dev/null +++ b/tests/mcp_server_test.c @@ -0,0 +1,230 @@ +/* Teste da tinyblocks-mcp-server: as duas eras do protocolo (handle direto), + * validacao dos cabecalhos HTTP, stdio e o HTTP de verdade (um processo + * filho serve, o teste pede por socket). */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(cond, msg) do { if (cond) printf("ok %s\n", msg); else { printf("FAIL %s\n", msg); fails++; } } while (0) + +static void soma(void* user, TbMcpRequest* rq) { + int* calls = user; + (*calls)++; + if (!tb_mcp_req_has(rq, "a")) { tb_mcp_req_error(rq, "falta o argumento a"); return; } + double r = tb_mcp_req_num(rq, "a", 0) + tb_mcp_req_num(rq, "b", 0); + TinyBlocks_JsonValue* o = tb_json_object(); + TinyBlocks_JsonValue* n = tb_json_number(r); + tb_json_object_set(o, "soma", n); + tb_json_release(n); + tb_mcp_req_structured(rq, o); +} + +static void eco(void* user, TbMcpRequest* rq) { + (void)user; + tb_mcp_req_text(rq, "eco: %s", tb_mcp_req_str(rq, "texto", "")); +} + +static const TbMcpTool T_SOMA = { "soma", "Soma", "Soma a e b", + "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"number\"},\"b\":{\"type\":\"number\"}}}", + TB_MCP_READ_ONLY | TB_MCP_IDEMPOTENT, soma }; +static const TbMcpTool T_ECO = { "eco", "Eco", "Devolve o texto", + "{\"type\":\"object\",\"properties\":{\"texto\":{\"type\":\"string\"}}}", 0, eco }; + +#define MODERN_META "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"," \ + "\"io.modelcontextprotocol/clientCapabilities\":{}," \ + "\"io.modelcontextprotocol/clientInfo\":{\"name\":\"teste\",\"version\":\"1\"}}" + +static void sleep_ms(long ms) { + struct timespec ts = { ms / 1000, (ms % 1000) * 1000000L }; + nanosleep(&ts, NULL); +} + +static bool has(const char* s, const char* sub) { return s && strstr(s, sub); } + +/* Pedido HTTP cru; devolve status e corpo (malloc) */ +static int http(int port, const char* method, const char* extra_headers, const char* body, char** out) { + int fd = socket(AF_INET, SOCK_STREAM, 0); + struct sockaddr_in a; + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_port = htons((unsigned short)port); + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + for (int i = 0; i < 50 && connect(fd, (struct sockaddr*)&a, sizeof(a)) != 0; i++) sleep_ms(20); + char req[4096]; + int n = snprintf(req, sizeof(req), "%s /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\n%sContent-Length: %zu\r\n\r\n%s", + method, extra_headers ? extra_headers : "", body ? strlen(body) : 0, body ? body : ""); + send(fd, req, (size_t)n, 0); + size_t cap = 65536, len = 0; + char* buf = malloc(cap); + ssize_t r; + while ((r = recv(fd, buf + len, cap - len - 1, 0)) > 0) len += (size_t)r; + buf[len] = 0; + close(fd); + int status = 0; + sscanf(buf, "HTTP/1.1 %d", &status); + char* b = strstr(buf, "\r\n\r\n"); + *out = strdup(b ? b + 4 : ""); + free(buf); + return status; +} + +int main(void) { + int calls = 0; + TbMcpServer* s = tb_mcp_server_new("tb-teste", "9.9", "Servidor de teste."); + tb_mcp_server_add_tool(s, &T_SOMA, &calls); + tb_mcp_server_add_tool(s, &T_ECO, NULL); + int st; + char* r; + + /* -- era moderna (2026-07-28) -- */ + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":\"d1\",\"method\":\"server/discover\",\"params\":{" MODERN_META "}}", NULL, &st); + CHECK(st == 200 && has(r, "\"id\":\"d1\"") && has(r, "\"supportedVersions\":[\"2026-07-28\"") && + has(r, "\"resultType\":\"complete\"") && has(r, "\"io.modelcontextprotocol/serverInfo\":{\"name\":\"tb-teste\"") && + has(r, "\"instructions\":\"Servidor de teste.\""), "moderno: server/discover"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{" MODERN_META "}}", NULL, &st); + CHECK(st == 200 && has(r, "\"name\":\"soma\"") && has(r, "\"name\":\"eco\"") && has(r, "\"readOnlyHint\":true") && + has(r, "\"ttlMs\":") && has(r, "\"cacheScope\":\"private\"") && strstr(r, "soma") < strstr(r, "\"eco\""), + "moderno: tools/list (ordem fixa, dicas, cache)"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\"," + "\"arguments\":{\"a\":2,\"b\":40}," MODERN_META "}}", NULL, &st); + CHECK(st == 200 && has(r, "\"structuredContent\":{\"soma\":42}") && has(r, "\"text\":\"{\\\"soma\\\":42}\"") && + has(r, "\"isError\":false") && calls == 1, "moderno: tools/call com resultado estruturado (e o JSON em texto)"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\"," + "\"arguments\":{}," MODERN_META "}}", NULL, &st); + CHECK(has(r, "\"isError\":true") && has(r, "falta o argumento a"), "erro da ferramenta: isError com a mensagem"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\",\"params\":{\"name\":\"nao\"," MODERN_META "}}", NULL, &st); + CHECK(has(r, "\"code\":-32602") && has(r, "Ferramenta desconhecida"), "ferramenta desconhecida: -32602"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"tools/list\",\"params\":{\"_meta\":{" + "\"io.modelcontextprotocol/protocolVersion\":\"1900-01-01\"," + "\"io.modelcontextprotocol/clientCapabilities\":{}}}}", NULL, &st); + CHECK(st == 400 && has(r, "\"code\":-32022") && has(r, "\"supported\":[\"2026-07-28\"]") && + has(r, "\"requested\":\"1900-01-01\""), "versão desconhecida: -32022 com as suportadas"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/list\",\"params\":{\"_meta\":{" + "\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"}}}", NULL, &st); + CHECK(st == 400 && has(r, "\"code\":-32602"), "sem clientCapabilities: -32602 (400)"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"x/y\",\"params\":{" MODERN_META "}}", NULL, &st); + CHECK(st == 404 && has(r, "\"code\":-32601"), "método desconhecido: -32601 (404)"); + free(r); + r = tb_mcp_server_handle(s, "{quebrado", NULL, &st); + CHECK(st == 400 && has(r, "\"code\":-32700"), "JSON inválido: -32700"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{}}", NULL, &st); + CHECK(!r && st == 202, "notificação: sem resposta (202)"); + + /* cabecalhos HTTP espelham o corpo */ + const char* call = "{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"tools/call\",\"params\":{\"name\":\"eco\"," + "\"arguments\":{\"texto\":\"oi\"}," MODERN_META "}}"; + TbMcpHttpHeaders h = { "2026-07-28", "tools/call", "eco" }; + r = tb_mcp_server_handle(s, call, &h, &st); + CHECK(st == 200 && has(r, "eco: oi"), "HTTP: cabeçalhos certos passam"); + free(r); + h.name = "=?base64?ZWNv?="; /* "eco" em base64 */ + r = tb_mcp_server_handle(s, call, &h, &st); + CHECK(st == 200 && has(r, "eco: oi"), "HTTP: Mcp-Name em base64 é decodificado"); + free(r); + h.name = "soma"; + r = tb_mcp_server_handle(s, call, &h, &st); + CHECK(st == 400 && has(r, "\"code\":-32020"), "HTTP: Mcp-Name diferente do corpo: -32020"); + free(r); + h.name = "eco"; h.method = NULL; + r = tb_mcp_server_handle(s, call, &h, &st); + CHECK(st == 400 && has(r, "\"code\":-32020"), "HTTP: sem Mcp-Method: -32020"); + free(r); + h.method = "tools/call"; h.protocol_version = "2025-11-25"; + r = tb_mcp_server_handle(s, call, &h, &st); + CHECK(st == 400 && has(r, "\"code\":-32020"), "HTTP: versão do cabeçalho diferente do _meta: -32020"); + free(r); + + /* -- era antiga (initialize) -- */ + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{" + "\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}," + "\"clientInfo\":{\"name\":\"velho\",\"version\":\"1\"}}}", NULL, &st); + CHECK(st == 200 && has(r, "\"protocolVersion\":\"2025-06-18\"") && has(r, "\"serverInfo\":{\"name\":\"tb-teste\"") && + has(r, "\"tools\":{"), "antigo: initialize negocia a versão pedida"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{" + "\"protocolVersion\":\"2099-01-01\",\"capabilities\":{}}}", NULL, &st); + CHECK(has(r, "\"protocolVersion\":\"2025-11-25\""), "antigo: versão desconhecida no initialize -> a mais nova antiga"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"eco\"," + "\"arguments\":{\"texto\":\"velho\"}}}", NULL, &st); + CHECK(st == 200 && has(r, "eco: velho"), "antigo: tools/call sem _meta"); + free(r); + r = tb_mcp_server_handle(s, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\"}", NULL, &st); + CHECK(st == 200 && has(r, "\"result\""), "antigo: ping"); + free(r); + + /* -- stdio -- */ + { + const char* in_text = + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{}}}\n" + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n" + "\n" + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"eco\",\"arguments\":{\"texto\":\"linha\"}}}\n"; + FILE* in = fmemopen((void*)in_text, strlen(in_text), "r"); + char* outbuf = NULL; + size_t outlen = 0; + FILE* out = open_memstream(&outbuf, &outlen); + int n = tb_mcp_server_serve_stdio(s, in, out); + fclose(in); + fclose(out); + CHECK(n == 2 && has(outbuf, "\"id\":1") && has(outbuf, "eco: linha") && strchr(outbuf, '\n') < strrchr(outbuf, '\n'), + "stdio: uma resposta por linha, notificação sem resposta"); + free(outbuf); + } + + /* -- HTTP de verdade -- */ + CHECK(tb_mcp_server_listen(s, 0) && tb_mcp_server_port(s) > 0, "HTTP: escuta numa porta livre de 127.0.0.1"); + int port = tb_mcp_server_port(s); + fflush(stdout); + pid_t child = fork(); + if (child == 0) { for (;;) { tb_mcp_server_poll(s); sleep_ms(2); } } + char* b = NULL; + char hdr[512]; + snprintf(hdr, sizeof(hdr), "Content-Type: application/json\r\nAccept: application/json, text/event-stream\r\n" + "MCP-Protocol-Version: 2026-07-28\r\nMcp-Method: tools/call\r\nMcp-Name: soma\r\n"); + st = http(port, "POST", hdr, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\"," + "\"arguments\":{\"a\":1,\"b\":1}," MODERN_META "}}", &b); + CHECK(st == 200 && has(b, "\"soma\":2"), "HTTP: POST /mcp moderno"); + free(b); + st = http(port, "POST", "MCP-Protocol-Version: 2026-07-28\r\nMcp-Method: tools/list\r\n", + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"soma\"," MODERN_META "}}", &b); + CHECK(st == 400 && has(b, "-32020"), "HTTP: cabeçalho que não bate dá 400 HeaderMismatch"); + free(b); + st = http(port, "POST", "Origin: http://malicioso.example\r\n", "{}", &b); + CHECK(st == 403, "HTTP: Origin de fora dá 403"); + free(b); + st = http(port, "POST", "Origin: http://localhost:5173\r\n", + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-03-26\",\"capabilities\":{}}}", &b); + CHECK(st == 200 && has(b, "\"protocolVersion\":\"2025-03-26\""), "HTTP: Origin local e initialize antigo"); + free(b); + st = http(port, "POST", NULL, "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", &b); + CHECK(st == 202 && !b[0], "HTTP: notificação dá 202 sem corpo"); + free(b); + st = http(port, "GET", NULL, NULL, &b); + CHECK(st == 405, "HTTP: GET dá 405 (sem stream nem sessão)"); + free(b); + kill(child, SIGTERM); + waitpid(child, NULL, 0); + + tb_mcp_server_free(s); + printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); + return fails != 0; +} diff --git a/tests/mcp_test.c b/tests/mcp_test.c index e7e0413..7a48db9 100644 --- a/tests/mcp_test.c +++ b/tests/mcp_test.c @@ -10,6 +10,8 @@ #include #include #include +#include +#include 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) @@ -44,6 +46,28 @@ static void stop_http(pid_t pid) { waitpid(pid, NULL, 0); } +/* -- Servidor moderno (tinyblocks-mcp-server), para o cliente falar 2026-07-28 -- */ +static void srv_soma(void* user, TbMcpRequest* rq) { + (void)user; + tb_mcp_req_text(rq, "%g", tb_mcp_req_num(rq, "a", 0) + tb_mcp_req_num(rq, "b", 0)); +} +static void srv_eco(void* user, TbMcpRequest* rq) { + (void)user; + tb_mcp_req_text(rq, "%s", tb_mcp_req_str(rq, "message", "")); +} +static void srv_falha(void* user, TbMcpRequest* rq) { (void)user; tb_mcp_req_error(rq, "falhou no moderno"); } +static const TbMcpTool SRV_TOOLS[] = { + { "add", NULL, "Soma", "{\"type\":\"object\"}", TB_MCP_READ_ONLY, srv_soma }, + { "echo", NULL, "Eco", "{\"type\":\"object\"}", TB_MCP_READ_ONLY, srv_eco }, + { "fail", NULL, "Falha", "{\"type\":\"object\"}", 0, srv_falha }, + { "ação", NULL, "Nome com acento (vai em base64 no Mcp-Name)", "{\"type\":\"object\"}", 0, srv_eco }, +}; +static TbMcpServer* modern_server(void) { + TbMcpServer* s = tb_mcp_server_new("tb-moderno", "2.0", ""); + for (size_t i = 0; i < sizeof(SRV_TOOLS) / sizeof(SRV_TOOLS[0]); i++) tb_mcp_server_add_tool(s, &SRV_TOOLS[i], NULL); + return s; +} + /* Bateria comum a todos os transportes */ static void suite(const char* label, const char* url, bool can_crash) { char msg[256]; @@ -108,7 +132,12 @@ static void suite(const char* label, const char* url, bool can_crash) { } int main(int argc, char** argv) { - (void)argc; + if (argc > 1 && !strcmp(argv[1], "--serve-stdio")) { /* servidor moderno por stdio */ + TbMcpServer* s = modern_server(); + tb_mcp_server_serve_stdio(s, stdin, stdout); + tb_mcp_server_free(s); + return 0; + } /* 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; } @@ -119,6 +148,56 @@ int main(int argc, char** argv) { char url[600]; snprintf(url, sizeof(url), "stdio://python3 %s --stdio", g_server); suite("stdio", url, true); + { + bool ok2; + char* era = tb_mcp_protocol(url, &ok2); + CHECK(ok2 && era && strstr(era, "antiga"), "stdio: servidor antigo detectado (sonda + initialize)"); + free(era); + } + + /* cliente moderno contra o servidor moderno (tinyblocks-mcp-server) */ + { + char surl[700]; + snprintf(surl, sizeof(surl), "stdio://%s --serve-stdio", argv[0]); + bool ok2; + char* era = tb_mcp_protocol(surl, &ok2); + CHECK(ok2 && era && strstr(era, "moderna (2026-07-28)"), "moderno/stdio: server/discover, sem initialize"); + free(era); + char* r2 = tb_mcp_call_tool(surl, "add", "{\"a\": 40, \"b\": 2}", &ok2); + CHECK(ok2 && r2 && !strcmp(r2, "42"), "moderno/stdio: tools/call com _meta"); + free(r2); + r2 = tb_mcp_server_info(surl, &ok2); + CHECK(ok2 && r2 && !strcmp(r2, "tb-moderno 2.0"), "moderno/stdio: serverInfo vem do discover"); + free(r2); + r2 = tb_mcp_call_tool(surl, "fail", "{}", &ok2); + CHECK(!ok2 && r2 && strstr(r2, "falhou no moderno"), "moderno/stdio: isError vira erro"); + free(r2); + r2 = tb_mcp_ping(surl, &ok2); + CHECK(ok2, "moderno/stdio: \"ping\" vira server/discover (a era moderna nao tem ping)"); + free(r2); + + TbMcpServer* hs = modern_server(); + int hport = 0; + if (tb_mcp_server_listen(hs, 0)) hport = tb_mcp_server_port(hs); + fflush(stdout); + pid_t hp = hport ? fork() : -1; + if (hp == 0) { + struct timespec ts = { 0, 2000000 }; + for (;;) { tb_mcp_server_poll(hs); nanosleep(&ts, NULL); } + } + snprintf(surl, sizeof(surl), "http://127.0.0.1:%d/mcp", hport); + era = tb_mcp_protocol(surl, &ok2); + CHECK(ok2 && era && strstr(era, "moderna"), "moderno/http: pedido moderno direto (sem sessao)"); + free(era); + r2 = tb_mcp_call_tool(surl, "ação", "{\"message\": \"acentuado\"}", &ok2); + CHECK(ok2 && r2 && !strcmp(r2, "acentuado"), "moderno/http: Mcp-Name em base64 confere com o corpo"); + free(r2); + r2 = tb_mcp_tool_names(surl, &ok2); + CHECK(ok2 && r2 && strstr(r2, "add\necho\nfail"), "moderno/http: tools/list"); + free(r2); + if (hp > 0) { kill(hp, SIGTERM); waitpid(hp, NULL, 0); } + tb_mcp_server_free(hs); + } bool ok; char* r = tb_mcp_ping("stdio://comando-que-nao-existe-xyz", &ok); @@ -133,6 +212,12 @@ int main(int argc, char** argv) { 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); + { + bool ok2; + char* era = tb_mcp_protocol(url, &ok2); + CHECK(ok2 && era && strstr(era, "antiga"), "http: servidor antigo detectado (cai para o initialize)"); + free(era); + } 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");