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

@@ -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;
}