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 (como uma `TAction` que a IA
11//!   dispara). É 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    pub active: bool,
111    pub port: u32,
112    pub token: String,
113    /// O nome que o agente vê (vazio: o nome do componente).
114    pub server_name: String,
115    /// O que o agente lê ao conectar: para que serve o app e como usar as ferramentas.
116    pub instructions: String,
117    pub expose_ui: bool,
118    pub read_only: bool,
119    pub forms: String,
120    /// Quanto uma chamada pode demorar, em milissegundos (vale ao ligar).
121    pub call_timeout: u32,
122    running: Option<http::HttpServer>,
123    /// Já tentou ligar com a configuração atual (uma falha não repete a cada volta do timer).
124    attempted: bool,
125    last_error: String,
126}
127
128impl Default for McpServer {
129    fn default() -> Self {
130        Self {
131            active: false,
132            port: 0,
133            token: String::new(),
134            server_name: String::new(),
135            instructions: String::new(),
136            expose_ui: false,
137            read_only: false,
138            forms: String::new(),
139            call_timeout: DEFAULT_TIMEOUT,
140            running: None,
141            attempted: false,
142            last_error: String::new(),
143        }
144    }
145}
146
147impl McpServer {
148    /// O endereço dos clientes (vazio: parado).
149    pub fn url(&self) -> String {
150        self.running.as_ref().map(http::HttpServer::url).unwrap_or_default()
151    }
152
153    pub fn running(&self) -> bool {
154        self.running.is_some()
155    }
156
157    /// A falha da última tentativa de ligar (vazia: nenhuma).
158    pub fn last_error(&self) -> String {
159        self.last_error.clone()
160    }
161
162    /// A linha que liga o Claude Code a este app (vazia: parado). Com o `claude` fora do PATH
163    /// (o que vem com o Claude Desktop, por exemplo), a linha leva o caminho completo dele,
164    /// para rodar num terminal comum.
165    pub fn client_command(&self, ui: &Ui, id: ComponentId) -> String {
166        if self.running.is_none() {
167            return String::new();
168        }
169        let name = self.display_name(ui, id).replace(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_', "-");
170        let claude = match claude_executable() {
171            Some(ClaudeCode { path, in_path: false }) => format!("\"{}\"", path.display()),
172            _ => "claude".to_string(),
173        };
174        format!("{claude} mcp add --transport http {name} {} --header \"Authorization: Bearer {}\"", self.url(), self.token)
175    }
176
177    fn display_name(&self, ui: &Ui, id: ComponentId) -> String {
178        if !self.server_name.trim().is_empty() {
179            return self.server_name.trim().to_string();
180        }
181        ui.name(id).filter(|n| !n.is_empty()).unwrap_or("aylis-app").to_string()
182    }
183
184    fn allowed_forms(&self) -> Vec<String> {
185        self.forms.split([',', ';']).map(str::trim).filter(|f| !f.is_empty()).map(str::to_string).collect()
186    }
187
188    fn set_s(&mut self, _: String) {}
189    fn set_b(&mut self, _: bool) {}
190
191    /// Liga ou desliga conforme `active` (nunca no designer).
192    fn sync(&mut self, ctx: &mut EventCtx<'_>) {
193        if ctx.ui.design_mode() {
194            return;
195        }
196        if !self.active {
197            self.running = None;
198            self.attempted = false;
199            return;
200        }
201        if self.running.is_some() || self.attempted {
202            return;
203        }
204        self.attempted = true;
205        match self.start(ctx.ui.poster(), ctx.id) {
206            Ok(server) => {
207                self.last_error.clear();
208                self.running = Some(server);
209            }
210            Err(e) => {
211                self.last_error = e.clone();
212                ctx.fire("on_error", EventArgs::Text(e));
213            }
214        }
215    }
216
217    fn start(&mut self, poster: Poster, id: ComponentId) -> Result<http::HttpServer, String> {
218        let port = u16::try_from(self.port).map_err(|_| format!("MCP: porta inválida: {}", self.port))?;
219        if self.token.is_empty() {
220            self.token = random_token()?;
221        }
222        let timeout = Duration::from_millis(u64::from(if self.call_timeout == 0 { DEFAULT_TIMEOUT } else { self.call_timeout }));
223        http::start(port, self.token.clone(), "aylis-mcp", Arc::new(move |message| handle_message(message, &poster, id, timeout)))
224    }
225}
226
227impl Component for McpServer {
228    fn class_name(&self) -> &'static str {
229        "McpServer"
230    }
231
232    properties! {
233        active: bool => "Behavior",
234        port: u32 => "Behavior",
235        token: String => "Behavior",
236        server_name: String => "Behavior",
237        instructions: String => "Behavior",
238        expose_ui: bool => "Behavior",
239        read_only: bool => "Behavior",
240        forms: String => "Behavior",
241        call_timeout: u32 as Duration => "Behavior";
242        events: on_call, on_error;
243        computed: url: String => url / set_s, running: bool => running / set_b, last_error: String => last_error / set_s
244    }
245
246    fn methods(&self) -> &'static [MethodInfo] {
247        const METHODS: &[MethodInfo] = &[MethodInfo::new("client_command", &[], Some(PropKind::String))];
248        METHODS
249    }
250
251    fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, _args: &[PropValue]) -> Result<PropValue, String> {
252        match method {
253            "client_command" => Ok(PropValue::String(self.client_command(ctx.ui, ctx.id))),
254            _ => Err(format!("McpServer não tem o método '{method}'")),
255        }
256    }
257
258    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
259        if matches!(name, "port" | "token" | "call_timeout") && self.running.is_some() {
260            // Religa com a configuração nova.
261            self.running = None;
262            self.attempted = false;
263        }
264        if name == "active" {
265            self.attempted = false;
266        }
267        self.sync(ctx);
268    }
269
270    // Carregado de um form com `active` ligado, liga na primeira volta do timer.
271    fn timer_interval(&self) -> Option<f64> {
272        (self.active && self.running.is_none() && !self.attempted).then_some(0.2)
273    }
274
275    fn timer(&mut self, ctx: &mut EventCtx<'_>) {
276        self.sync(ctx);
277    }
278}
279
280#[cfg(not(target_arch = "wasm32"))]
281fn random_token() -> Result<String, String> {
282    let mut bytes = [0u8; 32];
283    getrandom::fill(&mut bytes).map_err(|e| format!("MCP: sem gerador aleatório do sistema: {e}"))?;
284    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
285}
286
287#[cfg(target_arch = "wasm32")]
288fn random_token() -> Result<String, String> {
289    Err("MCP: o navegador não abre portas (use o app de desktop)".into())
290}
291
292// ---------------------------------------------------------------------------
293// McpTool
294
295/// Uma ferramenta do app para o agente (filha de um [`McpServer`]). `tool_name` é o nome que
296/// ele chama (vazio: o nome do componente), `description` diz quando usar, e `params` os
297/// parâmetros: um JSON Schema (`{"type": "object", "properties": {..}}`), só as
298/// propriedades (`{"cliente": {"type": "string"}}`) ou a forma curta
299/// `cliente: string, quantidade: integer, obs?: string` (o `?` marca o opcional).
300///
301/// `on_execute` recebe os argumentos (o texto do evento é o JSON; [`McpTool::arguments`]
302/// lê) e responde com [`McpTool::reply`] (ou `ui.reply("result", ..)`); recusar
303/// ([`Ui::refuse`]) devolve o erro. Um backend em outra linguagem responde depois, como em
304/// todo evento-pergunta. `read_only` avisa o agente que a ferramenta não muda nada.
305pub struct McpTool {
306    pub tool_name: String,
307    pub description: String,
308    pub params: String,
309    pub read_only: bool,
310    pub enabled: bool,
311}
312
313impl Default for McpTool {
314    fn default() -> Self {
315        Self { tool_name: String::new(), description: String::new(), params: String::new(), read_only: false, enabled: true }
316    }
317}
318
319impl McpTool {
320    /// Os argumentos que o agente mandou (no `on_execute`).
321    pub fn arguments(args: &EventArgs) -> Value {
322        args.text().and_then(|t| serde_json::from_str(t).ok()).unwrap_or_else(|| json!({}))
323    }
324
325    /// Responde o `on_execute`: um texto, ou JSON (vai como texto JSON).
326    pub fn reply(ui: &mut Ui, result: impl Into<Value>) {
327        let text = match result.into() {
328            Value::String(s) => s,
329            other => serde_json::to_string_pretty(&other).unwrap_or_default(),
330        };
331        ui.reply("result", PropValue::String(text));
332    }
333
334    /// O nome que o agente chama.
335    pub fn name_in(&self, ui: &Ui, id: ComponentId) -> String {
336        let name = self.tool_name.trim();
337        if name.is_empty() { ui.name(id).unwrap_or_default().to_string() } else { name.to_string() }
338    }
339
340    /// O JSON Schema dos argumentos, a partir de `params`.
341    pub fn schema(&self) -> Result<Value, String> {
342        let text = self.params.trim();
343        if text.is_empty() {
344            return Ok(json!({ "type": "object", "properties": {} }));
345        }
346        if text.starts_with('{') {
347            let v: Value = serde_json::from_str(text).map_err(|e| format!("params: JSON inválido: {e}"))?;
348            if v.get("type").is_some() {
349                return Ok(v);
350            }
351            return Ok(json!({ "type": "object", "properties": v }));
352        }
353        // A forma curta: `nome: tipo, outro?: tipo`.
354        let mut properties = Map::new();
355        let mut required = Vec::new();
356        for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) {
357            let (name, kind) = part.split_once(':').map_or((part, "string"), |(n, k)| (n.trim(), k.trim()));
358            let (name, optional) = match name.strip_suffix('?') {
359                Some(n) => (n.trim(), true),
360                None => (name, false),
361            };
362            if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
363                return Err(format!("params: nome inválido: '{part}'"));
364            }
365            let kind = match kind.to_ascii_lowercase().as_str() {
366                "" | "string" | "text" | "texto" => "string",
367                "integer" | "int" | "inteiro" => "integer",
368                "number" | "float" | "numero" | "número" => "number",
369                "boolean" | "bool" => "boolean",
370                "object" | "objeto" => "object",
371                "array" | "lista" => "array",
372                other => return Err(format!("params: tipo desconhecido '{other}' em '{part}'")),
373            };
374            properties.insert(name.to_string(), json!({ "type": kind }));
375            if !optional {
376                required.push(Value::String(name.to_string()));
377            }
378        }
379        Ok(json!({ "type": "object", "properties": properties, "required": required }))
380    }
381}
382
383impl Component for McpTool {
384    fn class_name(&self) -> &'static str {
385        "McpTool"
386    }
387
388    properties! {
389        tool_name: String => "Behavior",
390        description: String => "Behavior",
391        params: String => "Behavior",
392        read_only: bool => "Behavior",
393        enabled: bool => "Behavior";
394        events: on_execute
395    }
396
397    fn default_event(&self) -> Option<&'static str> {
398        Some("on_execute")
399    }
400}
401
402/// Registra as classes do MCP.
403pub fn register(ui: &mut Ui) {
404    ui.register_class::<McpServer>("System");
405    ui.register_class::<McpTool>("System");
406}
407
408// ---------------------------------------------------------------------------
409// JSON-RPC
410
411/// Responde uma mensagem JSON-RPC na thread da conexão (`None` para notificações).
412fn handle_message(message: Value, poster: &Poster, server: ComponentId, timeout: Duration) -> Option<Value> {
413    let id = message.get("id").cloned()?; // notificação (`notifications/initialized`...)
414    let method = message.get("method").and_then(Value::as_str).unwrap_or_default().to_string();
415    let params = message.get("params").cloned().unwrap_or(Value::Null);
416    let result = match method.as_str() {
417        "initialize" => on_ui(poster, timeout, move |ui, reply| reply.send(initialize(ui, server, &params))),
418        "ping" => Ok(json!({})),
419        "tools/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "tools": tools(ui, server) }))),
420        "tools/call" => {
421            let name = params.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
422            let args = params.get("arguments").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
423            on_ui(poster, timeout, move |ui, reply| call_tool(ui, server, name, args, reply)).or_else(|e| Ok(text_result(e, true)))
424        }
425        _ => return Some(http::rpc_error(id, -32601, &format!("método desconhecido: {method}"))),
426    };
427    Some(match result {
428        Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
429        Err(e) => http::rpc_error(id, -32603, &e),
430    })
431}
432
433/// Onde a resposta de uma chamada volta (pode ir para um `on_answer`, depois).
434struct Reply(mpsc::Sender<Value>);
435
436impl Reply {
437    fn send(&self, value: Value) {
438        let _ = self.0.send(value);
439    }
440}
441
442/// Roda `f` na thread da interface e espera a resposta (até `timeout`).
443fn on_ui(poster: &Poster, timeout: Duration, f: impl FnOnce(&mut Ui, Reply) + Send + 'static) -> Result<Value, String> {
444    let (tx, rx) = mpsc::channel();
445    poster.post(move |ui| f(ui, Reply(tx)));
446    rx.recv_timeout(timeout).map_err(|_| "o app não respondeu a tempo".to_string())
447}
448
449fn text_result(text: impl Into<String>, is_error: bool) -> Value {
450    json!({ "content": [{ "type": "text", "text": text.into() }], "isError": is_error })
451}
452
453fn json_text(v: &Value) -> String {
454    match v {
455        Value::String(s) => s.clone(),
456        Value::Null => "ok".into(),
457        other => serde_json::to_string_pretty(other).unwrap_or_default(),
458    }
459}
460
461fn initialize(ui: &Ui, server: ComponentId, params: &Value) -> Value {
462    let (name, mut instructions, expose_ui) = match ui.get::<McpServer>(server) {
463        Some(s) => (s.display_name(ui, server), s.instructions.trim().to_string(), s.expose_ui),
464        None => ("aylis-app".to_string(), String::new(), false),
465    };
466    if expose_ui {
467        if !instructions.is_empty() {
468            instructions.push_str("\n\n");
469        }
470        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).");
471    }
472    json!({
473        "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL),
474        "capabilities": { "tools": { "listChanged": false } },
475        "serverInfo": { "name": name, "version": env!("CARGO_PKG_VERSION") },
476        "instructions": instructions,
477    })
478}
479
480/// As ferramentas filhas do servidor (as ligadas).
481fn app_tools(ui: &Ui, server: ComponentId) -> Vec<(ComponentId, String)> {
482    ui.children(server)
483        .iter()
484        .filter_map(|&c| ui.get::<McpTool>(c).filter(|t| t.enabled).map(|t| (c, t.name_in(ui, c))))
485        .filter(|(_, n)| !n.is_empty())
486        .collect()
487}
488
489fn tool(name: &str, description: &str, properties: Value, required: &[&str], read_only: bool) -> Value {
490    json!({
491        "name": name,
492        "description": description,
493        "inputSchema": { "type": "object", "properties": properties, "required": required },
494        "annotations": { "readOnlyHint": read_only },
495    })
496}
497
498/// A lista que o agente vê: as do app e, com `expose_ui`, as de tela.
499pub fn tools(ui: &Ui, server: ComponentId) -> Vec<Value> {
500    let Some(srv) = ui.get::<McpServer>(server) else { return Vec::new() };
501    let mut out: Vec<Value> = app_tools(ui, server)
502        .into_iter()
503        .filter_map(|(id, name)| {
504            let t = ui.get::<McpTool>(id)?;
505            let schema = t.schema().unwrap_or_else(|_| json!({ "type": "object" }));
506            Some(json!({ "name": name, "description": t.description, "inputSchema": schema, "annotations": { "readOnlyHint": t.read_only } }))
507        })
508        .collect();
509    if srv.expose_ui {
510        out.extend(ui_tools().into_iter().filter(|t| !srv.read_only || READ_TOOLS.contains(&t["name"].as_str().unwrap_or_default())));
511        if srv.read_only {
512            out.push(data_tool(true));
513        }
514    }
515    out
516}
517
518fn ui_tools() -> Vec<Value> {
519    let s = |d: &str| json!({ "type": "string", "description": d });
520    let target = s("o componente: nome ou caminho (frmClientes.edtNome)");
521    vec![
522        tool("ui_forms", "Os forms criados (e DataModules): nome, classe, título, se está aberto (`open`) e visível.", json!({}), &[], true),
523        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),
524        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),
525        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),
526        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),
527        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),
528        tool("ui_click", "Clica num controle (botão, caixa, item de menu), como o usuário.", json!({ "target": target }), &["target"], false),
529        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),
530        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),
531        tool("ui_key", "Aperta uma tecla no form do controle (\"Enter\", \"Tab\", \"Escape\", \"Ctrl+S\"); com `target`, o foco vai antes para ele.", json!({ "target": target, "key": s("a tecla") }), &["target", "key"], false),
532        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),
533        data_tool(false),
534    ]
535}
536
537fn data_tool(read_only: bool) -> Value {
538    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() };
539    tool(
540        "ui_data",
541        &format!("Uma operação num ClientDataSet (`op`: {ops}), com os campos dela (`field`, `value`, `values`, `index`)."),
542        json!({ "target": { "type": "string" }, "op": { "type": "string" }, "field": { "type": "string" }, "value": {}, "values": { "type": "object" }, "index": { "type": "integer" } }),
543        &["target", "op"],
544        read_only,
545    )
546}
547
548/// Uma chamada, na thread da interface: o `on_call`, depois a ferramenta.
549fn call_tool(ui: &mut Ui, server: ComponentId, name: String, args: Value, reply: Reply) {
550    if !ui.get::<McpServer>(server).is_some_and(|s| s.active) {
551        return reply.send(text_result("o servidor MCP foi desligado", true));
552    }
553    if ui.has_handler(server, "on_call") {
554        let info = json!({ "tool": name, "arguments": args }).to_string();
555        match ui.ask(server, "on_call", &EventArgs::Text(info)) {
556            Asked::Answered(Answer::Refused(m)) => return reply.send(text_result(refused(m), true)),
557            Asked::Answered(Answer::Accepted(_)) => {}
558            Asked::Deferred(token) => {
559                return ui.on_answer(token, move |ui, answer| match answer {
560                    Answer::Refused(m) => reply.send(text_result(refused(m), true)),
561                    Answer::Accepted(_) => run_tool(ui, server, &name, &args, reply),
562                });
563            }
564        }
565    }
566    run_tool(ui, server, &name, &args, reply);
567}
568
569fn refused(message: String) -> String {
570    if message.trim().is_empty() { "chamada recusada pelo app".into() } else { message }
571}
572
573fn run_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value, reply: Reply) {
574    if let Some((tool, _)) = app_tools(ui, server).into_iter().find(|(_, n)| n == name) {
575        return execute_tool(ui, tool, args, reply);
576    }
577    let Some(srv) = ui.get::<McpServer>(server) else { return reply.send(text_result("o servidor MCP foi liberado", true)) };
578    let listed = srv.expose_ui && (!srv.read_only || READ_TOOLS.contains(&name) || name == "ui_data");
579    if !listed || !name.starts_with("ui_") {
580        return reply.send(text_result(format!("ferramenta desconhecida: {name}"), true));
581    }
582    let result = ui_tool(ui, server, name, args);
583    // O que a ação disparou (o on_click, o on_change) roda antes da resposta.
584    ui.process_events();
585    reply.send(match result {
586        Ok(v) => text_result(json_text(&v), false),
587        Err(e) => text_result(e, true),
588    });
589}
590
591fn execute_tool(ui: &mut Ui, tool: ComponentId, args: &Value, reply: Reply) {
592    if !ui.has_handler(tool, "on_execute") {
593        let name = ui.name(tool).unwrap_or_default().to_string();
594        return reply.send(text_result(format!("a ferramenta '{name}' não tem o on_execute ligado"), true));
595    }
596    match ui.ask(tool, "on_execute", &EventArgs::Text(args.to_string())) {
597        Asked::Answered(answer) => {
598            ui.process_events();
599            reply.send(answer_result(ui, answer));
600        }
601        Asked::Deferred(token) => ui.on_answer(token, move |ui, answer| reply.send(answer_result(ui, answer))),
602    }
603}
604
605fn answer_result(ui: &Ui, answer: Answer) -> Value {
606    match answer {
607        Answer::Refused(m) => text_result(if m.trim().is_empty() { "a ferramenta recusou".into() } else { m }, true),
608        Answer::Accepted(values) => {
609            let text = values.iter().rev().find(|(k, _)| k == "result").map(|(_, v)| match v {
610                PropValue::String(s) => s.clone(),
611                other => json_text(&aylis_json::prop_to_json(ui, other)),
612            });
613            text_result(text.unwrap_or_else(|| "ok".into()), false)
614        }
615    }
616}
617
618// ---------------------------------------------------------------------------
619// As ferramentas de tela
620
621/// O componente do alvo, se o agente pode chegar nele: nunca o próprio MCP (servidor e
622/// ferramentas, nem dentro deles), e só os forms de `forms`.
623fn reach(ui: &Ui, server: ComponentId, value: Option<&Value>) -> Result<ComponentId, String> {
624    let id = crate::resolve(ui, value.ok_or("falta \"target\"")?)?;
625    let mut at = Some(id);
626    while let Some(c) = at {
627        let class = ui.component(c).map(|c| c.class_name()).unwrap_or_default();
628        if c == server || class == "McpServer" || class == "McpTool" {
629            return Err("o servidor MCP e as ferramentas dele não podem ser comandados por aqui".into());
630        }
631        at = ui.parent(c);
632    }
633    form_allowed(ui, server, ui.root_of(id))?;
634    Ok(id)
635}
636
637fn form_allowed(ui: &Ui, server: ComponentId, form: ComponentId) -> Result<(), String> {
638    let allowed = ui.get::<McpServer>(server).map(McpServer::allowed_forms).unwrap_or_default();
639    let name = ui.name(form).unwrap_or_default();
640    if allowed.is_empty() || allowed.iter().any(|f| f.eq_ignore_ascii_case(name)) {
641        Ok(())
642    } else {
643        Err(format!("o form '{name}' não está liberado para o agente"))
644    }
645}
646
647fn ui_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value) -> Result<Value, String> {
648    let read_only = ui.get::<McpServer>(server).is_some_and(|s| s.read_only);
649    let str_arg = |key: &str| args.get(key).and_then(Value::as_str).unwrap_or_default().to_string();
650    match name {
651        "ui_forms" => Ok(Value::Array(
652            ui.roots()
653                .iter()
654                .filter(|&&r| form_allowed(ui, server, r).is_ok() && !ui.name(r).unwrap_or_default().is_empty())
655                .map(|&r| {
656                    let class = ui.component(r).map(|c| c.class_name()).unwrap_or_default();
657                    let caption = ui.get_prop(r, "caption").ok().and_then(|v| v.to_str().ok().map(str::to_string));
658                    // `open`: a janela está aberta. Um form criado no início e não mostrado (como o
659                    // `CreateForm` do Delphi) existe mas não aparece: `visible` só vale aberto
660                    // (antes dizia `true` para todos, e parecia que tinham aberto).
661                    let open = ui.is_open(r);
662                    json!({ "name": ui.name(r), "class": class, "caption": caption, "open": open, "visible": open && ui.control(r).is_some_and(|c| c.visible()) })
663                })
664                .collect(),
665        )),
666        "ui_tree" => {
667            let form = str_arg("form");
668            if form.is_empty() {
669                let roots: Vec<ComponentId> = ui.roots().iter().copied().filter(|&r| form_allowed(ui, server, r).is_ok()).collect();
670                return Ok(Value::Array(roots.into_iter().map(|r| crate::inspect::tree(ui, Some(r))).collect()));
671            }
672            let id = reach(ui, server, Some(&Value::String(form)))?;
673            Ok(crate::inspect::tree(ui, Some(id)))
674        }
675        "ui_get" => {
676            let id = reach(ui, server, args.get("target"))?;
677            match args.get("prop").and_then(Value::as_str).filter(|p| !p.is_empty()) {
678                Some(prop) => crate::get(ui, id, prop),
679                None => Ok(crate::inspect::props(ui, id)),
680            }
681        }
682        "ui_items" => {
683            let id = reach(ui, server, args.get("target"))?;
684            crate::execute(ui, &json!({ "cmd": "items", "target": id.to_u64() }))
685        }
686        "ui_rows" => {
687            let id = reach(ui, server, args.get("target"))?;
688            rows(ui, id, args)
689        }
690        "ui_data" => {
691            let id = reach(ui, server, args.get("target"))?;
692            let op = str_arg("op");
693            if read_only && !READ_DATA_OPS.contains(&op.as_str()) {
694                return Err(format!("o servidor está só para leitura: a operação '{op}' não vale"));
695            }
696            let mut command = args.as_object().cloned().unwrap_or_default();
697            command.insert("cmd".into(), "data".into());
698            command.insert("target".into(), id.to_u64().into());
699            crate::execute(ui, &Value::Object(command))
700        }
701        _ if read_only => Err(format!("o servidor está só para leitura: '{name}' não vale")),
702        "ui_set" => {
703            let id = reach(ui, server, args.get("target"))?;
704            let prop = str_arg("prop");
705            if prop.is_empty() {
706                return Err("falta \"prop\"".into());
707            }
708            let value = args.get("value").cloned().unwrap_or(Value::Null);
709            crate::execute(ui, &json!({ "cmd": "set", "target": id.to_u64(), "props": { prop: value } }))
710        }
711        "ui_click" => {
712            let id = reach(ui, server, args.get("target"))?;
713            crate::execute(ui, &json!({ "cmd": "click", "target": id.to_u64() }))
714        }
715        "ui_click_item" => {
716            let id = reach(ui, server, args.get("target"))?;
717            let mut command = json!({ "cmd": "click_item", "target": id.to_u64() });
718            for key in ["item", "index", "action"] {
719                if let Some(v) = args.get(key) {
720                    command[key] = v.clone();
721                }
722            }
723            crate::execute(ui, &command)
724        }
725        "ui_type" => {
726            let id = reach(ui, server, args.get("target"))?;
727            ui.set_focus(id);
728            crate::execute(ui, &json!({ "cmd": "type", "target": id.to_u64(), "text": str_arg("text") }))
729        }
730        "ui_key" => {
731            let id = reach(ui, server, args.get("target"))?;
732            if ui.root_of(id) != id {
733                ui.set_focus(id);
734            }
735            crate::execute(ui, &json!({ "cmd": "key", "target": id.to_u64(), "key": str_arg("key") }))
736        }
737        "ui_invoke" => {
738            let id = reach(ui, server, args.get("target"))?;
739            crate::execute(ui, &json!({ "cmd": "invoke", "target": id.to_u64(), "method": str_arg("method"), "args": args.get("args").cloned().unwrap_or_else(|| json!([])) }))
740        }
741        _ => Err(format!("ferramenta desconhecida: {name}")),
742    }
743}
744
745/// Os registros de um ClientDataSet, de `offset` até `limit`.
746fn rows(ui: &Ui, id: ComponentId, args: &Value) -> Result<Value, String> {
747    if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
748        return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
749    }
750    let v = aylis_data::view(ui, id);
751    let count = v.record_count();
752    let offset = args.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
753    let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 1000) as usize;
754    let names = v.field_names();
755    let list: Vec<Value> = (offset..count.min(offset.saturating_add(limit)))
756        .map(|i| {
757            let mut row = Map::new();
758            for name in &names {
759                let value = v.value_at(i, name).map(|x| aylis_data::json::value_to_json(&x)).unwrap_or(Value::Null);
760                row.insert(name.clone(), value);
761            }
762            Value::Object(row)
763        })
764        .collect();
765    Ok(json!({ "count": count, "offset": offset, "rows": list }))
766}