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

tinyblocks-mcp-server (C, sem Python): servidor MCP nas duas eras do
protocolo. Moderna (2026-07-28): sem handshake, versão e capacidades em
_meta a cada pedido, server/discover, resultType, cabeçalhos
MCP-Protocol-Version/Mcp-Method/Mcp-Name conferidos com o corpo
(HeaderMismatch, UnsupportedProtocolVersion). Antiga: initialize. HTTP só
em 127.0.0.1 (Origin conferido, GET/DELETE 405, sem sessão), sem
bloquear (o editor atende a cada quadro), e stdio. test-mcp-server.

Ferramentas do editor (tb_editor_mcp.c; http://127.0.0.1:7811/mcp,
TINYBLOCKS_MCP_PORT muda a porta, 0 = sem rede): get_editor,
list_block_types, list_stacks (scratchblocks + ids dos blocos),
get_scratchblocks, add_scratchblocks, replace_stack, move_stack,
delete_stack, add_block / move_block (solto, embaixo, num campo ou numa
boca; alone = só o bloco) / delete_block / set_inputs, run / stop /
get_output, new_tab / select_tab, save_project / open_project e ui_tree /
ui_action / ui_type (a interface pela árvore acessível).

O editor exporta e importa scratchblocks por pilha (numa aba existente,
numa posição), e o modelo de blocos fica na API privada para o servidor.
O scratchblocks usa também os rótulos declarados pelas libraries.
Duplicar um bloco C de três bocas copiava só duas.

O cliente (tinyblocks-mcp) fala as duas eras: sonda com server/discover
no stdio, pedido moderno no HTTP, e cai para o initialize com servidores
antigos. test-mcp testa contra o servidor antigo de teste e contra o
moderno (stdio e HTTP); harness cenário 29 usa as ferramentas do editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-23 08:13:24 -03:00
1 parent 10a8099c46
commit 2a2d22a64a
19 files changed
+2669 -116

No files matched your search

+157 -75
View File
@@ -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;
@@ -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 <stdarg.h>
#include <tb_editor_internal.h>
#include <tb_mcp_server.h>
#include <tb_a11y.h>
#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;
}