Skip to main content

aylis_remote/mcp/
mod.rs

1//! O app como servidor MCP (Model Context Protocol): um agente de IA (Claude Code, Claude
2//! Desktop e outros) usa o app pelos componentes, sem olhar a tela nem mandar cliques para a
3//! janela. Dois componentes não visuais:
4//!
5//! - [`McpServer`]: liga o servidor (HTTP em `127.0.0.1`, com token). Com `expose_ui`, dá ao
6//!   agente as ferramentas genéricas de tela (`ui_forms`, `ui_tree`, `ui_get`, `ui_set`,
7//!   `ui_click`, `ui_type`, `ui_rows`...), que são os comandos do protocolo remoto; com
8//!   `read_only`, só as que leem.
9//! - [`McpTool`] (filho do servidor): uma ferramenta do domínio do app, com nome, descrição e
10//!   parâmetros; o agente chama e o `on_execute` responde.
11//!   É aqui que mora a regra de negócio: `criar_pedido(cliente, itens)` em vez de
12//!   preencher campo por campo.
13//!
14//! Tudo roda na thread da interface: a conexão chega numa thread, a chamada vai pelo
15//! [`Poster`] e a resposta volta por um canal (até `call_timeout`). O `on_call` do servidor vê
16//! cada chamada antes (o registro, ou recusar: a resposta do agente é o erro).
17//!
18//! Para conectar o Claude Code: o método `client_command` devolve a linha
19//! (`claude mcp add --transport http ...`, com o endereço e o token; com o `claude` fora do
20//! PATH, pelo caminho completo: [`claude_executable`]).
21
22pub mod http;
23
24use std::sync::Arc;
25use std::sync::mpsc;
26use std::time::Duration;
27
28use aylis_core::prop::PropKind;
29use aylis_core::{Answer, Asked, Component, ComponentId, EventArgs, EventCtx, MethodInfo, Poster, PropValue, Ui, properties};
30use serde_json::{Map, Value, json};
31
32/// O executável do Claude Code achado nesta máquina.
33#[derive(Clone, Debug, PartialEq)]
34pub struct ClaudeCode {
35    pub path: std::path::PathBuf,
36    /// Está no PATH (um terminal comum roda `claude`); fora dele, só pelo caminho completo.
37    pub in_path: bool,
38}
39
40/// Acha o `claude` (o Claude Code): no PATH e, fora dele, nos lugares em que os instaladores
41/// põem (`~/.local/bin`, `~/.claude/local`, o npm global) e no que vem com o Claude Desktop
42/// (`%APPDATA%\Claude\claude-code\<versão>\...\claude.exe`, a versão mais nova). No navegador,
43/// nenhum.
44pub fn claude_executable() -> Option<ClaudeCode> {
45    use std::path::{Path, PathBuf};
46    let names: &[&str] = if cfg!(windows) { &["claude.exe", "claude.cmd", "claude"] } else { &["claude"] };
47    let first_in = |dir: &Path| names.iter().map(|n| dir.join(n)).find(|p| p.is_file());
48    if let Some(paths) = std::env::var_os("PATH") {
49        if let Some(path) = std::env::split_paths(&paths).find_map(|d| first_in(&d)) {
50            return Some(ClaudeCode { path, in_path: true });
51        }
52    }
53    let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
54    let mut dirs: Vec<PathBuf> = Vec::new();
55    if let Some(home) = &home {
56        dirs.push(home.join(".local").join("bin"));
57        dirs.push(home.join(".claude").join("local"));
58    }
59    if let Some(appdata) = std::env::var_os("APPDATA").filter(|_| cfg!(windows)) {
60        dirs.push(PathBuf::from(appdata).join("npm"));
61    }
62    if let Some(path) = dirs.iter().find_map(|d| first_in(d)) {
63        return Some(ClaudeCode { path, in_path: false });
64    }
65    // O que vem com o Claude Desktop: claude-code/<versão>/<marca>/claude(.exe).
66    let bundled = if cfg!(windows) {
67        std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("Claude").join("claude-code"))
68    } else if cfg!(target_os = "macos") {
69        home.as_ref().map(|h| h.join("Library/Application Support/Claude/claude-code"))
70    } else {
71        None
72    }?;
73    let version = |p: &Path| -> Vec<u64> { p.file_name().map(|n| n.to_string_lossy().split('.').map(|s| s.parse().unwrap_or(0)).collect()).unwrap_or_default() };
74    let mut versions: Vec<PathBuf> = std::fs::read_dir(&bundled).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
75    versions.sort_by_key(|p| std::cmp::Reverse(version(p)));
76    versions.iter().find_map(|v| {
77        let inner = std::fs::read_dir(v).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir());
78        std::iter::once(v.clone()).chain(inner).find_map(|d| first_in(&d))
79    })
80    .map(|path| ClaudeCode { path, in_path: false })
81}
82
83/// A versão do MCP que o aylis fala.
84pub const PROTOCOL: &str = "2025-06-18";
85
86/// O tempo padrão para uma chamada responder, em milissegundos.
87const DEFAULT_TIMEOUT: u32 = 30_000;
88
89/// As ferramentas de tela que só leem (as que `read_only` deixa).
90const READ_TOOLS: &[&str] = &["ui_forms", "ui_tree", "ui_get", "ui_items", "ui_rows"];
91
92/// As operações de dados que não mudam registros (as que `read_only` deixa no `ui_data`).
93const READ_DATA_OPS: &[&str] = &["first", "prior", "next", "last", "move_to", "locate", "value", "text", "record", "info", "field_texts", "field_error", "lookup"];
94
95// ---------------------------------------------------------------------------
96// McpServer
97
98/// Liga o app a agentes de IA pelo MCP. `active` liga (fora do designer); `port` 0 escolhe
99/// uma porta livre (o endereço fica em `url`); `token` vazio gera um aleatório ao ligar.
100/// Só aceita conexões deste computador, com o token.
101///
102/// `expose_ui` dá ao agente as ferramentas genéricas de tela; `read_only` deixa só as que
103/// leem; `forms` (nomes separados por vírgula) limita a quais forms ele chega. O próprio
104/// servidor e as ferramentas nunca são alcançáveis por elas (o agente não se dá mais poder).
105/// As ferramentas do app são os [`McpTool`] filhos.
106///
107/// `on_call` dispara antes de cada chamada (o texto é `{"tool": .., "arguments": ..}`):
108/// recusar ([`Ui::refuse`]) devolve o erro ao agente. `on_error` recebe as falhas ao ligar.
109pub struct McpServer {
110    /// Liga o servidor (fora do designer); desligado, ele para.
111    pub active: bool,
112    /// A porta em `127.0.0.1`; 0: uma porta livre (o endereço fica em `url`).
113    pub port: u32,
114    /// O segredo que o agente precisa mandar; vazio: um aleatório gerado ao ligar.
115    pub token: String,
116    /// O nome que o agente vê (vazio: o nome do componente).
117    pub server_name: String,
118    /// O que o agente lê ao conectar: para que serve o app e como usar as ferramentas.
119    pub instructions: String,
120    /// Dá ao agente as ferramentas genéricas de tela (ler a árvore, mexer em propriedades,
121    /// clicar, os dados).
122    pub expose_ui: bool,
123    /// Das ferramentas de tela, só as que leem (nenhuma muda a tela nem os registros).
124    pub read_only: bool,
125    /// Os forms que o agente alcança, por nome separados por vírgula; vazio: todos.
126    pub forms: String,
127    /// Quanto uma chamada pode demorar, em milissegundos (vale ao ligar).
128    pub call_timeout: u32,
129    running: Option<http::HttpServer>,
130    /// Já tentou ligar com a configuração atual (uma falha não repete a cada volta do timer).
131    attempted: bool,
132    last_error: String,
133}
134
135impl Default for McpServer {
136    fn default() -> Self {
137        Self {
138            active: false,
139            port: 0,
140            token: String::new(),
141            server_name: String::new(),
142            instructions: String::new(),
143            expose_ui: false,
144            read_only: false,
145            forms: String::new(),
146            call_timeout: DEFAULT_TIMEOUT,
147            running: None,
148            attempted: false,
149            last_error: String::new(),
150        }
151    }
152}
153
154impl McpServer {
155    /// O endereço dos clientes (vazio: parado).
156    pub fn url(&self) -> String {
157        self.running.as_ref().map(http::HttpServer::url).unwrap_or_default()
158    }
159
160    pub fn running(&self) -> bool {
161        self.running.is_some()
162    }
163
164    /// A falha da última tentativa de ligar (vazia: nenhuma).
165    pub fn last_error(&self) -> String {
166        self.last_error.clone()
167    }
168
169    /// A linha que liga o Claude Code a este app (vazia: parado). Com o `claude` fora do PATH
170    /// (o que vem com o Claude Desktop, por exemplo), a linha leva o caminho completo dele,
171    /// para rodar num terminal comum.
172    pub fn client_command(&self, ui: &Ui, id: ComponentId) -> String {
173        if self.running.is_none() {
174            return String::new();
175        }
176        let name = self.display_name(ui, id).replace(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_', "-");
177        let claude = match claude_executable() {
178            Some(ClaudeCode { path, in_path: false }) => format!("\"{}\"", path.display()),
179            _ => "claude".to_string(),
180        };
181        format!("{claude} mcp add --transport http {name} {} --header \"Authorization: Bearer {}\"", self.url(), self.token)
182    }
183
184    fn display_name(&self, ui: &Ui, id: ComponentId) -> String {
185        if !self.server_name.trim().is_empty() {
186            return self.server_name.trim().to_string();
187        }
188        ui.name(id).filter(|n| !n.is_empty()).unwrap_or("aylis-app").to_string()
189    }
190
191    fn allowed_forms(&self) -> Vec<String> {
192        self.forms.split([',', ';']).map(str::trim).filter(|f| !f.is_empty()).map(str::to_string).collect()
193    }
194
195    fn set_s(&mut self, _: String) {}
196    fn set_b(&mut self, _: bool) {}
197
198    /// Liga ou desliga conforme `active` (nunca no designer).
199    fn sync(&mut self, ctx: &mut EventCtx<'_>) {
200        if ctx.ui.design_mode() {
201            return;
202        }
203        if !self.active {
204            self.running = None;
205            self.attempted = false;
206            return;
207        }
208        if self.running.is_some() || self.attempted {
209            return;
210        }
211        self.attempted = true;
212        match self.start(ctx.ui.poster(), ctx.id) {
213            Ok(server) => {
214                self.last_error.clear();
215                self.running = Some(server);
216            }
217            Err(e) => {
218                self.last_error = e.clone();
219                ctx.fire("on_error", EventArgs::Text(e));
220            }
221        }
222    }
223
224    fn start(&mut self, poster: Poster, id: ComponentId) -> Result<http::HttpServer, String> {
225        let port = u16::try_from(self.port).map_err(|_| format!("MCP: porta inválida: {}", self.port))?;
226        if self.token.is_empty() {
227            self.token = random_token()?;
228        }
229        let timeout = Duration::from_millis(u64::from(if self.call_timeout == 0 { DEFAULT_TIMEOUT } else { self.call_timeout }));
230        http::start(port, self.token.clone(), "aylis-mcp", Arc::new(move |message| handle_message(message, &poster, id, timeout)))
231    }
232}
233
234impl Component for McpServer {
235    fn class_name(&self) -> &'static str {
236        "McpServer"
237    }
238
239    properties! {
240        active: bool => "Behavior",
241        port: u32 => "Behavior",
242        token: String => "Behavior",
243        server_name: String => "Behavior",
244        instructions: String => "Behavior",
245        expose_ui: bool => "Behavior",
246        read_only: bool => "Behavior",
247        forms: String => "Behavior",
248        call_timeout: u32 as Duration => "Behavior";
249        events: on_call, on_error;
250        computed: url: String => url / set_s, running: bool => running / set_b, last_error: String => last_error / set_s
251    }
252
253    fn methods(&self) -> &'static [MethodInfo] {
254        const METHODS: &[MethodInfo] = &[MethodInfo::new("client_command", &[], Some(PropKind::String))];
255        METHODS
256    }
257
258    fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, _args: &[PropValue]) -> Result<PropValue, String> {
259        match method {
260            "client_command" => Ok(PropValue::String(self.client_command(ctx.ui, ctx.id))),
261            _ => Err(format!("McpServer não tem o método '{method}'")),
262        }
263    }
264
265    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
266        if matches!(name, "port" | "token" | "call_timeout") && self.running.is_some() {
267            // Religa com a configuração nova.
268            self.running = None;
269            self.attempted = false;
270        }
271        if name == "active" {
272            self.attempted = false;
273        }
274        self.sync(ctx);
275    }
276
277    // Carregado de um form com `active` ligado, liga na primeira volta do timer.
278    fn timer_interval(&self) -> Option<f64> {
279        (self.active && self.running.is_none() && !self.attempted).then_some(0.2)
280    }
281
282    fn timer(&mut self, ctx: &mut EventCtx<'_>) {
283        self.sync(ctx);
284    }
285}
286
287#[cfg(not(target_arch = "wasm32"))]
288fn random_token() -> Result<String, String> {
289    let mut bytes = [0u8; 32];
290    getrandom::fill(&mut bytes).map_err(|e| format!("MCP: sem gerador aleatório do sistema: {e}"))?;
291    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
292}
293
294#[cfg(target_arch = "wasm32")]
295fn random_token() -> Result<String, String> {
296    Err("MCP: o navegador não abre portas (use o app de desktop)".into())
297}
298
299// ---------------------------------------------------------------------------
300// McpTool
301
302/// Uma ferramenta do app para o agente (filha de um [`McpServer`]). `tool_name` é o nome que
303/// ele chama (vazio: o nome do componente), `description` diz quando usar, e `params` os
304/// parâmetros: um JSON Schema (`{"type": "object", "properties": {..}}`), só as
305/// propriedades (`{"cliente": {"type": "string"}}`) ou a forma curta
306/// `cliente: string, quantidade: integer, obs?: string` (o `?` marca o opcional).
307///
308/// `on_execute` recebe os argumentos (o texto do evento é o JSON; [`McpTool::arguments`]
309/// lê) e responde com [`McpTool::reply`] (ou `ui.reply("result", ..)`); recusar
310/// ([`Ui::refuse`]) devolve o erro. Um backend em outra linguagem responde depois, como em
311/// todo evento-pergunta. `read_only` avisa o agente que a ferramenta não muda nada.
312pub struct McpTool {
313    /// O nome que o agente chama; vazio: o nome do componente.
314    pub tool_name: String,
315    /// O que a ferramenta faz e quando usar (o agente lê para escolher).
316    pub description: String,
317    /// Os parâmetros: um JSON Schema, só as propriedades ou a forma curta
318    /// `cliente: string, quantidade: integer, obs?: string` (`?`: opcional); vazio: nenhum.
319    pub params: String,
320    /// Avisa o agente que a ferramenta só lê, não muda nada.
321    pub read_only: bool,
322    /// Oferecida ao agente; desligada, ele não a vê.
323    pub enabled: bool,
324}
325
326impl Default for McpTool {
327    fn default() -> Self {
328        Self { tool_name: String::new(), description: String::new(), params: String::new(), read_only: false, enabled: true }
329    }
330}
331
332impl McpTool {
333    /// Os argumentos que o agente mandou (no `on_execute`).
334    pub fn arguments(args: &EventArgs) -> Value {
335        args.text().and_then(|t| serde_json::from_str(t).ok()).unwrap_or_else(|| json!({}))
336    }
337
338    /// Responde o `on_execute`: um texto, ou JSON (vai como texto JSON).
339    pub fn reply(ui: &mut Ui, result: impl Into<Value>) {
340        let text = match result.into() {
341            Value::String(s) => s,
342            other => serde_json::to_string_pretty(&other).unwrap_or_default(),
343        };
344        ui.reply("result", PropValue::String(text));
345    }
346
347    /// O nome que o agente chama.
348    pub fn name_in(&self, ui: &Ui, id: ComponentId) -> String {
349        let name = self.tool_name.trim();
350        if name.is_empty() { ui.name(id).unwrap_or_default().to_string() } else { name.to_string() }
351    }
352
353    /// O JSON Schema dos argumentos, a partir de `params`.
354    pub fn schema(&self) -> Result<Value, String> {
355        let text = self.params.trim();
356        if text.is_empty() {
357            return Ok(json!({ "type": "object", "properties": {} }));
358        }
359        if text.starts_with('{') {
360            let v: Value = serde_json::from_str(text).map_err(|e| format!("params: JSON inválido: {e}"))?;
361            if v.get("type").is_some() {
362                return Ok(v);
363            }
364            return Ok(json!({ "type": "object", "properties": v }));
365        }
366        // A forma curta: `nome: tipo, outro?: tipo`.
367        let mut properties = Map::new();
368        let mut required = Vec::new();
369        for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) {
370            let (name, kind) = part.split_once(':').map_or((part, "string"), |(n, k)| (n.trim(), k.trim()));
371            let (name, optional) = match name.strip_suffix('?') {
372                Some(n) => (n.trim(), true),
373                None => (name, false),
374            };
375            if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
376                return Err(format!("params: nome inválido: '{part}'"));
377            }
378            let kind = match kind.to_ascii_lowercase().as_str() {
379                "" | "string" | "text" | "texto" => "string",
380                "integer" | "int" | "inteiro" => "integer",
381                "number" | "float" | "numero" | "número" => "number",
382                "boolean" | "bool" => "boolean",
383                "object" | "objeto" => "object",
384                "array" | "lista" => "array",
385                other => return Err(format!("params: tipo desconhecido '{other}' em '{part}'")),
386            };
387            properties.insert(name.to_string(), json!({ "type": kind }));
388            if !optional {
389                required.push(Value::String(name.to_string()));
390            }
391        }
392        Ok(json!({ "type": "object", "properties": properties, "required": required }))
393    }
394}
395
396impl Component for McpTool {
397    fn class_name(&self) -> &'static str {
398        "McpTool"
399    }
400
401    properties! {
402        tool_name: String => "Behavior",
403        description: String => "Behavior",
404        params: String => "Behavior",
405        read_only: bool => "Behavior",
406        enabled: bool => "Behavior";
407        events: on_execute
408    }
409
410    fn default_event(&self) -> Option<&'static str> {
411        Some("on_execute")
412    }
413}
414
415/// Registra as classes do MCP.
416pub fn register(ui: &mut Ui) {
417    ui.register_class::<McpServer>("System");
418    ui.register_class::<McpTool>("System");
419}
420
421// ---------------------------------------------------------------------------
422// JSON-RPC
423
424/// Responde uma mensagem JSON-RPC na thread da conexão (`None` para notificações).
425fn handle_message(message: Value, poster: &Poster, server: ComponentId, timeout: Duration) -> Option<Value> {
426    let id = message.get("id").cloned()?; // notificação (`notifications/initialized`...)
427    let method = message.get("method").and_then(Value::as_str).unwrap_or_default().to_string();
428    let params = message.get("params").cloned().unwrap_or(Value::Null);
429    let result = match method.as_str() {
430        "initialize" => on_ui(poster, timeout, move |ui, reply| reply.send(initialize(ui, server, &params))),
431        "ping" => Ok(json!({})),
432        "tools/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "tools": tools(ui, server) }))),
433        "tools/call" => {
434            let name = params.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
435            let args = params.get("arguments").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
436            on_ui(poster, timeout, move |ui, reply| call_tool(ui, server, name, args, reply)).or_else(|e| Ok(text_result(e, true)))
437        }
438        _ => return Some(http::rpc_error(id, -32601, &format!("método desconhecido: {method}"))),
439    };
440    Some(match result {
441        Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
442        Err(e) => http::rpc_error(id, -32603, &e),
443    })
444}
445
446/// Onde a resposta de uma chamada volta (pode ir para um `on_answer`, depois).
447struct Reply(mpsc::Sender<Value>);
448
449impl Reply {
450    fn send(&self, value: Value) {
451        let _ = self.0.send(value);
452    }
453}
454
455/// Roda `f` na thread da interface e espera a resposta (até `timeout`).
456fn on_ui(poster: &Poster, timeout: Duration, f: impl FnOnce(&mut Ui, Reply) + Send + 'static) -> Result<Value, String> {
457    let (tx, rx) = mpsc::channel();
458    poster.post(move |ui| f(ui, Reply(tx)));
459    rx.recv_timeout(timeout).map_err(|_| "o app não respondeu a tempo".to_string())
460}
461
462fn text_result(text: impl Into<String>, is_error: bool) -> Value {
463    json!({ "content": [{ "type": "text", "text": text.into() }], "isError": is_error })
464}
465
466fn json_text(v: &Value) -> String {
467    match v {
468        Value::String(s) => s.clone(),
469        Value::Null => "ok".into(),
470        other => serde_json::to_string_pretty(other).unwrap_or_default(),
471    }
472}
473
474fn initialize(ui: &Ui, server: ComponentId, params: &Value) -> Value {
475    let (name, mut instructions, expose_ui) = match ui.get::<McpServer>(server) {
476        Some(s) => (s.display_name(ui, server), s.instructions.trim().to_string(), s.expose_ui),
477        None => ("aylis-app".to_string(), String::new(), false),
478    };
479    if expose_ui {
480        if !instructions.is_empty() {
481            instructions.push_str("\n\n");
482        }
483        instructions.push_str("As ferramentas ui_* usam a tela do app pelos componentes (sem olhar pixels): ui_forms lista os forms, ui_tree mostra os componentes de um form (nome, classe, caminho), ui_get lê propriedades, ui_items os itens que um controle desenha (abas, linhas, nós), ui_rows os registros de um ClientDataSet. O alvo é o nome ou o caminho (frmClientes.edtNome).");
484    }
485    json!({
486        "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL),
487        "capabilities": { "tools": { "listChanged": false } },
488        "serverInfo": { "name": name, "version": env!("CARGO_PKG_VERSION") },
489        "instructions": instructions,
490    })
491}
492
493/// As ferramentas filhas do servidor (as ligadas).
494fn app_tools(ui: &Ui, server: ComponentId) -> Vec<(ComponentId, String)> {
495    ui.children(server)
496        .iter()
497        .filter_map(|&c| ui.get::<McpTool>(c).filter(|t| t.enabled).map(|t| (c, t.name_in(ui, c))))
498        .filter(|(_, n)| !n.is_empty())
499        .collect()
500}
501
502fn tool(name: &str, description: &str, properties: Value, required: &[&str], read_only: bool) -> Value {
503    json!({
504        "name": name,
505        "description": description,
506        "inputSchema": { "type": "object", "properties": properties, "required": required },
507        "annotations": { "readOnlyHint": read_only },
508    })
509}
510
511/// A lista que o agente vê: as do app e, com `expose_ui`, as de tela.
512pub fn tools(ui: &Ui, server: ComponentId) -> Vec<Value> {
513    let Some(srv) = ui.get::<McpServer>(server) else { return Vec::new() };
514    let mut out: Vec<Value> = app_tools(ui, server)
515        .into_iter()
516        .filter_map(|(id, name)| {
517            let t = ui.get::<McpTool>(id)?;
518            let schema = t.schema().unwrap_or_else(|_| json!({ "type": "object" }));
519            Some(json!({ "name": name, "description": t.description, "inputSchema": schema, "annotations": { "readOnlyHint": t.read_only } }))
520        })
521        .collect();
522    if srv.expose_ui {
523        out.extend(ui_tools().into_iter().filter(|t| !srv.read_only || READ_TOOLS.contains(&t["name"].as_str().unwrap_or_default())));
524        if srv.read_only {
525            out.push(data_tool(true));
526        }
527    }
528    out
529}
530
531fn ui_tools() -> Vec<Value> {
532    let s = |d: &str| json!({ "type": "string", "description": d });
533    let target = s("o componente: nome ou caminho (frmClientes.edtNome)");
534    vec![
535        tool("ui_forms", "Os forms criados (e DataModules): nome, classe, título, se está aberto (`open`) e visível.", json!({}), &[], true),
536        tool("ui_tree", "A árvore de componentes de um form: nome, classe, caminho, visível e filhos.", json!({ "form": s("o form (vazio: todos)") }), &[], true),
537        tool("ui_get", "As propriedades de um componente (todas, com tipo e valor) ou só uma (`prop`).", json!({ "target": target, "prop": s("a propriedade, opcional") }), &["target"], true),
538        tool("ui_items", "Os itens que um controle desenha sozinho (abas, linhas de lista e grid, nós de árvore, itens de menu): papel, texto, selecionado, marcado.", json!({ "target": target }), &["target"], true),
539        tool("ui_rows", "Os registros de um ClientDataSet (como o grid mostra, sem rolar), a partir de `offset` (padrão 0), até `limit` (padrão 50), e o total.", json!({ "target": target, "offset": { "type": "integer" }, "limit": { "type": "integer" } }), &["target"], true),
540        tool("ui_set", "Muda uma propriedade (`value` é o valor JSON, como no layout: texto, número, booleano, \"#rrggbb\").", json!({ "target": target, "prop": s("a propriedade"), "value": {} }), &["target", "prop", "value"], false),
541        tool(
542            "ui_click",
543            "Clica num controle (botão, caixa, item de menu), como o usuário. Com `modifiers` (\"Ctrl+Shift\" ou [\"ctrl\",\"shift\"]; ctrl, shift, alt, meta), `x`/`y` (dentro do controle; padrão o meio), `button` (left, right, middle) ou `double`, é o mouse de verdade naquele ponto (Ctrl+clique na lista, o menu do botão direito).",
544            json!({ "target": target, "modifiers": {}, "x": { "type": "number" }, "y": { "type": "number" }, "button": s("left | right | middle"), "double": { "type": "boolean" } }),
545            &["target"],
546            false,
547        ),
548        tool(
549            "ui_drag",
550            "Arrasta de um controle (`from`) a outro (`to`): aperta no meio de `from`, anda em `steps` passos (10) e solta no meio de `to` (o arrastar e soltar entre listas; `from` igual a `to` arrasta dentro dele), com `from_x`/`from_y`/`to_x`/`to_y` (dentro de cada um), `modifiers` e `button` como no ui_click.",
551            json!({ "from": target, "to": target, "from_x": { "type": "number" }, "from_y": { "type": "number" }, "to_x": { "type": "number" }, "to_y": { "type": "number" }, "steps": { "type": "integer" }, "modifiers": {}, "button": s("left | right | middle") }),
552            &["from", "to"],
553            false,
554        ),
555        tool("ui_click_item", "Clica num item desenhado (de ui_items) pelo texto (`item`) ou pela posição (`index`); `action`: click, select, expand ou collapse.", json!({ "target": target, "item": s("o texto do item"), "index": { "type": "integer" }, "action": s("click | select | expand | collapse") }), &["target"], false),
556        tool("ui_type", "Põe o foco no controle e digita o texto, como o teclado (passa pelas máscaras e validações).", json!({ "target": target, "text": s("o texto") }), &["target", "text"], false),
557        tool("ui_key", "Aperta uma tecla no form do controle (\"Enter\", \"Tab\", \"Escape\", \"Ctrl+S\"; `modifiers` soma: {\"key\":\"A\",\"modifiers\":[\"ctrl\"]}); com `target`, o foco vai antes para ele.", json!({ "target": target, "key": s("a tecla"), "modifiers": {} }), &["target", "key"], false),
558        tool("ui_invoke", "Chama um método do componente (os do ui_get de cada classe: refresh, clear...).", json!({ "target": target, "method": s("o método"), "args": { "type": "array" } }), &["target", "method"], false),
559        data_tool(false),
560    ]
561}
562
563fn data_tool(read_only: bool) -> Value {
564    let ops = if read_only { READ_DATA_OPS.join(", ") } else { "first, next, prior, last, locate, record, info, edit, insert, set_values, post, cancel, delete, apply...".to_string() };
565    tool(
566        "ui_data",
567        &format!("Uma operação num ClientDataSet (`op`: {ops}), com os campos dela (`field`, `value`, `values`, `index`)."),
568        json!({ "target": { "type": "string" }, "op": { "type": "string" }, "field": { "type": "string" }, "value": {}, "values": { "type": "object" }, "index": { "type": "integer" } }),
569        &["target", "op"],
570        read_only,
571    )
572}
573
574/// Uma chamada, na thread da interface: o `on_call`, depois a ferramenta.
575fn call_tool(ui: &mut Ui, server: ComponentId, name: String, args: Value, reply: Reply) {
576    if !ui.get::<McpServer>(server).is_some_and(|s| s.active) {
577        return reply.send(text_result("o servidor MCP foi desligado", true));
578    }
579    if ui.has_handler(server, "on_call") {
580        let info = json!({ "tool": name, "arguments": args }).to_string();
581        match ui.ask(server, "on_call", &EventArgs::Text(info)) {
582            Asked::Answered(Answer::Refused(m)) => return reply.send(text_result(refused(m), true)),
583            Asked::Answered(Answer::Accepted(_)) => {}
584            Asked::Deferred(token) => {
585                return ui.on_answer(token, move |ui, answer| match answer {
586                    Answer::Refused(m) => reply.send(text_result(refused(m), true)),
587                    Answer::Accepted(_) => run_tool(ui, server, &name, &args, reply),
588                });
589            }
590        }
591    }
592    run_tool(ui, server, &name, &args, reply);
593}
594
595fn refused(message: String) -> String {
596    if message.trim().is_empty() { "chamada recusada pelo app".into() } else { message }
597}
598
599fn run_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value, reply: Reply) {
600    if let Some((tool, _)) = app_tools(ui, server).into_iter().find(|(_, n)| n == name) {
601        return execute_tool(ui, tool, args, reply);
602    }
603    let Some(srv) = ui.get::<McpServer>(server) else { return reply.send(text_result("o servidor MCP foi liberado", true)) };
604    let listed = srv.expose_ui && (!srv.read_only || READ_TOOLS.contains(&name) || name == "ui_data");
605    if !listed || !name.starts_with("ui_") {
606        return reply.send(text_result(format!("ferramenta desconhecida: {name}"), true));
607    }
608    let result = ui_tool(ui, server, name, args);
609    // O que a ação disparou (o on_click, o on_change) roda antes da resposta.
610    ui.process_events();
611    reply.send(match result {
612        Ok(v) => text_result(json_text(&v), false),
613        Err(e) => text_result(e, true),
614    });
615}
616
617fn execute_tool(ui: &mut Ui, tool: ComponentId, args: &Value, reply: Reply) {
618    if !ui.has_handler(tool, "on_execute") {
619        let name = ui.name(tool).unwrap_or_default().to_string();
620        return reply.send(text_result(format!("a ferramenta '{name}' não tem o on_execute ligado"), true));
621    }
622    match ui.ask(tool, "on_execute", &EventArgs::Text(args.to_string())) {
623        Asked::Answered(answer) => {
624            ui.process_events();
625            reply.send(answer_result(ui, answer));
626        }
627        Asked::Deferred(token) => ui.on_answer(token, move |ui, answer| reply.send(answer_result(ui, answer))),
628    }
629}
630
631fn answer_result(ui: &Ui, answer: Answer) -> Value {
632    match answer {
633        Answer::Refused(m) => text_result(if m.trim().is_empty() { "a ferramenta recusou".into() } else { m }, true),
634        Answer::Accepted(values) => {
635            let text = values.iter().rev().find(|(k, _)| k == "result").map(|(_, v)| match v {
636                PropValue::String(s) => s.clone(),
637                other => json_text(&aylis_json::prop_to_json(ui, other)),
638            });
639            text_result(text.unwrap_or_else(|| "ok".into()), false)
640        }
641    }
642}
643
644// ---------------------------------------------------------------------------
645// As ferramentas de tela
646
647/// O componente do alvo, se o agente pode chegar nele: nunca o próprio MCP (servidor e
648/// ferramentas, nem dentro deles), e só os forms de `forms`.
649fn reach(ui: &Ui, server: ComponentId, value: Option<&Value>) -> Result<ComponentId, String> {
650    let id = crate::resolve(ui, value.ok_or("falta \"target\"")?)?;
651    let mut at = Some(id);
652    while let Some(c) = at {
653        let class = ui.component(c).map(|c| c.class_name()).unwrap_or_default();
654        if c == server || class == "McpServer" || class == "McpTool" {
655            return Err("o servidor MCP e as ferramentas dele não podem ser comandados por aqui".into());
656        }
657        at = ui.parent(c);
658    }
659    form_allowed(ui, server, ui.root_of(id))?;
660    Ok(id)
661}
662
663fn form_allowed(ui: &Ui, server: ComponentId, form: ComponentId) -> Result<(), String> {
664    let allowed = ui.get::<McpServer>(server).map(McpServer::allowed_forms).unwrap_or_default();
665    let name = ui.name(form).unwrap_or_default();
666    if allowed.is_empty() || allowed.iter().any(|f| f.eq_ignore_ascii_case(name)) {
667        Ok(())
668    } else {
669        Err(format!("o form '{name}' não está liberado para o agente"))
670    }
671}
672
673fn ui_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value) -> Result<Value, String> {
674    let read_only = ui.get::<McpServer>(server).is_some_and(|s| s.read_only);
675    let str_arg = |key: &str| args.get(key).and_then(Value::as_str).unwrap_or_default().to_string();
676    match name {
677        "ui_forms" => Ok(Value::Array(
678            ui.roots()
679                .iter()
680                .filter(|&&r| form_allowed(ui, server, r).is_ok() && !ui.name(r).unwrap_or_default().is_empty())
681                .map(|&r| {
682                    let class = ui.component(r).map(|c| c.class_name()).unwrap_or_default();
683                    let caption = ui.get_prop(r, "caption").ok().and_then(|v| v.to_str().ok().map(str::to_string));
684                    // `open`: a janela está aberta. Um form criado no início e não mostrado
685                    // existe mas não aparece: `visible` só vale aberto
686                    // (antes dizia `true` para todos, e parecia que tinham aberto).
687                    let open = ui.is_open(r);
688                    json!({ "name": ui.name(r), "class": class, "caption": caption, "open": open, "visible": open && ui.control(r).is_some_and(|c| c.visible()) })
689                })
690                .collect(),
691        )),
692        "ui_tree" => {
693            let form = str_arg("form");
694            if form.is_empty() {
695                let roots: Vec<ComponentId> = ui.roots().iter().copied().filter(|&r| form_allowed(ui, server, r).is_ok()).collect();
696                return Ok(Value::Array(roots.into_iter().map(|r| crate::inspect::tree(ui, Some(r))).collect()));
697            }
698            let id = reach(ui, server, Some(&Value::String(form)))?;
699            Ok(crate::inspect::tree(ui, Some(id)))
700        }
701        "ui_get" => {
702            let id = reach(ui, server, args.get("target"))?;
703            match args.get("prop").and_then(Value::as_str).filter(|p| !p.is_empty()) {
704                Some(prop) => crate::get(ui, id, prop),
705                None => Ok(crate::inspect::props(ui, id)),
706            }
707        }
708        "ui_items" => {
709            let id = reach(ui, server, args.get("target"))?;
710            crate::execute(ui, &json!({ "cmd": "items", "target": id.to_u64() }))
711        }
712        "ui_rows" => {
713            let id = reach(ui, server, args.get("target"))?;
714            rows(ui, id, args)
715        }
716        "ui_data" => {
717            let id = reach(ui, server, args.get("target"))?;
718            let op = str_arg("op");
719            if read_only && !READ_DATA_OPS.contains(&op.as_str()) {
720                return Err(format!("o servidor está só para leitura: a operação '{op}' não vale"));
721            }
722            let mut command = args.as_object().cloned().unwrap_or_default();
723            command.insert("cmd".into(), "data".into());
724            command.insert("target".into(), id.to_u64().into());
725            crate::execute(ui, &Value::Object(command))
726        }
727        _ if read_only => Err(format!("o servidor está só para leitura: '{name}' não vale")),
728        "ui_set" => {
729            let id = reach(ui, server, args.get("target"))?;
730            let prop = str_arg("prop");
731            if prop.is_empty() {
732                return Err("falta \"prop\"".into());
733            }
734            let value = args.get("value").cloned().unwrap_or(Value::Null);
735            crate::execute(ui, &json!({ "cmd": "set", "target": id.to_u64(), "props": { prop: value } }))
736        }
737        "ui_click" => {
738            let id = reach(ui, server, args.get("target"))?;
739            // As opções do clique (o mouse de verdade) passam como estão ao protocolo, o mesmo
740            // caminho do `app_command` da IDE.
741            let mut command = json!({ "cmd": "click", "target": id.to_u64() });
742            for key in ["modifiers", "x", "y", "button", "double"] {
743                if let Some(v) = args.get(key) {
744                    command[key] = v.clone();
745                }
746            }
747            crate::execute(ui, &command)
748        }
749        "ui_drag" => {
750            // Os dois lados passam pelo alcance do servidor (os forms permitidos, nunca ele).
751            let (from, to) = (reach(ui, server, args.get("from"))?, reach(ui, server, args.get("to"))?);
752            let mut command = json!({ "cmd": "drag", "from": from.to_u64(), "to": to.to_u64() });
753            for key in ["from_x", "from_y", "to_x", "to_y", "steps", "modifiers", "button"] {
754                if let Some(v) = args.get(key) {
755                    command[key] = v.clone();
756                }
757            }
758            crate::execute(ui, &command)
759        }
760        "ui_click_item" => {
761            let id = reach(ui, server, args.get("target"))?;
762            let mut command = json!({ "cmd": "click_item", "target": id.to_u64() });
763            for key in ["item", "index", "action"] {
764                if let Some(v) = args.get(key) {
765                    command[key] = v.clone();
766                }
767            }
768            crate::execute(ui, &command)
769        }
770        "ui_type" => {
771            let id = reach(ui, server, args.get("target"))?;
772            ui.set_focus(id);
773            crate::execute(ui, &json!({ "cmd": "type", "target": id.to_u64(), "text": str_arg("text") }))
774        }
775        "ui_key" => {
776            let id = reach(ui, server, args.get("target"))?;
777            if ui.root_of(id) != id {
778                ui.set_focus(id);
779            }
780            let mut command = json!({ "cmd": "key", "target": id.to_u64(), "key": str_arg("key") });
781            if let Some(v) = args.get("modifiers") {
782                command["modifiers"] = v.clone();
783            }
784            crate::execute(ui, &command)
785        }
786        "ui_invoke" => {
787            let id = reach(ui, server, args.get("target"))?;
788            crate::execute(ui, &json!({ "cmd": "invoke", "target": id.to_u64(), "method": str_arg("method"), "args": args.get("args").cloned().unwrap_or_else(|| json!([])) }))
789        }
790        _ => Err(format!("ferramenta desconhecida: {name}")),
791    }
792}
793
794/// Os registros de um ClientDataSet, de `offset` até `limit`.
795fn rows(ui: &Ui, id: ComponentId, args: &Value) -> Result<Value, String> {
796    if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
797        return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
798    }
799    let v = aylis_data::view(ui, id);
800    let count = v.record_count();
801    let offset = args.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
802    let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 1000) as usize;
803    let names = v.field_names();
804    let list: Vec<Value> = (offset..count.min(offset.saturating_add(limit)))
805        .map(|i| {
806            let mut row = Map::new();
807            for name in &names {
808                let value = v.value_at(i, name).map(|x| aylis_data::json::value_to_json(&x)).unwrap_or(Value::Null);
809                row.insert(name.clone(), value);
810            }
811            Value::Object(row)
812        })
813        .collect();
814    Ok(json!({ "count": count, "offset": offset, "rows": list }))
815}