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 timed(&self) -> Option<&dyn aylis_core::Timed> {
236        Some(self)
237    }
238
239    fn timed_mut(&mut self) -> Option<&mut dyn aylis_core::Timed> {
240        Some(self)
241    }
242
243    fn class_name(&self) -> &'static str {
244        "McpServer"
245    }
246
247    properties! {
248        active: bool => "Behavior",
249        port: u32 => "Behavior",
250        token: String => "Behavior",
251        server_name: String => "Behavior",
252        instructions: String => "Behavior",
253        expose_ui: bool => "Behavior",
254        read_only: bool => "Behavior",
255        forms: String => "Behavior",
256        call_timeout: u32 as Duration => "Behavior";
257        events: on_call, on_error: String;
258        computed: url: String => url / set_s, running: bool => running / set_b, last_error: String => last_error / set_s
259    }
260
261    fn methods(&self) -> &'static [MethodInfo] {
262        const METHODS: &[MethodInfo] = &[MethodInfo::new("client_command", &[], Some(PropKind::String))];
263        METHODS
264    }
265
266    fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, _args: &[PropValue]) -> Result<PropValue, String> {
267        match method {
268            "client_command" => Ok(PropValue::String(self.client_command(ctx.ui, ctx.id))),
269            _ => Err(format!("McpServer não tem o método '{method}'")),
270        }
271    }
272
273    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
274        if matches!(name, "port" | "token" | "call_timeout") && self.running.is_some() {
275            // Religa com a configuração nova.
276            self.running = None;
277            self.attempted = false;
278        }
279        if name == "active" {
280            self.attempted = false;
281        }
282        self.sync(ctx);
283    }
284
285    // Carregado de um form com `active` ligado, liga na primeira volta do timer.
286
287}
288
289impl aylis_core::Timed for McpServer {
290    fn timer_interval(&self) -> Option<f64> {
291        (self.active && self.running.is_none() && !self.attempted).then_some(0.2)
292    }
293
294    fn timer(&mut self, ctx: &mut EventCtx<'_>) {
295        self.sync(ctx);
296    }
297}
298
299#[cfg(not(target_arch = "wasm32"))]
300fn random_token() -> Result<String, String> {
301    let mut bytes = [0u8; 32];
302    getrandom::fill(&mut bytes).map_err(|e| format!("MCP: sem gerador aleatório do sistema: {e}"))?;
303    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
304}
305
306#[cfg(target_arch = "wasm32")]
307fn random_token() -> Result<String, String> {
308    Err("MCP: o navegador não abre portas (use o app de desktop)".into())
309}
310
311// ---------------------------------------------------------------------------
312// McpTool
313
314/// Uma ferramenta do app para o agente (filha de um [`McpServer`]). `tool_name` é o nome que
315/// ele chama (vazio: o nome do componente), `description` diz quando usar, e `params` os
316/// parâmetros: um JSON Schema (`{"type": "object", "properties": {..}}`), só as
317/// propriedades (`{"cliente": {"type": "string"}}`) ou a forma curta
318/// `cliente: string, quantidade: integer, obs?: string` (o `?` marca o opcional).
319///
320/// `on_execute` recebe os argumentos (o texto do evento é o JSON; [`McpTool::arguments`]
321/// lê) e responde com [`McpTool::reply`] (ou `ui.reply("result", ..)`); recusar
322/// ([`Ui::refuse`]) devolve o erro. Um backend em outra linguagem responde depois, como em
323/// todo evento-pergunta. `read_only` avisa o agente que a ferramenta não muda nada.
324pub struct McpTool {
325    /// O nome que o agente chama; vazio: o nome do componente.
326    pub tool_name: String,
327    /// O que a ferramenta faz e quando usar (o agente lê para escolher).
328    pub description: String,
329    /// Os parâmetros: um JSON Schema, só as propriedades ou a forma curta
330    /// `cliente: string, quantidade: integer, obs?: string` (`?`: opcional); vazio: nenhum.
331    pub params: String,
332    /// Avisa o agente que a ferramenta só lê, não muda nada.
333    pub read_only: bool,
334    /// Oferecida ao agente; desligada, ele não a vê.
335    pub enabled: bool,
336}
337
338impl Default for McpTool {
339    fn default() -> Self {
340        Self { tool_name: String::new(), description: String::new(), params: String::new(), read_only: false, enabled: true }
341    }
342}
343
344impl McpTool {
345    /// Os argumentos que o agente mandou (no `on_execute`).
346    pub fn arguments(args: &EventArgs) -> Value {
347        args.text().and_then(|t| serde_json::from_str(t).ok()).unwrap_or_else(|| json!({}))
348    }
349
350    /// Responde o `on_execute`: um texto, ou JSON (vai como texto JSON).
351    pub fn reply(ui: &mut Ui, result: impl Into<Value>) {
352        let text = match result.into() {
353            Value::String(s) => s,
354            other => serde_json::to_string_pretty(&other).unwrap_or_default(),
355        };
356        ui.reply("result", PropValue::String(text));
357    }
358
359    /// O nome que o agente chama.
360    pub fn name_in(&self, ui: &Ui, id: ComponentId) -> String {
361        let name = self.tool_name.trim();
362        if name.is_empty() { ui.name(id).unwrap_or_default().to_string() } else { name.to_string() }
363    }
364
365    /// O JSON Schema dos argumentos, a partir de `params`.
366    pub fn schema(&self) -> Result<Value, String> {
367        let text = self.params.trim();
368        if text.is_empty() {
369            return Ok(json!({ "type": "object", "properties": {} }));
370        }
371        if text.starts_with('{') {
372            let v: Value = serde_json::from_str(text).map_err(|e| format!("params: JSON inválido: {e}"))?;
373            if v.get("type").is_some() {
374                return Ok(v);
375            }
376            return Ok(json!({ "type": "object", "properties": v }));
377        }
378        // A forma curta: `nome: tipo, outro?: tipo`.
379        let mut properties = Map::new();
380        let mut required = Vec::new();
381        for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) {
382            let (name, kind) = part.split_once(':').map_or((part, "string"), |(n, k)| (n.trim(), k.trim()));
383            let (name, optional) = match name.strip_suffix('?') {
384                Some(n) => (n.trim(), true),
385                None => (name, false),
386            };
387            if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
388                return Err(format!("params: nome inválido: '{part}'"));
389            }
390            let kind = match kind.to_ascii_lowercase().as_str() {
391                "" | "string" | "text" | "texto" => "string",
392                "integer" | "int" | "inteiro" => "integer",
393                "number" | "float" | "numero" | "número" => "number",
394                "boolean" | "bool" => "boolean",
395                "object" | "objeto" => "object",
396                "array" | "lista" => "array",
397                other => return Err(format!("params: tipo desconhecido '{other}' em '{part}'")),
398            };
399            properties.insert(name.to_string(), json!({ "type": kind }));
400            if !optional {
401                required.push(Value::String(name.to_string()));
402            }
403        }
404        Ok(json!({ "type": "object", "properties": properties, "required": required }))
405    }
406}
407
408impl Component for McpTool {
409    fn class_name(&self) -> &'static str {
410        "McpTool"
411    }
412
413    properties! {
414        tool_name: String => "Behavior",
415        description: String => "Behavior",
416        params: String => "Behavior",
417        read_only: bool => "Behavior",
418        enabled: bool => "Behavior";
419        events: on_execute
420    }
421
422    fn default_event(&self) -> Option<&'static str> {
423        Some("on_execute")
424    }
425}
426
427/// Registra as classes do MCP.
428pub fn register(ui: &mut Ui) {
429    ui.register_class::<McpServer>("System");
430    ui.register_class::<McpTool>("System");
431}
432
433// ---------------------------------------------------------------------------
434// JSON-RPC
435
436/// Responde uma mensagem JSON-RPC na thread da conexão (`None` para notificações).
437fn handle_message(message: Value, poster: &Poster, server: ComponentId, timeout: Duration) -> Option<Value> {
438    let id = message.get("id").cloned()?; // notificação (`notifications/initialized`...)
439    let method = message.get("method").and_then(Value::as_str).unwrap_or_default().to_string();
440    let params = message.get("params").cloned().unwrap_or(Value::Null);
441    let result = match method.as_str() {
442        "initialize" => on_ui(poster, timeout, move |ui, reply| reply.send(initialize(ui, server, &params))),
443        "ping" => Ok(json!({})),
444        "tools/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "tools": tools(ui, server) }))),
445        "tools/call" => {
446            let name = params.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
447            let args = params.get("arguments").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
448            on_ui(poster, timeout, move |ui, reply| call_tool(ui, server, name, args, reply)).or_else(|e| Ok(text_result(e, true)))
449        }
450        _ => return Some(http::rpc_error(id, -32601, &format!("método desconhecido: {method}"))),
451    };
452    Some(match result {
453        Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
454        Err(e) => http::rpc_error(id, -32603, &e),
455    })
456}
457
458/// Onde a resposta de uma chamada volta (pode ir para um `on_answer`, depois).
459struct Reply(mpsc::Sender<Value>);
460
461impl Reply {
462    fn send(&self, value: Value) {
463        let _ = self.0.send(value);
464    }
465}
466
467/// Roda `f` na thread da interface e espera a resposta (até `timeout`).
468fn on_ui(poster: &Poster, timeout: Duration, f: impl FnOnce(&mut Ui, Reply) + Send + 'static) -> Result<Value, String> {
469    let (tx, rx) = mpsc::channel();
470    poster.post(move |ui| f(ui, Reply(tx)));
471    rx.recv_timeout(timeout).map_err(|_| "o app não respondeu a tempo".to_string())
472}
473
474fn text_result(text: impl Into<String>, is_error: bool) -> Value {
475    json!({ "content": [{ "type": "text", "text": text.into() }], "isError": is_error })
476}
477
478fn json_text(v: &Value) -> String {
479    match v {
480        Value::String(s) => s.clone(),
481        Value::Null => "ok".into(),
482        other => serde_json::to_string_pretty(other).unwrap_or_default(),
483    }
484}
485
486fn initialize(ui: &Ui, server: ComponentId, params: &Value) -> Value {
487    let (name, mut instructions, expose_ui) = match ui.get::<McpServer>(server) {
488        Some(s) => (s.display_name(ui, server), s.instructions.trim().to_string(), s.expose_ui),
489        None => ("aylis-app".to_string(), String::new(), false),
490    };
491    if expose_ui {
492        if !instructions.is_empty() {
493            instructions.push_str("\n\n");
494        }
495        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).");
496    }
497    json!({
498        "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL),
499        "capabilities": { "tools": { "listChanged": false } },
500        "serverInfo": { "name": name, "version": env!("CARGO_PKG_VERSION") },
501        "instructions": instructions,
502    })
503}
504
505/// As ferramentas filhas do servidor (as ligadas).
506fn app_tools(ui: &Ui, server: ComponentId) -> Vec<(ComponentId, String)> {
507    ui.children(server)
508        .iter()
509        .filter_map(|&c| ui.get::<McpTool>(c).filter(|t| t.enabled).map(|t| (c, t.name_in(ui, c))))
510        .filter(|(_, n)| !n.is_empty())
511        .collect()
512}
513
514fn tool(name: &str, description: &str, properties: Value, required: &[&str], read_only: bool) -> Value {
515    json!({
516        "name": name,
517        "description": description,
518        "inputSchema": { "type": "object", "properties": properties, "required": required },
519        "annotations": { "readOnlyHint": read_only },
520    })
521}
522
523/// A lista que o agente vê: as do app e, com `expose_ui`, as de tela.
524pub fn tools(ui: &Ui, server: ComponentId) -> Vec<Value> {
525    let Some(srv) = ui.get::<McpServer>(server) else { return Vec::new() };
526    let mut out: Vec<Value> = app_tools(ui, server)
527        .into_iter()
528        .filter_map(|(id, name)| {
529            let t = ui.get::<McpTool>(id)?;
530            let schema = t.schema().unwrap_or_else(|_| json!({ "type": "object" }));
531            Some(json!({ "name": name, "description": t.description, "inputSchema": schema, "annotations": { "readOnlyHint": t.read_only } }))
532        })
533        .collect();
534    if srv.expose_ui {
535        out.extend(ui_tools().into_iter().filter(|t| !srv.read_only || READ_TOOLS.contains(&t["name"].as_str().unwrap_or_default())));
536        if srv.read_only {
537            out.push(data_tool(true));
538        }
539    }
540    out
541}
542
543fn ui_tools() -> Vec<Value> {
544    let s = |d: &str| json!({ "type": "string", "description": d });
545    let target = s("o componente: nome ou caminho (frmClientes.edtNome)");
546    vec![
547        tool("ui_forms", "Os forms criados (e DataModules): nome, classe, título, se está aberto (`open`) e visível.", json!({}), &[], true),
548        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),
549        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),
550        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),
551        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),
552        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),
553        tool(
554            "ui_click",
555            "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).",
556            json!({ "target": target, "modifiers": {}, "x": { "type": "number" }, "y": { "type": "number" }, "button": s("left | right | middle"), "double": { "type": "boolean" } }),
557            &["target"],
558            false,
559        ),
560        tool(
561            "ui_drag",
562            "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.",
563            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") }),
564            &["from", "to"],
565            false,
566        ),
567        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),
568        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),
569        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),
570        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),
571        data_tool(false),
572    ]
573}
574
575fn data_tool(read_only: bool) -> Value {
576    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() };
577    tool(
578        "ui_data",
579        &format!("Uma operação num ClientDataSet (`op`: {ops}), com os campos dela (`field`, `value`, `values`, `index`)."),
580        json!({ "target": { "type": "string" }, "op": { "type": "string" }, "field": { "type": "string" }, "value": {}, "values": { "type": "object" }, "index": { "type": "integer" } }),
581        &["target", "op"],
582        read_only,
583    )
584}
585
586/// Uma chamada, na thread da interface: o `on_call`, depois a ferramenta.
587fn call_tool(ui: &mut Ui, server: ComponentId, name: String, args: Value, reply: Reply) {
588    if !ui.get::<McpServer>(server).is_some_and(|s| s.active) {
589        return reply.send(text_result("o servidor MCP foi desligado", true));
590    }
591    if ui.has_handler(server, "on_call") {
592        let info = json!({ "tool": name, "arguments": args }).to_string();
593        match ui.ask(server, "on_call", &EventArgs::Text(info)) {
594            Asked::Answered(Answer::Refused(m)) => return reply.send(text_result(refused(m), true)),
595            Asked::Answered(Answer::Accepted(_)) => {}
596            Asked::Deferred(token) => {
597                return ui.on_answer(token, move |ui, answer| match answer {
598                    Answer::Refused(m) => reply.send(text_result(refused(m), true)),
599                    Answer::Accepted(_) => run_tool(ui, server, &name, &args, reply),
600                });
601            }
602        }
603    }
604    run_tool(ui, server, &name, &args, reply);
605}
606
607fn refused(message: String) -> String {
608    if message.trim().is_empty() { "chamada recusada pelo app".into() } else { message }
609}
610
611fn run_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value, reply: Reply) {
612    if let Some((tool, _)) = app_tools(ui, server).into_iter().find(|(_, n)| n == name) {
613        return execute_tool(ui, tool, args, reply);
614    }
615    let Some(srv) = ui.get::<McpServer>(server) else { return reply.send(text_result("o servidor MCP foi liberado", true)) };
616    let listed = srv.expose_ui && (!srv.read_only || READ_TOOLS.contains(&name) || name == "ui_data");
617    if !listed || !name.starts_with("ui_") {
618        return reply.send(text_result(format!("ferramenta desconhecida: {name}"), true));
619    }
620    let result = ui_tool(ui, server, name, args);
621    // O que a ação disparou (o on_click, o on_change) roda antes da resposta.
622    ui.process_events();
623    reply.send(match result {
624        Ok(v) => text_result(json_text(&v), false),
625        Err(e) => text_result(e, true),
626    });
627}
628
629fn execute_tool(ui: &mut Ui, tool: ComponentId, args: &Value, reply: Reply) {
630    if !ui.has_handler(tool, "on_execute") {
631        let name = ui.name(tool).unwrap_or_default().to_string();
632        return reply.send(text_result(format!("a ferramenta '{name}' não tem o on_execute ligado"), true));
633    }
634    match ui.ask(tool, "on_execute", &EventArgs::Text(args.to_string())) {
635        Asked::Answered(answer) => {
636            ui.process_events();
637            reply.send(answer_result(ui, answer));
638        }
639        Asked::Deferred(token) => ui.on_answer(token, move |ui, answer| reply.send(answer_result(ui, answer))),
640    }
641}
642
643fn answer_result(ui: &Ui, answer: Answer) -> Value {
644    match answer {
645        Answer::Refused(m) => text_result(if m.trim().is_empty() { "a ferramenta recusou".into() } else { m }, true),
646        Answer::Accepted(values) => {
647            let text = values.iter().rev().find(|(k, _)| k == "result").map(|(_, v)| match v {
648                PropValue::String(s) => s.clone(),
649                other => json_text(&aylis_json::prop_to_json(ui, other)),
650            });
651            text_result(text.unwrap_or_else(|| "ok".into()), false)
652        }
653    }
654}
655
656// ---------------------------------------------------------------------------
657// As ferramentas de tela
658
659/// O componente do alvo, se o agente pode chegar nele: nunca o próprio MCP (servidor e
660/// ferramentas, nem dentro deles), e só os forms de `forms`.
661fn reach(ui: &Ui, server: ComponentId, value: Option<&Value>) -> Result<ComponentId, String> {
662    let id = crate::resolve(ui, value.ok_or("falta \"target\"")?)?;
663    let mut at = Some(id);
664    while let Some(c) = at {
665        let class = ui.component(c).map(|c| c.class_name()).unwrap_or_default();
666        if c == server || class == "McpServer" || class == "McpTool" {
667            return Err("o servidor MCP e as ferramentas dele não podem ser comandados por aqui".into());
668        }
669        at = ui.parent(c);
670    }
671    form_allowed(ui, server, ui.root_of(id))?;
672    Ok(id)
673}
674
675fn form_allowed(ui: &Ui, server: ComponentId, form: ComponentId) -> Result<(), String> {
676    let allowed = ui.get::<McpServer>(server).map(McpServer::allowed_forms).unwrap_or_default();
677    let name = ui.name(form).unwrap_or_default();
678    if allowed.is_empty() || allowed.iter().any(|f| f.eq_ignore_ascii_case(name)) {
679        Ok(())
680    } else {
681        Err(format!("o form '{name}' não está liberado para o agente"))
682    }
683}
684
685fn ui_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value) -> Result<Value, String> {
686    let read_only = ui.get::<McpServer>(server).is_some_and(|s| s.read_only);
687    let str_arg = |key: &str| args.get(key).and_then(Value::as_str).unwrap_or_default().to_string();
688    match name {
689        "ui_forms" => Ok(Value::Array(
690            ui.roots()
691                .iter()
692                .filter(|&&r| form_allowed(ui, server, r).is_ok() && !ui.name(r).unwrap_or_default().is_empty())
693                .map(|&r| {
694                    let class = ui.component(r).map(|c| c.class_name()).unwrap_or_default();
695                    let caption = ui.get_prop(r, "caption").ok().and_then(|v| v.to_str().ok().map(str::to_string));
696                    // `open`: a janela está aberta. Um form criado no início e não mostrado
697                    // existe mas não aparece: `visible` só vale aberto
698                    // (antes dizia `true` para todos, e parecia que tinham aberto).
699                    let open = ui.is_open(r);
700                    json!({ "name": ui.name(r), "class": class, "caption": caption, "open": open, "visible": open && ui.control(r).is_some_and(|c| c.visible()) })
701                })
702                .collect(),
703        )),
704        "ui_tree" => {
705            let form = str_arg("form");
706            if form.is_empty() {
707                let roots: Vec<ComponentId> = ui.roots().iter().copied().filter(|&r| form_allowed(ui, server, r).is_ok()).collect();
708                return Ok(Value::Array(roots.into_iter().map(|r| crate::inspect::tree(ui, Some(r))).collect()));
709            }
710            let id = reach(ui, server, Some(&Value::String(form)))?;
711            Ok(crate::inspect::tree(ui, Some(id)))
712        }
713        "ui_get" => {
714            let id = reach(ui, server, args.get("target"))?;
715            match args.get("prop").and_then(Value::as_str).filter(|p| !p.is_empty()) {
716                Some(prop) => crate::get(ui, id, prop),
717                None => Ok(crate::inspect::props(ui, id)),
718            }
719        }
720        "ui_items" => {
721            let id = reach(ui, server, args.get("target"))?;
722            crate::execute(ui, &json!({ "cmd": "items", "target": id.to_u64() }))
723        }
724        "ui_rows" => {
725            let id = reach(ui, server, args.get("target"))?;
726            rows(ui, id, args)
727        }
728        "ui_data" => {
729            let id = reach(ui, server, args.get("target"))?;
730            let op = str_arg("op");
731            if read_only && !READ_DATA_OPS.contains(&op.as_str()) {
732                return Err(format!("o servidor está só para leitura: a operação '{op}' não vale"));
733            }
734            let mut command = args.as_object().cloned().unwrap_or_default();
735            command.insert("cmd".into(), "data".into());
736            command.insert("target".into(), id.to_u64().into());
737            crate::execute(ui, &Value::Object(command))
738        }
739        _ if read_only => Err(format!("o servidor está só para leitura: '{name}' não vale")),
740        "ui_set" => {
741            let id = reach(ui, server, args.get("target"))?;
742            let prop = str_arg("prop");
743            if prop.is_empty() {
744                return Err("falta \"prop\"".into());
745            }
746            let value = args.get("value").cloned().unwrap_or(Value::Null);
747            crate::execute(ui, &json!({ "cmd": "set", "target": id.to_u64(), "props": { prop: value } }))
748        }
749        "ui_click" => {
750            let id = reach(ui, server, args.get("target"))?;
751            // As opções do clique (o mouse de verdade) passam como estão ao protocolo, o mesmo
752            // caminho do `app_command` da IDE.
753            let mut command = json!({ "cmd": "click", "target": id.to_u64() });
754            for key in ["modifiers", "x", "y", "button", "double"] {
755                if let Some(v) = args.get(key) {
756                    command[key] = v.clone();
757                }
758            }
759            crate::execute(ui, &command)
760        }
761        "ui_drag" => {
762            // Os dois lados passam pelo alcance do servidor (os forms permitidos, nunca ele).
763            let (from, to) = (reach(ui, server, args.get("from"))?, reach(ui, server, args.get("to"))?);
764            let mut command = json!({ "cmd": "drag", "from": from.to_u64(), "to": to.to_u64() });
765            for key in ["from_x", "from_y", "to_x", "to_y", "steps", "modifiers", "button"] {
766                if let Some(v) = args.get(key) {
767                    command[key] = v.clone();
768                }
769            }
770            crate::execute(ui, &command)
771        }
772        "ui_click_item" => {
773            let id = reach(ui, server, args.get("target"))?;
774            let mut command = json!({ "cmd": "click_item", "target": id.to_u64() });
775            for key in ["item", "index", "action"] {
776                if let Some(v) = args.get(key) {
777                    command[key] = v.clone();
778                }
779            }
780            crate::execute(ui, &command)
781        }
782        "ui_type" => {
783            let id = reach(ui, server, args.get("target"))?;
784            ui.set_focus(id);
785            crate::execute(ui, &json!({ "cmd": "type", "target": id.to_u64(), "text": str_arg("text") }))
786        }
787        "ui_key" => {
788            let id = reach(ui, server, args.get("target"))?;
789            if ui.root_of(id) != id {
790                ui.set_focus(id);
791            }
792            let mut command = json!({ "cmd": "key", "target": id.to_u64(), "key": str_arg("key") });
793            if let Some(v) = args.get("modifiers") {
794                command["modifiers"] = v.clone();
795            }
796            crate::execute(ui, &command)
797        }
798        "ui_invoke" => {
799            let id = reach(ui, server, args.get("target"))?;
800            crate::execute(ui, &json!({ "cmd": "invoke", "target": id.to_u64(), "method": str_arg("method"), "args": args.get("args").cloned().unwrap_or_else(|| json!([])) }))
801        }
802        _ => Err(format!("ferramenta desconhecida: {name}")),
803    }
804}
805
806/// Os registros de um ClientDataSet, de `offset` até `limit`.
807fn rows(ui: &Ui, id: ComponentId, args: &Value) -> Result<Value, String> {
808    if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
809        return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
810    }
811    let v = aylis_data::view(ui, id);
812    let count = v.record_count();
813    let offset = args.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
814    let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 1000) as usize;
815    let names = v.field_names();
816    let list: Vec<Value> = (offset..count.min(offset.saturating_add(limit)))
817        .map(|i| {
818            let mut row = Map::new();
819            for name in &names {
820                let value = v.value_at(i, name).map(|x| aylis_data::json::value_to_json(&x)).unwrap_or(Value::Null);
821                row.insert(name.clone(), value);
822            }
823            Value::Object(row)
824        })
825        .collect();
826    Ok(json!({ "count": count, "offset": offset, "rows": list }))
827}