MCP funcionando: cliente conforme o protocolo, blocos na library e testes
A tinyblocks-mcp passa a ser uma library de blocos (categoria MCP, carregável pelas Bibliotecas): "servidor MCP %1 responde?", nome do servidor, ferramentas, nomes das ferramentas e "chame %2 do servidor MCP %1 com %3". Falha vira erro do TinyBlocks (pega no "se der erro" e no "tente obter"); só o "responde?" nunca falha. Cliente (Python embutido, tudo sob _tbmcp_ no __main__): - uma sessão por servidor: initialize uma vez, processo stdio vivo, reconecta se o servidor cair - stdio: shlex, ignora notificações e linhas que não são JSON-RPC, responde ping do servidor, tempo limite, stderr do servidor no erro - Streamable HTTP: Mcp-Session-Id, MCP-Protocol-Version, resposta JSON ou SSE, DELETE ao fechar - lista paginada; conteúdo de texto, imagem, recurso e estruturado; isError e erros JSON-RPC viram mensagens em português Corrige o carregamento do módulo (o vetor do xxd não termina em \0) e o build (lib-mcp depende de lib-python). O plugin examples/mcp saiu: os blocos vivem na library. test-mcp: servidor de teste próprio (tests/mcp_server.py) por stdio, HTTP e HTTP+SSE, com notificações no meio, ping do servidor, log que não é JSON, paginação, falhas e queda do servidor; e os blocos. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2d580005b1
commit
11d6e5317b
9 files changed
+986
-207
No files matched your search
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Servidor MCP de teste (sem dependencias), para o test-mcp.
|
||||
|
||||
python3 tests/mcp_server.py --stdio
|
||||
python3 tests/mcp_server.py --http PORTA [--sse]
|
||||
|
||||
Coisas dificeis de proposito: notificacoes antes de cada resposta, um pedido
|
||||
"ping" do servidor no meio de tools/call, uma linha de log que nao e JSON (stdio),
|
||||
lista de ferramentas paginada, ferramenta que falha (isError) e ferramenta que
|
||||
derruba o servidor (o cliente deve reconectar).
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
PROTOCOL = "2025-06-18"
|
||||
|
||||
TOOLS = [
|
||||
{"name": "echo", "description": "Devolve a mensagem.\nSegunda linha da descricao.",
|
||||
"inputSchema": {"type": "object", "properties": {"message": {"type": "string"}}}},
|
||||
{"name": "add", "description": "Soma a e b.",
|
||||
"inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}},
|
||||
{"name": "fail", "description": "Sempre falha.", "inputSchema": {"type": "object"}},
|
||||
{"name": "image", "description": "Devolve uma imagem.", "inputSchema": {"type": "object"}},
|
||||
{"name": "crash", "description": "Derruba o servidor.", "inputSchema": {"type": "object"}},
|
||||
]
|
||||
PAGE = 3
|
||||
|
||||
|
||||
def text(t):
|
||||
return [{"type": "text", "text": t}]
|
||||
|
||||
|
||||
def call_tool(name, args):
|
||||
"""-> (result, crash)"""
|
||||
if name == "echo":
|
||||
return {"content": text(str(args.get("message", "")))}, False
|
||||
if name == "add":
|
||||
s = args.get("a", 0) + args.get("b", 0)
|
||||
return {"content": text(str(int(s) if float(s).is_integer() else s))}, False
|
||||
if name == "fail":
|
||||
return {"content": text("falhou de propósito"), "isError": True}, False
|
||||
if name == "image":
|
||||
return {"content": [{"type": "image", "data": "iVBORw0KGgo=", "mimeType": "image/png"},
|
||||
{"type": "text", "text": "legenda"}]}, False
|
||||
if name == "crash":
|
||||
return None, True
|
||||
return None, False
|
||||
|
||||
|
||||
def handle(msg):
|
||||
"""Mensagem do cliente -> (resposta ou None, crash)"""
|
||||
method = msg.get("method")
|
||||
rid = msg.get("id")
|
||||
if rid is None:
|
||||
return None, False # notificacao
|
||||
p = msg.get("params") or {}
|
||||
if method == "initialize":
|
||||
res = {"protocolVersion": PROTOCOL, "capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "tb-teste", "version": "0.1"}}
|
||||
elif method == "ping":
|
||||
res = {}
|
||||
elif method == "tools/list":
|
||||
start = int(p.get("cursor") or 0)
|
||||
res = {"tools": TOOLS[start:start + PAGE]}
|
||||
if start + PAGE < len(TOOLS):
|
||||
res["nextCursor"] = str(start + PAGE)
|
||||
elif method == "tools/call":
|
||||
res, crash = call_tool(p.get("name"), p.get("arguments") or {})
|
||||
if crash:
|
||||
return None, True
|
||||
if res is None:
|
||||
return {"jsonrpc": "2.0", "id": rid,
|
||||
"error": {"code": -32602, "message": "ferramenta desconhecida: %s" % p.get("name")}}, False
|
||||
else:
|
||||
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "metodo desconhecido"}}, False
|
||||
return {"jsonrpc": "2.0", "id": rid, "result": res}, False
|
||||
|
||||
|
||||
LOG = {"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "processando"}}
|
||||
|
||||
|
||||
def run_stdio():
|
||||
out = sys.stdout
|
||||
|
||||
def send(obj):
|
||||
out.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
out.flush()
|
||||
|
||||
server_req = 1000
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
msg = json.loads(line)
|
||||
if "method" not in msg:
|
||||
continue # resposta do cliente (ao nosso ping)
|
||||
if msg.get("method") == "tools/call":
|
||||
out.write("log do servidor que nao e JSON\n")
|
||||
send({"jsonrpc": "2.0", "id": server_req, "method": "ping"}) # cliente deve responder
|
||||
server_req += 1
|
||||
reply = json.loads(sys.stdin.readline())
|
||||
if reply.get("result") != {}:
|
||||
send({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -1, "message": "cliente nao respondeu o ping"}})
|
||||
continue
|
||||
resp, crash = handle(msg)
|
||||
if crash:
|
||||
sys.exit(3)
|
||||
if resp is not None:
|
||||
send(LOG)
|
||||
send(resp)
|
||||
|
||||
|
||||
def run_http(port, sse):
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sessions = set()
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _reply(self, code, body=None, ctype="application/json", headers=None):
|
||||
data = body.encode("utf-8") if body is not None else b""
|
||||
self.send_response(code)
|
||||
for k, v in (headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
if body is not None:
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_DELETE(self):
|
||||
sessions.discard(self.headers.get("Mcp-Session-Id"))
|
||||
self._reply(200)
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/mcp":
|
||||
return self._reply(404, json.dumps({"error": "nao achei"}))
|
||||
accept = self.headers.get("Accept", "")
|
||||
if "application/json" not in accept or "text/event-stream" not in accept:
|
||||
return self._reply(406, json.dumps({"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32000, "message": "Accept incompleto"}}))
|
||||
msg = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))).decode("utf-8"))
|
||||
headers = {}
|
||||
if msg.get("method") == "initialize":
|
||||
sid = uuid.uuid4().hex
|
||||
sessions.add(sid)
|
||||
headers["Mcp-Session-Id"] = sid
|
||||
else:
|
||||
sid = self.headers.get("Mcp-Session-Id")
|
||||
if sid not in sessions:
|
||||
return self._reply(404, json.dumps({"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32001, "message": "sessao desconhecida"}}))
|
||||
if self.headers.get("MCP-Protocol-Version") != PROTOCOL:
|
||||
return self._reply(400, json.dumps({"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32000, "message": "sem MCP-Protocol-Version"}}))
|
||||
if "method" not in msg or msg.get("id") is None:
|
||||
return self._reply(202, None, headers=headers)
|
||||
resp, crash = handle(msg)
|
||||
if crash:
|
||||
return self._reply(500, json.dumps({"jsonrpc": "2.0", "id": msg.get("id"),
|
||||
"error": {"code": -32603, "message": "o servidor caiu"}}))
|
||||
if sse:
|
||||
body = ": aquecendo\n\n" + "event: message\ndata: " + json.dumps(LOG) + "\n\n" + \
|
||||
"event: message\ndata: " + json.dumps(resp, ensure_ascii=False) + "\n\n"
|
||||
return self._reply(200, body, "text/event-stream", headers)
|
||||
self._reply(200, json.dumps(resp, ensure_ascii=False), "application/json", headers)
|
||||
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", port), H)
|
||||
print("pronto", flush=True)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "--stdio" in sys.argv:
|
||||
run_stdio()
|
||||
elif "--http" in sys.argv:
|
||||
run_http(int(sys.argv[sys.argv.index("--http") + 1]), "--sse" in sys.argv)
|
||||
else:
|
||||
print(__doc__)
|
||||
Reference in new issue
Block a user