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:
1 parent
10a8099c46
commit
2a2d22a64a
19 files changed
+2669
-116
No files matched your search
@@ -104,6 +104,10 @@ TB_MCP_API char* tb_mcp_server_info(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_server", a, 1, ok);
|
||||
}
|
||||
TB_MCP_API char* tb_mcp_protocol(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_era", a, 1, ok);
|
||||
}
|
||||
TB_MCP_API char* tb_mcp_list_tools(const char* url, bool* ok) {
|
||||
const char* a[] = { url };
|
||||
return py_call("_tbmcp_tools", a, 1, ok);
|
||||
|
||||
@@ -8,18 +8,30 @@
|
||||
# http://... ou https://... "Streamable HTTP": POST com resposta JSON ou SSE,
|
||||
# sessao pelo cabecalho Mcp-Session-Id
|
||||
#
|
||||
# Uma sessao por URL fica aberta entre as chamadas (o initialize acontece uma
|
||||
# vez; o processo stdio continua vivo). As funcoes publicas devolvem texto com
|
||||
# um prefixo: "+" sucesso, "!" erro (o C transforma em erro do TinyBlocks).
|
||||
# Protocolo nas duas eras: a moderna (2026-07-28: sem handshake, cada pedido
|
||||
# leva versao e capacidades em _meta) e a antiga (initialize). A era do
|
||||
# servidor e descoberta uma vez (stdio: sonda com server/discover; HTTP:
|
||||
# pedido moderno, e cai para o initialize se a resposta nao for um erro
|
||||
# moderno). Uma conexao por URL fica aberta entre as chamadas. As funcoes
|
||||
# publicas devolvem texto com um prefixo: "+" sucesso, "!" erro (o C
|
||||
# transforma em erro do TinyBlocks).
|
||||
|
||||
import json as _tbmcp_json
|
||||
|
||||
_TBMCP_PROTOCOL = "2025-06-18"
|
||||
_TBMCP_MODERN = "2026-07-28"
|
||||
_TBMCP_LEGACY = "2025-11-25"
|
||||
_TBMCP_TIMEOUT = 30.0
|
||||
_TBMCP_PROBE_TIMEOUT = 5.0
|
||||
_TBMCP_CLIENT = {"name": "tinyblocks", "version": "1.0.0"}
|
||||
# erros que so um servidor moderno manda (HeaderMismatch, capacidade, versao)
|
||||
_TBMCP_MODERN_ERRORS = (-32020, -32021, -32022)
|
||||
|
||||
|
||||
class _TbMcpError(Exception):
|
||||
pass
|
||||
def __init__(self, text, code=None, data=None):
|
||||
Exception.__init__(self, text)
|
||||
self.code = code
|
||||
self.data = data
|
||||
|
||||
|
||||
def _tbmcp_result(msg):
|
||||
@@ -29,8 +41,18 @@ def _tbmcp_result(msg):
|
||||
err = msg["error"] or {}
|
||||
text = err.get("message", "erro") if isinstance(err, dict) else str(err)
|
||||
code = err.get("code") if isinstance(err, dict) else None
|
||||
raise _TbMcpError(text if code is None else "%s (codigo %s)" % (text, code))
|
||||
return msg.get("result", {})
|
||||
raise _TbMcpError(text if code is None else "%s (codigo %s)" % (text, code),
|
||||
code, err.get("data") if isinstance(err, dict) else None)
|
||||
res = msg.get("result", {})
|
||||
if isinstance(res, dict) and res.get("resultType", "complete") == "input_required":
|
||||
raise _TbMcpError("o servidor pediu informacoes extras (input_required), que este cliente nao suporta")
|
||||
return res
|
||||
|
||||
|
||||
def _tbmcp_meta():
|
||||
return {"io.modelcontextprotocol/protocolVersion": _TBMCP_MODERN,
|
||||
"io.modelcontextprotocol/clientCapabilities": {},
|
||||
"io.modelcontextprotocol/clientInfo": _TBMCP_CLIENT}
|
||||
|
||||
|
||||
def _tbmcp_error_reply(req_id, code, text):
|
||||
@@ -102,12 +124,12 @@ class _TbMcpStdio:
|
||||
def notify(self, method, params):
|
||||
self._send({"jsonrpc": "2.0", "method": method, "params": params})
|
||||
|
||||
def request(self, method, params):
|
||||
def request(self, method, params, timeout=_TBMCP_TIMEOUT):
|
||||
import time
|
||||
rid = self.next_id
|
||||
self.next_id += 1
|
||||
self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
|
||||
deadline = time.monotonic() + _TBMCP_TIMEOUT
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
line = self._readline(deadline).strip()
|
||||
if not line:
|
||||
@@ -146,41 +168,57 @@ class _TbMcpStdio:
|
||||
pass
|
||||
|
||||
|
||||
def _tbmcp_header_value(v):
|
||||
"""Valor de cabecalho: ASCII visivel como esta; o resto em =?base64?...?="""
|
||||
import base64
|
||||
plain = all(0x20 <= ord(c) < 0x7f for c in v) and v == v.strip() and \
|
||||
not (v.startswith("=?base64?") and v.endswith("?="))
|
||||
return v if plain else "=?base64?" + base64.b64encode(v.encode("utf-8")).decode("ascii") + "?="
|
||||
|
||||
|
||||
class _TbMcpHttp:
|
||||
def __init__(self, url):
|
||||
self.url = url
|
||||
self.session = None
|
||||
self.proto = None
|
||||
self.modern = False
|
||||
self.next_id = 1
|
||||
|
||||
def alive(self):
|
||||
return True
|
||||
|
||||
def _headers(self):
|
||||
def _headers(self, obj):
|
||||
h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
|
||||
if self.session:
|
||||
if self.session and not self.modern:
|
||||
h["Mcp-Session-Id"] = self.session
|
||||
if self.proto:
|
||||
h["MCP-Protocol-Version"] = self.proto
|
||||
if self.modern and isinstance(obj, dict) and "method" in obj:
|
||||
h["Mcp-Method"] = obj["method"]
|
||||
p = obj.get("params") or {}
|
||||
name = p.get("name", p.get("uri")) if obj["method"] in ("tools/call", "resources/read", "prompts/get") else None
|
||||
if isinstance(name, str):
|
||||
h["Mcp-Name"] = _tbmcp_header_value(name)
|
||||
return h
|
||||
|
||||
def _open(self, obj, method="POST"):
|
||||
import urllib.request, urllib.error
|
||||
data = _tbmcp_json.dumps(obj).encode("utf-8") if obj is not None else None
|
||||
req = urllib.request.Request(self.url, data=data, headers=self._headers(), method=method)
|
||||
req = urllib.request.Request(self.url, data=data, headers=self._headers(obj), method=method)
|
||||
try:
|
||||
return urllib.request.urlopen(req, timeout=_TBMCP_TIMEOUT)
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = ""
|
||||
detail, code, data = "", None, None
|
||||
try: # corpo JSON-RPC com a mensagem do erro
|
||||
body = _tbmcp_json.loads(e.read().decode("utf-8", "replace"))
|
||||
if isinstance(body, dict) and isinstance(body.get("error"), dict):
|
||||
detail = ": " + str(body["error"].get("message", ""))
|
||||
code, data = body["error"].get("code"), body["error"].get("data")
|
||||
except Exception:
|
||||
pass
|
||||
if e.code == 404 and self.session:
|
||||
if e.code == 404 and self.session and not self.modern:
|
||||
raise _TbMcpError("sessao expirada (HTTP 404)")
|
||||
raise _TbMcpError("HTTP %d %s%s" % (e.code, e.reason, detail))
|
||||
raise _TbMcpError("HTTP %d %s%s" % (e.code, e.reason, detail), code, data)
|
||||
except urllib.error.URLError as e:
|
||||
raise _TbMcpError("nao consegui conectar em %s: %s" % (self.url, e.reason))
|
||||
except OSError as e:
|
||||
@@ -240,13 +278,13 @@ class _TbMcpHttp:
|
||||
def notify(self, method, params):
|
||||
self._post({"jsonrpc": "2.0", "method": method, "params": params}, None)
|
||||
|
||||
def request(self, method, params):
|
||||
def request(self, method, params, timeout=None):
|
||||
rid = self.next_id
|
||||
self.next_id += 1
|
||||
return self._post({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}, rid)
|
||||
|
||||
def close(self):
|
||||
if not self.session:
|
||||
if not self.session or self.modern:
|
||||
return
|
||||
try:
|
||||
self._open(None, "DELETE").close()
|
||||
@@ -257,28 +295,70 @@ class _TbMcpHttp:
|
||||
class _TbMcpSession:
|
||||
def __init__(self, url):
|
||||
if url.startswith("stdio://"):
|
||||
self.t = _TbMcpStdio(url[len("stdio://"):])
|
||||
self.cmd = url[len("stdio://"):]
|
||||
self.t = _TbMcpStdio(self.cmd)
|
||||
elif url.startswith("http://") or url.startswith("https://"):
|
||||
self.cmd = None
|
||||
self.t = _TbMcpHttp(url)
|
||||
else:
|
||||
raise _TbMcpError("endereco invalido (use stdio://comando ou http://...): %s" % url)
|
||||
self.modern = False
|
||||
self.info = {}
|
||||
try:
|
||||
res = _tbmcp_result(self.t.request("initialize", {
|
||||
"protocolVersion": _TBMCP_PROTOCOL,
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "tinyblocks", "version": "1.0.0"},
|
||||
}))
|
||||
self.info = res.get("serverInfo", {}) or {}
|
||||
self.t.proto = res.get("protocolVersion") or _TBMCP_PROTOCOL
|
||||
self.t.notify("notifications/initialized", {})
|
||||
if not self._probe_modern():
|
||||
if self.cmd is not None and not self.t.alive(): # a sonda derrubou um servidor antigo
|
||||
self.t.close()
|
||||
self.t = _TbMcpStdio(self.cmd)
|
||||
self._legacy_init()
|
||||
except Exception:
|
||||
self.t.close()
|
||||
raise
|
||||
|
||||
def _probe_modern(self):
|
||||
"""server/discover com _meta moderno: sucesso ou erro moderno = servidor moderno."""
|
||||
if self.cmd is None:
|
||||
self.t.modern = True
|
||||
self.t.proto = _TBMCP_MODERN
|
||||
try:
|
||||
res = _tbmcp_result(self.t.request("server/discover", {"_meta": _tbmcp_meta()},
|
||||
timeout=_TBMCP_PROBE_TIMEOUT))
|
||||
except _TbMcpError as e:
|
||||
self.t.modern = False
|
||||
self.t.proto = None
|
||||
if e.code in _TBMCP_MODERN_ERRORS:
|
||||
sup = (e.data or {}).get("supported", []) if isinstance(e.data, dict) else []
|
||||
raise _TbMcpError("o servidor so fala as versoes %s do MCP" % ", ".join(sup) if sup else str(e))
|
||||
return False
|
||||
if _TBMCP_MODERN not in (res.get("supportedVersions") or []):
|
||||
self.t.modern = False
|
||||
self.t.proto = None
|
||||
return False
|
||||
self.modern = True
|
||||
self.t.modern = True
|
||||
self.t.proto = _TBMCP_MODERN
|
||||
meta = res.get("_meta") or {}
|
||||
self.info = meta.get("io.modelcontextprotocol/serverInfo") or {}
|
||||
return True
|
||||
|
||||
def _legacy_init(self):
|
||||
res = _tbmcp_result(self.t.request("initialize", {
|
||||
"protocolVersion": _TBMCP_LEGACY,
|
||||
"capabilities": {},
|
||||
"clientInfo": _TBMCP_CLIENT,
|
||||
}))
|
||||
self.info = res.get("serverInfo", {}) or {}
|
||||
self.t.proto = res.get("protocolVersion") or _TBMCP_LEGACY
|
||||
self.t.notify("notifications/initialized", {})
|
||||
|
||||
def alive(self):
|
||||
return self.t.alive()
|
||||
|
||||
def call(self, method, params):
|
||||
if self.modern:
|
||||
if method == "ping": # a era moderna nao tem ping
|
||||
method = "server/discover"
|
||||
params = dict(params)
|
||||
params["_meta"] = _tbmcp_meta()
|
||||
return _tbmcp_result(self.t.request(method, params))
|
||||
|
||||
def close(self):
|
||||
@@ -359,6 +439,12 @@ def _tbmcp_server(url):
|
||||
return ("%s %s" % (info.get("name", "?"), info.get("version", ""))).strip()
|
||||
|
||||
|
||||
@_tbmcp_api
|
||||
def _tbmcp_era(url):
|
||||
s = _tbmcp_session(url.strip())
|
||||
return "moderna (%s)" % _TBMCP_MODERN if s.modern else "antiga (%s)" % (s.t.proto or "?")
|
||||
|
||||
|
||||
def _tbmcp_all_tools(url):
|
||||
tools, cursor = [], None
|
||||
for _ in range(100): # paginas
|
||||
|
||||
Reference in new issue
Block a user