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. 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. `server_version` é a versão que o agente vê (vazia: a do app).
9//! - [`McpTool`] (filho do servidor): uma ferramenta do domínio do app, com nome, título,
10//!   descrição, parâmetros, as anotações (`read_only`, `destructive`, `idempotent`) e, com
11//!   `output_schema`, a resposta em JSON (`structuredContent`); o agente chama e o
12//!   `on_execute` responde. É aqui que mora a regra de negócio: `criar_pedido(cliente, itens)`
13//!   em vez de preencher campo por campo.
14//! - [`McpResource`] (filho do servidor): um recurso que o agente lê (`resources/read`), pelo
15//!   endereço (`app://tabelas/clientes`, ou um modelo com `{nome}`): o texto fixo ou o
16//!   `on_read`.
17//! - [`McpPrompt`] (filho do servidor): um prompt pronto que o cliente oferece ao usuário
18//!   (`prompts/get`), com argumentos: o texto com `{argumento}` ou o `on_get`.
19//!
20//! Tudo roda na thread da interface: a conexão chega numa thread, a chamada vai pelo
21//! [`Poster`] e a resposta volta por um canal (até `call_timeout`). O `on_call` do servidor vê
22//! cada chamada antes (o registro, ou recusar: a resposta do agente é o erro), e o `on_result`
23//! depois (a resposta e o tempo). Quando as listas mudam (uma ferramenta ligada, desligada ou
24//! renomeada), o servidor avisa quem ouve o `GET /mcp` (`notifications/*/list_changed`).
25//!
26//! Para conectar o Claude Code: o método `client_command` devolve a linha
27//! (`claude mcp add --transport http ...`, com o endereço e o token; com o `claude` fora do
28//! PATH, pelo caminho completo: [`claude_executable`]). Para o Claude Desktop, que só fala
29//! stdio, a ponte do app publicado ([`stdio`], `app.exe --mcp-stdio`, ligada pela opção
30//! `mcp_stdio` do projeto); o método `stdio_config` devolve a entrada da configuração dele.
31
32pub mod http;
33pub mod stdio;
34
35use std::sync::Arc;
36use std::sync::mpsc;
37use std::time::Duration;
38
39use aylis_core::prop::PropKind;
40use aylis_core::{Answer, Asked, Component, ComponentId, EventArgs, EventCtx, MethodInfo, Poster, PropValue, Ui, properties};
41use serde_json::{Map, Value, json};
42
43/// O executável do Claude Code achado nesta máquina.
44#[derive(Clone, Debug, PartialEq)]
45pub struct ClaudeCode {
46    pub path: std::path::PathBuf,
47    /// Está no PATH (um terminal comum roda `claude`); fora dele, só pelo caminho completo.
48    pub in_path: bool,
49}
50
51/// Acha o `claude` (o Claude Code): no PATH e, fora dele, nos lugares em que os instaladores
52/// põem (`~/.local/bin`, `~/.claude/local`, o npm global) e no que vem com o Claude Desktop
53/// (`%APPDATA%\Claude\claude-code\<versão>\...\claude.exe`, a versão mais nova). No navegador,
54/// nenhum.
55pub fn claude_executable() -> Option<ClaudeCode> {
56    use std::path::{Path, PathBuf};
57    let names: &[&str] = if cfg!(windows) { &["claude.exe", "claude.cmd", "claude"] } else { &["claude"] };
58    let first_in = |dir: &Path| names.iter().map(|n| dir.join(n)).find(|p| p.is_file());
59    if let Some(paths) = std::env::var_os("PATH") {
60        if let Some(path) = std::env::split_paths(&paths).find_map(|d| first_in(&d)) {
61            return Some(ClaudeCode { path, in_path: true });
62        }
63    }
64    let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
65    let mut dirs: Vec<PathBuf> = Vec::new();
66    if let Some(home) = &home {
67        dirs.push(home.join(".local").join("bin"));
68        dirs.push(home.join(".claude").join("local"));
69    }
70    if let Some(appdata) = std::env::var_os("APPDATA").filter(|_| cfg!(windows)) {
71        dirs.push(PathBuf::from(appdata).join("npm"));
72    }
73    if let Some(path) = dirs.iter().find_map(|d| first_in(d)) {
74        return Some(ClaudeCode { path, in_path: false });
75    }
76    // O que vem com o Claude Desktop: claude-code/<versão>/<marca>/claude(.exe).
77    let bundled = if cfg!(windows) {
78        std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("Claude").join("claude-code"))
79    } else if cfg!(target_os = "macos") {
80        home.as_ref().map(|h| h.join("Library/Application Support/Claude/claude-code"))
81    } else {
82        None
83    }?;
84    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() };
85    let mut versions: Vec<PathBuf> = std::fs::read_dir(&bundled).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
86    versions.sort_by_key(|p| std::cmp::Reverse(version(p)));
87    versions.iter().find_map(|v| {
88        let inner = std::fs::read_dir(v).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir());
89        std::iter::once(v.clone()).chain(inner).find_map(|d| first_in(&d))
90    })
91    .map(|path| ClaudeCode { path, in_path: false })
92}
93
94/// A versão do MCP que o aylis fala.
95pub const PROTOCOL: &str = "2025-06-18";
96
97/// O tempo padrão para uma chamada responder, em milissegundos.
98const DEFAULT_TIMEOUT: u32 = 30_000;
99
100/// As ferramentas de tela que só leem (as que `read_only` deixa).
101const READ_TOOLS: &[&str] = &["ui_forms", "ui_tree", "ui_get", "ui_items", "ui_rows"];
102
103/// As operações de dados que não mudam registros (as que `read_only` deixa no `ui_data`).
104const READ_DATA_OPS: &[&str] = &["first", "prior", "next", "last", "move_to", "locate", "value", "text", "record", "info", "field_texts", "field_error", "lookup"];
105
106// ---------------------------------------------------------------------------
107// McpServer
108
109/// Liga o app a agentes de IA pelo MCP. `active` liga (fora do designer); `port` 0 escolhe
110/// uma porta livre (o endereço fica em `url`); `token` vazio gera um aleatório ao ligar.
111/// Só aceita conexões deste computador, com o token.
112///
113/// `expose_ui` dá ao agente as ferramentas genéricas de tela; `read_only` deixa só as que
114/// leem; `forms` (nomes separados por vírgula) limita a quais forms ele chega. O próprio
115/// servidor e as ferramentas nunca são alcançáveis por elas (o agente não se dá mais poder).
116/// As ferramentas, os recursos e os prompts do app são os filhos [`McpTool`], [`McpResource`]
117/// e [`McpPrompt`].
118///
119/// `on_call` dispara antes de cada chamada (o texto é `{"tool": .., "arguments": ..}`, ou
120/// `{"resource": uri}` e `{"prompt": .., "arguments": ..}` nas leituras): recusar
121/// ([`Ui::refuse`]) devolve o erro ao agente. `on_result` dispara depois de cada chamada de
122/// ferramenta, com um [`McpResult`] (a ferramenta, os argumentos, a resposta, se foi erro e o
123/// tempo). `on_error` recebe as falhas ao ligar.
124pub struct McpServer {
125    /// Liga o servidor (fora do designer); desligado, ele para.
126    pub active: bool,
127    /// A porta em `127.0.0.1`; 0: uma porta livre (o endereço fica em `url`).
128    pub port: u32,
129    /// O segredo que o agente precisa mandar; vazio: um aleatório gerado ao ligar.
130    pub token: String,
131    /// O nome que o agente vê (vazio: o nome do componente).
132    pub server_name: String,
133    /// A versão que o agente vê (`serverInfo.version`); vazia: a do app (a da publicação).
134    pub server_version: String,
135    /// O que o agente lê ao conectar: para que serve o app e como usar as ferramentas.
136    pub instructions: String,
137    /// Dá ao agente as ferramentas genéricas de tela (ler a árvore, mexer em propriedades,
138    /// clicar, os dados).
139    pub expose_ui: bool,
140    /// Das ferramentas de tela, só as que leem (nenhuma muda a tela nem os registros).
141    pub read_only: bool,
142    /// Os forms que o agente alcança, por nome separados por vírgula; vazio: todos.
143    pub forms: String,
144    /// Quanto uma chamada pode demorar, em milissegundos (vale ao ligar).
145    pub call_timeout: u32,
146    running: Option<http::HttpServer>,
147    /// O endereço gravado para a ponte stdio (só com a opção `mcp_stdio` do projeto).
148    discovery: Option<stdio::Discovery>,
149    /// O resumo das listas (ferramentas, recursos, prompts) da última vez que o agente soube
150    /// delas (`None`: ainda não olhou).
151    lists: Option<[u64; 3]>,
152    /// Já tentou ligar com a configuração atual (uma falha não repete a cada volta do timer).
153    attempted: bool,
154    last_error: String,
155}
156
157impl Default for McpServer {
158    fn default() -> Self {
159        Self {
160            active: false,
161            port: 0,
162            token: String::new(),
163            server_name: String::new(),
164            server_version: String::new(),
165            instructions: String::new(),
166            expose_ui: false,
167            read_only: false,
168            forms: String::new(),
169            call_timeout: DEFAULT_TIMEOUT,
170            running: None,
171            discovery: None,
172            lists: None,
173            attempted: false,
174            last_error: String::new(),
175        }
176    }
177}
178
179impl McpServer {
180    /// O endereço dos clientes (vazio: parado).
181    pub fn url(&self) -> String {
182        self.running.as_ref().map(http::HttpServer::url).unwrap_or_default()
183    }
184
185    pub fn running(&self) -> bool {
186        self.running.is_some()
187    }
188
189    /// Quantos clientes ouvem os avisos do servidor (o `GET /mcp`).
190    pub fn listeners(&self) -> usize {
191        self.running.as_ref().map_or(0, http::HttpServer::listeners)
192    }
193
194    /// A falha da última tentativa de ligar (vazia: nenhuma).
195    pub fn last_error(&self) -> String {
196        self.last_error.clone()
197    }
198
199    /// A linha que liga o Claude Code a este app (vazia: parado). Com o `claude` fora do PATH
200    /// (o que vem com o Claude Desktop, por exemplo), a linha leva o caminho completo dele,
201    /// para rodar num terminal comum.
202    pub fn client_command(&self, ui: &Ui, id: ComponentId) -> String {
203        if self.running.is_none() {
204            return String::new();
205        }
206        let name = self.display_name(ui, id).replace(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_', "-");
207        let claude = match claude_executable() {
208            Some(ClaudeCode { path, in_path: false }) => format!("\"{}\"", path.display()),
209            _ => "claude".to_string(),
210        };
211        format!("{claude} mcp add --transport http {name} {} --header \"Authorization: Bearer {}\"", self.url(), self.token)
212    }
213
214    /// A entrada do Claude Desktop (`claude_desktop_config.json`) para este app pela ponte
215    /// stdio: o executável com `--mcp-stdio` e o nome do servidor (o token não vai: a ponte
216    /// acha sozinha). Erro com a ponte desligada.
217    pub fn stdio_config(&self, ui: &Ui, id: ComponentId) -> Result<String, String> {
218        if !stdio::enabled() {
219            return Err("a ponte stdio está desligada: ligue a opção mcp_stdio do projeto".into());
220        }
221        let exe = std::env::current_exe().map_err(|e| e.to_string())?;
222        let name = self.display_name(ui, id);
223        let entry = json!({ "command": exe.to_string_lossy(), "args": ["--mcp-stdio", name] });
224        Ok(serde_json::to_string_pretty(&json!({ "mcpServers": { name: entry } })).unwrap_or_default())
225    }
226
227    fn display_name(&self, ui: &Ui, id: ComponentId) -> String {
228        if !self.server_name.trim().is_empty() {
229            return self.server_name.trim().to_string();
230        }
231        ui.name(id).filter(|n| !n.is_empty()).unwrap_or("aylis-app").to_string()
232    }
233
234    /// A versão que o agente vê: `server_version`, a do app ou, sem as duas, a do Aylis.
235    fn version(&self) -> String {
236        let own = self.server_version.trim();
237        if !own.is_empty() {
238            return own.to_string();
239        }
240        let app = stdio::app_version();
241        if app.is_empty() { env!("CARGO_PKG_VERSION").to_string() } else { app }
242    }
243
244    fn allowed_forms(&self) -> Vec<String> {
245        self.forms.split([',', ';']).map(str::trim).filter(|f| !f.is_empty()).map(str::to_string).collect()
246    }
247
248    fn set_s(&mut self, _: String) {}
249    fn set_b(&mut self, _: bool) {}
250
251    /// Liga ou desliga conforme `active` (nunca no designer).
252    fn sync(&mut self, ctx: &mut EventCtx<'_>) {
253        if ctx.ui.design_mode() {
254            return;
255        }
256        if !self.active {
257            self.stop();
258            self.attempted = false;
259            return;
260        }
261        if self.running.is_some() || self.attempted {
262            return;
263        }
264        self.attempted = true;
265        match self.start(ctx.ui.poster(), ctx.id) {
266            Ok(server) => {
267                self.last_error.clear();
268                if stdio::enabled() {
269                    // A ponte stdio do app publicado acha este servidor por aqui.
270                    match stdio::publish(&self.display_name(ctx.ui, ctx.id), server.port(), &self.token) {
271                        Ok(d) => self.discovery = Some(d),
272                        Err(e) => aylis_core::stderr_line!("MCP: a ponte stdio não vai achar o servidor: {e}"),
273                    }
274                }
275                self.running = Some(server);
276                // O ponto de partida das listas (o aviso de mudança compara com ele).
277                let id = ctx.id;
278                ctx.ui.poster().post(move |ui| check_lists(ui, id));
279            }
280            Err(e) => {
281                self.last_error = e.clone();
282                ctx.fire("on_error", EventArgs::Text(e));
283            }
284        }
285    }
286
287    /// Para o servidor (e apaga o endereço da ponte).
288    fn stop(&mut self) {
289        self.running = None;
290        self.discovery = None;
291        self.lists = None;
292    }
293
294    fn start(&mut self, poster: Poster, id: ComponentId) -> Result<http::HttpServer, String> {
295        let port = u16::try_from(self.port).map_err(|_| format!("MCP: porta inválida: {}", self.port))?;
296        if self.token.is_empty() {
297            self.token = random_token()?;
298        }
299        let timeout = Duration::from_millis(u64::from(if self.call_timeout == 0 { DEFAULT_TIMEOUT } else { self.call_timeout }));
300        http::start(port, self.token.clone(), "aylis-mcp", Arc::new(move |message| handle_message(message, &poster, id, timeout)))
301    }
302}
303
304impl Component for McpServer {
305    fn timed(&self) -> Option<&dyn aylis_core::Timed> {
306        Some(self)
307    }
308
309    fn timed_mut(&mut self) -> Option<&mut dyn aylis_core::Timed> {
310        Some(self)
311    }
312
313    fn class_name(&self) -> &'static str {
314        "McpServer"
315    }
316
317    properties! {
318        active: bool => "Behavior",
319        port: u32 => "Behavior",
320        token: String => "Behavior",
321        server_name: String => "Behavior",
322        server_version: String => "Behavior",
323        instructions: String => "Behavior",
324        expose_ui: bool => "Behavior",
325        read_only: bool => "Behavior",
326        forms: String => "Behavior",
327        call_timeout: u32 as Duration => "Behavior";
328        events: on_call, on_result: McpResult, on_error: String;
329        computed: url: String => url / set_s, running: bool => running / set_b, last_error: String => last_error / set_s
330    }
331
332    fn methods(&self) -> &'static [MethodInfo] {
333        const METHODS: &[MethodInfo] = &[
334            MethodInfo::new("client_command", &[], Some(PropKind::String)),
335            MethodInfo::new("stdio_config", &[], Some(PropKind::String)),
336            MethodInfo::new("notify_lists_changed", &[], None),
337        ];
338        METHODS
339    }
340
341    fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, _args: &[PropValue]) -> Result<PropValue, String> {
342        match method {
343            "client_command" => Ok(PropValue::String(self.client_command(ctx.ui, ctx.id))),
344            "stdio_config" => self.stdio_config(ctx.ui, ctx.id).map(PropValue::String),
345            "notify_lists_changed" => {
346                // Depois do método, com o servidor de volta ao `Ui` (as listas lidas inteiras).
347                let id = ctx.id;
348                ctx.ui.poster().post(move |ui| check_lists(ui, id));
349                Ok(PropValue::Null)
350            }
351            _ => Err(format!("McpServer não tem o método '{method}'")),
352        }
353    }
354
355    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
356        if matches!(name, "port" | "token" | "call_timeout" | "server_name") && self.running.is_some() {
357            // Religa com a configuração nova.
358            self.stop();
359            self.attempted = false;
360        }
361        if name == "active" {
362            self.attempted = false;
363        }
364        self.sync(ctx);
365    }
366
367    // Carregado de um form com `active` ligado, liga na primeira volta do timer.
368}
369
370impl aylis_core::Timed for McpServer {
371    fn timer_interval(&self) -> Option<f64> {
372        (self.active && self.running.is_none() && !self.attempted).then_some(0.2)
373    }
374
375    fn timer(&mut self, ctx: &mut EventCtx<'_>) {
376        self.sync(ctx);
377    }
378}
379
380#[cfg(not(target_arch = "wasm32"))]
381fn random_token() -> Result<String, String> {
382    let mut bytes = [0u8; 32];
383    getrandom::fill(&mut bytes).map_err(|e| format!("MCP: sem gerador aleatório do sistema: {e}"))?;
384    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
385}
386
387#[cfg(target_arch = "wasm32")]
388fn random_token() -> Result<String, String> {
389    Err("MCP: o navegador não abre portas (use o app de desktop)".into())
390}
391
392/// O fim de uma chamada de ferramenta (o `on_result` do [`McpServer`]).
393#[derive(Clone, Debug, Default, PartialEq)]
394pub struct McpResult {
395    /// O nome da ferramenta.
396    pub tool: String,
397    /// Os argumentos, em JSON.
398    pub arguments: String,
399    /// A resposta que o agente recebeu (o texto; com JSON, o JSON).
400    pub result: String,
401    pub is_error: bool,
402    /// Quanto a chamada levou, em milissegundos (do `on_call` à resposta).
403    pub elapsed_ms: i64,
404}
405
406/// O registro do [`McpResult`] no acesso tipado.
407pub const MCP_RESULT: aylis_core::RecordInfo = aylis_core::RecordInfo {
408    name: "McpResult",
409    fields: &[("tool", PropKind::String), ("arguments", PropKind::String), ("result", PropKind::String), ("is_error", PropKind::Bool), ("elapsed_ms", PropKind::Int)],
410};
411
412impl McpResult {
413    fn to_json(&self) -> String {
414        json!({ "tool": self.tool, "arguments": self.arguments, "result": self.result, "is_error": self.is_error, "elapsed_ms": self.elapsed_ms }).to_string()
415    }
416}
417
418impl aylis_core::EventValue for McpResult {
419    const ARG: aylis_core::EventArg = aylis_core::EventArg::Value(PropKind::Record(&MCP_RESULT));
420    fn from_args(args: &EventArgs) -> Option<Self> {
421        let v: Value = serde_json::from_str(args.text()?).ok()?;
422        let s = |k: &str| v[k].as_str().unwrap_or_default().to_string();
423        Some(McpResult { tool: s("tool"), arguments: s("arguments"), result: s("result"), is_error: v["is_error"].as_bool().unwrap_or(false), elapsed_ms: v["elapsed_ms"].as_i64().unwrap_or(0) })
424    }
425}
426
427// ---------------------------------------------------------------------------
428// McpTool
429
430/// Uma ferramenta do app para o agente (filha de um [`McpServer`]). `tool_name` é o nome que
431/// ele chama (vazio: o nome do componente), `title` o nome para pessoas, `description` diz
432/// quando usar, e `params` os parâmetros: um JSON Schema (`{"type": "object", "properties":
433/// {..}}`), só as propriedades (`{"cliente": {"type": "string"}}`) ou a forma curta
434/// `cliente: string, quantidade: integer, obs?: string` (o `?` marca o opcional).
435///
436/// As anotações avisam o agente (e o cliente, que pode pedir confirmação ao usuário):
437/// `read_only` (só lê), `destructive` (pode apagar ou estragar dados; o padrão, como no MCP,
438/// é `true`; só vale sem `read_only`) e `idempotent` (chamar de novo com os mesmos argumentos
439/// não muda mais nada).
440///
441/// `on_execute` recebe os argumentos (o texto do evento é o JSON; [`McpTool::arguments`]
442/// lê) e responde com [`McpTool::reply`] (ou `ui.reply("result", ..)`); recusar
443/// ([`Ui::refuse`]) devolve o erro. Um backend em outra linguagem responde depois, como em
444/// todo evento-pergunta. Uma resposta que é um objeto JSON vai também como
445/// `structuredContent`; com `output_schema` (a mesma forma do `params`), o agente sabe o
446/// formato de antemão, e a resposta precisa ser um objeto JSON.
447pub struct McpTool {
448    /// O nome que o agente chama; vazio: o nome do componente.
449    pub tool_name: String,
450    /// O nome para pessoas (o cliente mostra); vazio: nenhum.
451    pub title: String,
452    /// O que a ferramenta faz e quando usar (o agente lê para escolher).
453    pub description: String,
454    /// Os parâmetros: um JSON Schema, só as propriedades ou a forma curta
455    /// `cliente: string, quantidade: integer, obs?: string` (`?`: opcional); vazio: nenhum.
456    pub params: String,
457    /// O formato da resposta (JSON Schema, só as propriedades ou a forma curta); vazio: livre.
458    pub output_schema: String,
459    /// Avisa o agente que a ferramenta só lê, não muda nada.
460    pub read_only: bool,
461    /// Avisa que a ferramenta pode apagar ou estragar dados (sem `read_only`).
462    pub destructive: bool,
463    /// Avisa que repetir a chamada com os mesmos argumentos não muda mais nada.
464    pub idempotent: bool,
465    /// Oferecida ao agente; desligada, ele não a vê.
466    pub enabled: bool,
467}
468
469impl Default for McpTool {
470    fn default() -> Self {
471        Self {
472            tool_name: String::new(),
473            title: String::new(),
474            description: String::new(),
475            params: String::new(),
476            output_schema: String::new(),
477            read_only: false,
478            destructive: true,
479            idempotent: false,
480            enabled: true,
481        }
482    }
483}
484
485impl McpTool {
486    /// Os argumentos que o agente mandou (no `on_execute`).
487    pub fn arguments(args: &EventArgs) -> Value {
488        args.text().and_then(|t| serde_json::from_str(t).ok()).unwrap_or_else(|| json!({}))
489    }
490
491    /// Responde o `on_execute`: um texto, ou JSON (vai como texto JSON e, sendo um objeto,
492    /// também como `structuredContent`).
493    pub fn reply(ui: &mut Ui, result: impl Into<Value>) {
494        let text = match result.into() {
495            Value::String(s) => s,
496            other => serde_json::to_string_pretty(&other).unwrap_or_default(),
497        };
498        ui.reply("result", PropValue::String(text));
499    }
500
501    /// O nome que o agente chama.
502    pub fn name_in(&self, ui: &Ui, id: ComponentId) -> String {
503        let name = self.tool_name.trim();
504        if name.is_empty() { ui.name(id).unwrap_or_default().to_string() } else { name.to_string() }
505    }
506
507    /// O JSON Schema dos argumentos, a partir de `params`.
508    pub fn schema(&self) -> Result<Value, String> {
509        parse_schema(&self.params, "params")
510    }
511
512    /// O JSON Schema da resposta (`None`: sem `output_schema`).
513    pub fn output(&self) -> Result<Option<Value>, String> {
514        if self.output_schema.trim().is_empty() {
515            return Ok(None);
516        }
517        parse_schema(&self.output_schema, "output_schema").map(Some)
518    }
519
520    /// A ferramenta como o agente vê no `tools/list`.
521    fn listed(&self, name: &str) -> Value {
522        let schema = self.schema().unwrap_or_else(|_| json!({ "type": "object" }));
523        let mut annotations = json!({ "readOnlyHint": self.read_only, "idempotentHint": self.idempotent });
524        if !self.read_only {
525            annotations["destructiveHint"] = Value::Bool(self.destructive);
526        }
527        let mut tool = json!({ "name": name, "description": self.description, "inputSchema": schema });
528        if !self.title.trim().is_empty() {
529            tool["title"] = Value::String(self.title.trim().to_string());
530            annotations["title"] = Value::String(self.title.trim().to_string());
531        }
532        tool["annotations"] = annotations;
533        if let Ok(Some(output)) = self.output() {
534            tool["outputSchema"] = output;
535        }
536        tool
537    }
538}
539
540/// Um JSON Schema de objeto a partir do texto: o schema, só as propriedades ou a forma curta
541/// `nome: tipo, outro?: tipo`.
542fn parse_schema(text: &str, what: &str) -> Result<Value, String> {
543    let text = text.trim();
544    if text.is_empty() {
545        return Ok(json!({ "type": "object", "properties": {} }));
546    }
547    if text.starts_with('{') {
548        let v: Value = serde_json::from_str(text).map_err(|e| format!("{what}: JSON inválido: {e}"))?;
549        if v.get("type").is_some() {
550            return Ok(v);
551        }
552        return Ok(json!({ "type": "object", "properties": v }));
553    }
554    // A forma curta: `nome: tipo, outro?: tipo`.
555    let mut properties = Map::new();
556    let mut required = Vec::new();
557    for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) {
558        let (name, kind) = part.split_once(':').map_or((part, "string"), |(n, k)| (n.trim(), k.trim()));
559        let (name, optional) = match name.strip_suffix('?') {
560            Some(n) => (n.trim(), true),
561            None => (name, false),
562        };
563        if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
564            return Err(format!("{what}: nome inválido: '{part}'"));
565        }
566        let kind = match kind.to_ascii_lowercase().as_str() {
567            "" | "string" | "text" | "texto" => "string",
568            "integer" | "int" | "inteiro" => "integer",
569            "number" | "float" | "numero" | "número" => "number",
570            "boolean" | "bool" => "boolean",
571            "object" | "objeto" => "object",
572            "array" | "lista" => "array",
573            other => return Err(format!("{what}: tipo desconhecido '{other}' em '{part}'")),
574        };
575        properties.insert(name.to_string(), json!({ "type": kind }));
576        if !optional {
577            required.push(Value::String(name.to_string()));
578        }
579    }
580    Ok(json!({ "type": "object", "properties": properties, "required": required }))
581}
582
583/// Avisa o servidor pai que uma lista mudou (depois: o filho está fora do `Ui` agora).
584fn child_changed(ctx: &mut EventCtx<'_>) {
585    if let Some(server) = ctx.ui.parent(ctx.id) {
586        ctx.ui.poster().post(move |ui| check_lists(ui, server));
587    }
588}
589
590impl Component for McpTool {
591    fn class_name(&self) -> &'static str {
592        "McpTool"
593    }
594
595    properties! {
596        tool_name: String => "Behavior",
597        title: String => "Behavior",
598        description: String => "Behavior",
599        params: String => "Behavior",
600        output_schema: String => "Behavior",
601        read_only: bool => "Behavior",
602        destructive: bool => "Behavior",
603        idempotent: bool => "Behavior",
604        enabled: bool => "Behavior";
605        events: on_execute
606    }
607
608    fn default_event(&self) -> Option<&'static str> {
609        Some("on_execute")
610    }
611
612    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, _name: &str) {
613        child_changed(ctx);
614    }
615}
616
617// ---------------------------------------------------------------------------
618// McpResource
619
620/// Um recurso que o agente lê (filho de um [`McpServer`]): um conteúdo do app pelo endereço
621/// (`uri`: `app://tabelas/clientes`), com nome, título, descrição e tipo (`mime_type`). Um
622/// `uri` com `{nome}` é um modelo (`app://tabelas/{tabela}`): vale para todo endereço que bate
623/// com ele, e o `on_read` recebe os pedaços.
624///
625/// O conteúdo é o `text` fixo ou, com o `on_read` ligado, a resposta dele: o evento recebe
626/// `{"uri": .., "params": {"tabela": ..}}` e responde com `ui.reply("result", texto)` (ou
627/// [`McpTool::reply`]); recusar devolve o erro.
628pub struct McpResource {
629    /// O endereço (ou o modelo, com `{nome}`).
630    pub uri: String,
631    /// O nome que o agente vê; vazio: o nome do componente.
632    pub resource_name: String,
633    /// O título que o cliente mostra (vazio: o nome).
634    pub title: String,
635    /// O que o recurso tem, para o agente decidir se o lê.
636    pub description: String,
637    /// O tipo do conteúdo (`text/plain`, `application/json`, `text/markdown`...).
638    pub mime_type: String,
639    /// O conteúdo fixo (sem `on_read`).
640    pub text: String,
641    /// Oferecido ao agente; desligado, ele não vê.
642    pub enabled: bool,
643}
644
645impl Default for McpResource {
646    fn default() -> Self {
647        Self { uri: String::new(), resource_name: String::new(), title: String::new(), description: String::new(), mime_type: "text/plain".into(), text: String::new(), enabled: true }
648    }
649}
650
651impl McpResource {
652    fn name_in(&self, ui: &Ui, id: ComponentId) -> String {
653        let name = self.resource_name.trim();
654        if name.is_empty() { ui.name(id).unwrap_or_default().to_string() } else { name.to_string() }
655    }
656
657    /// Um modelo (`{nome}` no endereço).
658    pub fn is_template(&self) -> bool {
659        self.uri.contains('{')
660    }
661
662    /// Os pedaços de `uri` pelo modelo (`None`: não bate). Sem modelo, só o endereço igual.
663    pub fn matches(&self, uri: &str) -> Option<Map<String, Value>> {
664        if !self.is_template() {
665            return (self.uri.trim() == uri).then(Map::new);
666        }
667        match_template(self.uri.trim(), uri)
668    }
669
670    fn listed(&self, name: &str) -> Value {
671        let mut v = json!({ "name": name, "mimeType": self.mime_type });
672        v[if self.is_template() { "uriTemplate" } else { "uri" }] = Value::String(self.uri.trim().to_string());
673        if !self.title.trim().is_empty() {
674            v["title"] = Value::String(self.title.trim().to_string());
675        }
676        if !self.description.trim().is_empty() {
677            v["description"] = Value::String(self.description.clone());
678        }
679        v
680    }
681}
682
683/// Os pedaços de `uri` por um modelo com `{nome}` (cada um vai até o próximo trecho fixo; o
684/// último, até o fim). Um pedaço não fica vazio nem atravessa `/`, a menos que seja o último.
685fn match_template(template: &str, uri: &str) -> Option<Map<String, Value>> {
686    let mut params = Map::new();
687    let (mut t, mut u) = (template, uri);
688    loop {
689        let Some(open) = t.find('{') else { return (t == u).then_some(params) };
690        let (fixed, rest) = t.split_at(open);
691        u = u.strip_prefix(fixed)?;
692        let close = rest.find('}')?;
693        let name = &rest[1..close];
694        t = &rest[close + 1..];
695        let end = match t.find('{').map_or(t, |i| &t[..i]) {
696            "" if t.is_empty() => u.len(),
697            "" => return None,
698            next => u.find(next)?,
699        };
700        let value = &u[..end];
701        if value.is_empty() || (!t.is_empty() && value.contains('/')) {
702            return None;
703        }
704        params.insert(name.to_string(), Value::String(value.to_string()));
705        u = &u[end..];
706    }
707}
708
709impl Component for McpResource {
710    fn class_name(&self) -> &'static str {
711        "McpResource"
712    }
713
714    properties! {
715        uri: String => "Behavior",
716        resource_name: String => "Behavior",
717        title: String => "Behavior",
718        description: String => "Behavior",
719        mime_type: String => "Behavior",
720        text: String => "Behavior",
721        enabled: bool => "Behavior";
722        events: on_read
723    }
724
725    fn default_event(&self) -> Option<&'static str> {
726        Some("on_read")
727    }
728
729    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, _name: &str) {
730        child_changed(ctx);
731    }
732}
733
734// ---------------------------------------------------------------------------
735// McpPrompt
736
737/// Um prompt pronto (filho de um [`McpServer`]): o cliente oferece ao usuário (no Claude
738/// Desktop, no menu de prompts) e manda ao agente o texto montado. `arguments` são os
739/// argumentos, separados por `;`: `cliente: o código do cliente; periodo?: o mês (AAAA-MM)`
740/// (o `?` marca o opcional; depois do `:`, a descrição).
741///
742/// O texto é o `text` com cada `{argumento}` trocado pelo valor, ou, com o `on_get` ligado, a
743/// resposta dele (o evento recebe os argumentos em JSON e responde com
744/// `ui.reply("result", texto)`).
745pub struct McpPrompt {
746    /// O nome que o cliente usa; vazio: o nome do componente.
747    pub prompt_name: String,
748    /// O título que o cliente mostra no menu de prompts (vazio: o nome).
749    pub title: String,
750    /// Para que serve o prompt, mostrado ao escolher.
751    pub description: String,
752    /// Os argumentos: `nome: descrição; outro?: descrição` (`?`: opcional).
753    pub arguments: String,
754    /// O texto do prompt, com `{argumento}` (sem `on_get`).
755    pub text: String,
756    /// Oferecido ao cliente; desligado, ele não vê.
757    pub enabled: bool,
758}
759
760impl Default for McpPrompt {
761    fn default() -> Self {
762        Self { prompt_name: String::new(), title: String::new(), description: String::new(), arguments: String::new(), text: String::new(), enabled: true }
763    }
764}
765
766impl McpPrompt {
767    fn name_in(&self, ui: &Ui, id: ComponentId) -> String {
768        let name = self.prompt_name.trim();
769        if name.is_empty() { ui.name(id).unwrap_or_default().to_string() } else { name.to_string() }
770    }
771
772    /// Os argumentos: o nome, a descrição e se é obrigatório.
773    pub fn argument_list(&self) -> Vec<(String, String, bool)> {
774        self.arguments
775            .split([';', '\n'])
776            .map(str::trim)
777            .filter(|a| !a.is_empty())
778            .map(|a| {
779                let (name, description) = a.split_once(':').map_or((a, ""), |(n, d)| (n.trim(), d.trim()));
780                match name.strip_suffix('?') {
781                    Some(n) => (n.trim().to_string(), description.to_string(), false),
782                    None => (name.to_string(), description.to_string(), true),
783                }
784            })
785            .collect()
786    }
787
788    /// O texto com cada `{argumento}` trocado pelo valor.
789    pub fn fill(&self, args: &Map<String, Value>) -> String {
790        let mut text = self.text.clone();
791        for (name, _, _) in self.argument_list() {
792            let value = args.get(&name).map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)).unwrap_or_default();
793            text = text.replace(&format!("{{{name}}}"), &value);
794        }
795        text
796    }
797
798    fn listed(&self, name: &str) -> Value {
799        let arguments: Vec<Value> = self.argument_list().into_iter().map(|(n, d, r)| json!({ "name": n, "description": d, "required": r })).collect();
800        let mut v = json!({ "name": name, "arguments": arguments });
801        if !self.title.trim().is_empty() {
802            v["title"] = Value::String(self.title.trim().to_string());
803        }
804        if !self.description.trim().is_empty() {
805            v["description"] = Value::String(self.description.clone());
806        }
807        v
808    }
809}
810
811impl Component for McpPrompt {
812    fn class_name(&self) -> &'static str {
813        "McpPrompt"
814    }
815
816    properties! {
817        prompt_name: String => "Behavior",
818        title: String => "Behavior",
819        description: String => "Behavior",
820        arguments: String => "Behavior",
821        text: String => "Behavior",
822        enabled: bool => "Behavior";
823        events: on_get
824    }
825
826    fn default_event(&self) -> Option<&'static str> {
827        Some("on_get")
828    }
829
830    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, _name: &str) {
831        child_changed(ctx);
832    }
833}
834
835/// Registra as classes do MCP.
836pub fn register(ui: &mut Ui) {
837    ui.register_class::<McpServer>("System");
838    ui.register_class::<McpTool>("System");
839    ui.register_class::<McpResource>("System");
840    ui.register_class::<McpPrompt>("System");
841}
842
843// ---------------------------------------------------------------------------
844// As listas e o aviso de mudança
845
846/// Os filhos ligados de uma classe, com o nome que o agente vê.
847fn children_of<T: Component>(ui: &Ui, server: ComponentId, name: impl Fn(&T, ComponentId) -> Option<String>) -> Vec<(ComponentId, String)> {
848    ui.children(server).iter().filter_map(|&c| ui.get::<T>(c).and_then(|t| name(t, c)).map(|n| (c, n))).filter(|(_, n)| !n.is_empty()).collect()
849}
850
851/// As ferramentas filhas do servidor (as ligadas).
852fn app_tools(ui: &Ui, server: ComponentId) -> Vec<(ComponentId, String)> {
853    children_of::<McpTool>(ui, server, |t, c| t.enabled.then(|| t.name_in(ui, c)))
854}
855
856fn app_resources(ui: &Ui, server: ComponentId) -> Vec<(ComponentId, String)> {
857    children_of::<McpResource>(ui, server, |r, c| (r.enabled && !r.uri.trim().is_empty()).then(|| r.name_in(ui, c)))
858}
859
860fn app_prompts(ui: &Ui, server: ComponentId) -> Vec<(ComponentId, String)> {
861    children_of::<McpPrompt>(ui, server, |p, c| p.enabled.then(|| p.name_in(ui, c)))
862}
863
864/// Os recursos fixos (`resources/list`) e os modelos (`resources/templates/list`).
865fn resources(ui: &Ui, server: ComponentId, templates: bool) -> Vec<Value> {
866    app_resources(ui, server).into_iter().filter_map(|(id, name)| ui.get::<McpResource>(id).filter(|r| r.is_template() == templates).map(|r| r.listed(&name))).collect()
867}
868
869fn prompts(ui: &Ui, server: ComponentId) -> Vec<Value> {
870    app_prompts(ui, server).into_iter().filter_map(|(id, name)| ui.get::<McpPrompt>(id).map(|p| p.listed(&name))).collect()
871}
872
873fn digest(values: &[Value]) -> u64 {
874    let text = serde_json::to_string(values).unwrap_or_default();
875    text.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))
876}
877
878/// Compara as listas com as da última vez e avisa o agente das que mudaram
879/// (`notifications/tools/list_changed` e as de recursos e prompts). Na primeira vez, só guarda.
880pub fn check_lists(ui: &mut Ui, server: ComponentId) {
881    if !ui.get::<McpServer>(server).is_some_and(McpServer::running) {
882        return;
883    }
884    let mut all = resources(ui, server, false);
885    all.extend(resources(ui, server, true));
886    let now = [digest(&tools(ui, server)), digest(&all), digest(&prompts(ui, server))];
887    let Some(srv) = ui.get_mut::<McpServer>(server) else { return };
888    let before = srv.lists.replace(now);
889    let Some(before) = before else { return };
890    let Some(running) = &srv.running else { return };
891    for (i, kind) in ["tools", "resources", "prompts"].iter().enumerate() {
892        if before[i] != now[i] {
893            running.notify(&json!({ "jsonrpc": "2.0", "method": format!("notifications/{kind}/list_changed") }));
894        }
895    }
896}
897
898// ---------------------------------------------------------------------------
899// JSON-RPC
900
901/// Responde uma mensagem JSON-RPC na thread da conexão (`None` para notificações).
902fn handle_message(message: Value, poster: &Poster, server: ComponentId, timeout: Duration) -> Option<Value> {
903    let id = message.get("id").cloned()?; // notificação (`notifications/initialized`...)
904    let method = message.get("method").and_then(Value::as_str).unwrap_or_default().to_string();
905    let params = message.get("params").cloned().unwrap_or(Value::Null);
906    let result = match method.as_str() {
907        "initialize" => on_ui(poster, timeout, move |ui, reply| reply.send(initialize(ui, server, &params))),
908        "ping" => Ok(json!({})),
909        "tools/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "tools": tools(ui, server) }))),
910        "tools/call" => {
911            let name = params.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
912            let args = params.get("arguments").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
913            on_ui(poster, timeout, move |ui, reply| call_tool(ui, server, name, args, reply)).or_else(|e| Ok(text_result(e, true)))
914        }
915        "resources/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "resources": resources(ui, server, false) }))),
916        "resources/templates/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "resourceTemplates": resources(ui, server, true) }))),
917        "resources/read" => {
918            let uri = params.get("uri").and_then(Value::as_str).unwrap_or_default().to_string();
919            match on_ui(poster, timeout, move |ui, reply| read_resource(ui, server, uri, reply)) {
920                Ok(v) if v.get("error").is_some() => return Some(json!({ "jsonrpc": "2.0", "id": id, "error": v["error"] })),
921                other => other,
922            }
923        }
924        "prompts/list" => on_ui(poster, timeout, move |ui, reply| reply.send(json!({ "prompts": prompts(ui, server) }))),
925        "prompts/get" => {
926            let name = params.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
927            let args = params.get("arguments").and_then(Value::as_object).cloned().unwrap_or_default();
928            match on_ui(poster, timeout, move |ui, reply| get_prompt(ui, server, name, args, reply)) {
929                Ok(v) if v.get("error").is_some() => return Some(json!({ "jsonrpc": "2.0", "id": id, "error": v["error"] })),
930                other => other,
931            }
932        }
933        _ => return Some(http::rpc_error(id, -32601, &format!("método desconhecido: {method}"))),
934    };
935    Some(match result {
936        Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
937        Err(e) => http::rpc_error(id, -32603, &e),
938    })
939}
940
941/// Onde a resposta de uma chamada volta (pode ir para um `on_answer`, depois). Numa chamada
942/// de ferramenta, leva também o que o `on_result` conta.
943struct Reply {
944    tx: mpsc::Sender<Value>,
945    call: Option<CallInfo>,
946}
947
948/// A chamada em andamento, para o `on_result`.
949struct CallInfo {
950    server: ComponentId,
951    tool: String,
952    arguments: String,
953    started: f64,
954}
955
956impl Reply {
957    fn send(&self, value: Value) {
958        let _ = self.tx.send(value);
959    }
960
961    /// A resposta de uma ferramenta: o `on_result` do servidor e, depois, o agente.
962    fn finish(self, ui: &mut Ui, value: Value) {
963        if let Some(call) = &self.call {
964            let result = match value.get("structuredContent") {
965                Some(s) => s.to_string(),
966                None => value["content"][0]["text"].as_str().unwrap_or_default().to_string(),
967            };
968            let report = McpResult {
969                tool: call.tool.clone(),
970                arguments: call.arguments.clone(),
971                result,
972                is_error: value["isError"] == true,
973                elapsed_ms: ((ui.time() - call.started) * 1000.0).max(0.0).round() as i64,
974            };
975            if ui.has_handler(call.server, "on_result") {
976                ui.fire(call.server, "on_result", &EventArgs::Text(report.to_json()));
977            }
978        }
979        self.send(value);
980    }
981}
982
983/// Roda `f` na thread da interface e espera a resposta (até `timeout`).
984fn on_ui(poster: &Poster, timeout: Duration, f: impl FnOnce(&mut Ui, Reply) + Send + 'static) -> Result<Value, String> {
985    let (tx, rx) = mpsc::channel();
986    poster.post(move |ui| f(ui, Reply { tx, call: None }));
987    rx.recv_timeout(timeout).map_err(|_| "o app não respondeu a tempo".to_string())
988}
989
990fn text_result(text: impl Into<String>, is_error: bool) -> Value {
991    json!({ "content": [{ "type": "text", "text": text.into() }], "isError": is_error })
992}
993
994/// A resposta de uma ferramenta do app: o texto e, sendo um objeto JSON, o `structuredContent`
995/// (com `output_schema`, precisa ser um objeto com os campos obrigatórios).
996fn tool_result(text: String, output: Option<&Value>) -> Value {
997    let parsed = serde_json::from_str::<Value>(&text).ok().filter(Value::is_object);
998    match (parsed, output) {
999        (Some(object), output) => {
1000            if let Some(missing) = output.and_then(|s| s["required"].as_array()).and_then(|req| req.iter().filter_map(Value::as_str).find(|k| object.get(*k).is_none())) {
1001                return text_result(format!("a resposta não segue o output_schema: falta \"{missing}\""), true);
1002            }
1003            json!({ "content": [{ "type": "text", "text": text }], "structuredContent": object, "isError": false })
1004        }
1005        (None, Some(_)) => text_result("a resposta não segue o output_schema: precisa ser um objeto JSON", true),
1006        (None, None) => text_result(text, false),
1007    }
1008}
1009
1010fn json_text(v: &Value) -> String {
1011    match v {
1012        Value::String(s) => s.clone(),
1013        Value::Null => "ok".into(),
1014        other => serde_json::to_string_pretty(other).unwrap_or_default(),
1015    }
1016}
1017
1018fn initialize(ui: &Ui, server: ComponentId, params: &Value) -> Value {
1019    let (name, version, mut instructions, expose_ui) = match ui.get::<McpServer>(server) {
1020        Some(s) => (s.display_name(ui, server), s.version(), s.instructions.trim().to_string(), s.expose_ui),
1021        None => ("aylis-app".to_string(), env!("CARGO_PKG_VERSION").to_string(), String::new(), false),
1022    };
1023    if expose_ui {
1024        if !instructions.is_empty() {
1025            instructions.push_str("\n\n");
1026        }
1027        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).");
1028    }
1029    json!({
1030        "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL),
1031        "capabilities": {
1032            "tools": { "listChanged": true },
1033            "resources": { "listChanged": true, "subscribe": false },
1034            "prompts": { "listChanged": true },
1035        },
1036        "serverInfo": { "name": name, "version": version },
1037        "instructions": instructions,
1038    })
1039}
1040
1041fn tool(name: &str, description: &str, properties: Value, required: &[&str], read_only: bool) -> Value {
1042    json!({
1043        "name": name,
1044        "description": description,
1045        "inputSchema": { "type": "object", "properties": properties, "required": required },
1046        "annotations": { "readOnlyHint": read_only },
1047    })
1048}
1049
1050/// A lista que o agente vê: as do app e, com `expose_ui`, as de tela.
1051pub fn tools(ui: &Ui, server: ComponentId) -> Vec<Value> {
1052    let Some(srv) = ui.get::<McpServer>(server) else { return Vec::new() };
1053    let mut out: Vec<Value> = app_tools(ui, server).into_iter().filter_map(|(id, name)| Some(ui.get::<McpTool>(id)?.listed(&name))).collect();
1054    if srv.expose_ui {
1055        out.extend(ui_tools().into_iter().filter(|t| !srv.read_only || READ_TOOLS.contains(&t["name"].as_str().unwrap_or_default())));
1056        if srv.read_only {
1057            out.push(data_tool(true));
1058        }
1059    }
1060    out
1061}
1062
1063fn ui_tools() -> Vec<Value> {
1064    let s = |d: &str| json!({ "type": "string", "description": d });
1065    let target = s("o componente: nome ou caminho (frmClientes.edtNome)");
1066    vec![
1067        tool("ui_forms", "Os forms criados (e DataModules): nome, classe, título, se está aberto (`open`) e visível.", json!({}), &[], true),
1068        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),
1069        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),
1070        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),
1071        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),
1072        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),
1073        tool(
1074            "ui_click",
1075            "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).",
1076            json!({ "target": target, "modifiers": {}, "x": { "type": "number" }, "y": { "type": "number" }, "button": s("left | right | middle"), "double": { "type": "boolean" } }),
1077            &["target"],
1078            false,
1079        ),
1080        tool(
1081            "ui_drag",
1082            "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.",
1083            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") }),
1084            &["from", "to"],
1085            false,
1086        ),
1087        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),
1088        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),
1089        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),
1090        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),
1091        data_tool(false),
1092    ]
1093}
1094
1095fn data_tool(read_only: bool) -> Value {
1096    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() };
1097    tool(
1098        "ui_data",
1099        &format!("Uma operação num ClientDataSet (`op`: {ops}), com os campos dela (`field`, `value`, `values`, `index`)."),
1100        json!({ "target": { "type": "string" }, "op": { "type": "string" }, "field": { "type": "string" }, "value": {}, "values": { "type": "object" }, "index": { "type": "integer" } }),
1101        &["target", "op"],
1102        read_only,
1103    )
1104}
1105
1106/// Pergunta ao `on_call` do servidor (se ligado) e segue com `then`, ou devolve a recusa.
1107fn gate(ui: &mut Ui, server: ComponentId, info: Value, refuse: impl FnOnce(&mut Ui, String) + 'static, then: impl FnOnce(&mut Ui) + 'static) {
1108    if !ui.has_handler(server, "on_call") {
1109        return then(ui);
1110    }
1111    match ui.ask(server, "on_call", &EventArgs::Text(info.to_string())) {
1112        Asked::Answered(Answer::Refused(m)) => refuse(ui, refused(m)),
1113        Asked::Answered(Answer::Accepted(_)) => then(ui),
1114        Asked::Deferred(token) => ui.on_answer(token, move |ui, answer| match answer {
1115            Answer::Refused(m) => refuse(ui, refused(m)),
1116            Answer::Accepted(_) => then(ui),
1117        }),
1118    }
1119}
1120
1121/// Uma chamada, na thread da interface: o `on_call`, depois a ferramenta, e o `on_result`.
1122fn call_tool(ui: &mut Ui, server: ComponentId, name: String, args: Value, mut reply: Reply) {
1123    if !ui.get::<McpServer>(server).is_some_and(|s| s.active) {
1124        return reply.send(text_result("o servidor MCP foi desligado", true));
1125    }
1126    reply.call = Some(CallInfo { server, tool: name.clone(), arguments: args.to_string(), started: ui.time() });
1127    let info = json!({ "tool": name, "arguments": args });
1128    // Só uma das duas roda: a resposta fica num lugar que as duas alcançam.
1129    let slot = std::rc::Rc::new(std::cell::RefCell::new(Some(reply)));
1130    let refuse_slot = slot.clone();
1131    gate(
1132        ui,
1133        server,
1134        info,
1135        move |ui, message| {
1136            if let Some(reply) = refuse_slot.borrow_mut().take() {
1137                reply.finish(ui, text_result(message, true));
1138            }
1139        },
1140        move |ui| {
1141            if let Some(reply) = slot.borrow_mut().take() {
1142                run_tool(ui, server, &name, &args, reply);
1143            }
1144        },
1145    );
1146}
1147
1148fn refused(message: String) -> String {
1149    if message.trim().is_empty() { "chamada recusada pelo app".into() } else { message }
1150}
1151
1152fn run_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value, reply: Reply) {
1153    if let Some((tool, _)) = app_tools(ui, server).into_iter().find(|(_, n)| n == name) {
1154        return execute_tool(ui, tool, args, reply);
1155    }
1156    let Some(srv) = ui.get::<McpServer>(server) else { return reply.finish(ui, text_result("o servidor MCP foi liberado", true)) };
1157    let listed = srv.expose_ui && (!srv.read_only || READ_TOOLS.contains(&name) || name == "ui_data");
1158    if !listed || !name.starts_with("ui_") {
1159        return reply.finish(ui, text_result(format!("ferramenta desconhecida: {name}"), true));
1160    }
1161    let result = ui_tool(ui, server, name, args);
1162    // O que a ação disparou (o on_click, o on_change) roda antes da resposta.
1163    ui.process_events();
1164    let value = match result {
1165        Ok(v) => text_result(json_text(&v), false),
1166        Err(e) => text_result(e, true),
1167    };
1168    reply.finish(ui, value);
1169}
1170
1171fn execute_tool(ui: &mut Ui, tool: ComponentId, args: &Value, reply: Reply) {
1172    if !ui.has_handler(tool, "on_execute") {
1173        let name = ui.name(tool).unwrap_or_default().to_string();
1174        return reply.finish(ui, text_result(format!("a ferramenta '{name}' não tem o on_execute ligado"), true));
1175    }
1176    match ui.ask(tool, "on_execute", &EventArgs::Text(args.to_string())) {
1177        Asked::Answered(answer) => {
1178            ui.process_events();
1179            let value = answer_result(ui, tool, answer);
1180            reply.finish(ui, value);
1181        }
1182        Asked::Deferred(token) => ui.on_answer(token, move |ui, answer| {
1183            let value = answer_result(ui, tool, answer);
1184            reply.finish(ui, value);
1185        }),
1186    }
1187}
1188
1189/// O texto da resposta de um evento-pergunta (`result`), como o agente recebe.
1190fn answer_text(ui: &Ui, values: &[(String, PropValue)]) -> Option<String> {
1191    values.iter().rev().find(|(k, _)| k == "result").map(|(_, v)| match v {
1192        PropValue::String(s) => s.clone(),
1193        other => json_text(&aylis_json::prop_to_json(ui, other)),
1194    })
1195}
1196
1197fn answer_result(ui: &Ui, tool: ComponentId, answer: Answer) -> Value {
1198    match answer {
1199        Answer::Refused(m) => text_result(if m.trim().is_empty() { "a ferramenta recusou".into() } else { m }, true),
1200        Answer::Accepted(values) => {
1201            let output = ui.get::<McpTool>(tool).and_then(|t| t.output().ok().flatten());
1202            tool_result(answer_text(ui, &values).unwrap_or_else(|| "ok".into()), output.as_ref())
1203        }
1204    }
1205}
1206
1207/// Um erro JSON-RPC para o `handle_message` repassar (no lugar do `result`).
1208fn rpc_failure(code: i64, message: impl Into<String>) -> Value {
1209    json!({ "error": { "code": code, "message": message.into() } })
1210}
1211
1212/// `resources/read`: o `on_call`, depois o `on_read` (ou o `text` fixo).
1213fn read_resource(ui: &mut Ui, server: ComponentId, uri: String, reply: Reply) {
1214    let found = app_resources(ui, server).into_iter().find_map(|(id, _)| ui.get::<McpResource>(id).and_then(|r| r.matches(&uri)).map(|params| (id, params)));
1215    let Some((resource, params)) = found else {
1216        return reply.send(rpc_failure(-32002, format!("recurso não encontrado: {uri}")));
1217    };
1218    let reply = std::rc::Rc::new(std::cell::RefCell::new(Some(reply)));
1219    let (refuse, go) = (reply.clone(), reply);
1220    gate(
1221        ui,
1222        server,
1223        json!({ "resource": uri }),
1224        move |_, message| {
1225            if let Some(r) = refuse.borrow_mut().take() {
1226                r.send(rpc_failure(-32603, message));
1227            }
1228        },
1229        move |ui| {
1230            let Some(reply) = go.borrow_mut().take() else { return };
1231            let Some(r) = ui.get::<McpResource>(resource) else { return reply.send(rpc_failure(-32002, "o recurso foi liberado")) };
1232            let (mime, args) = (r.mime_type.clone(), json!({ "uri": uri, "params": params }).to_string());
1233            let contents = move |text: String| json!({ "contents": [{ "uri": uri, "mimeType": mime, "text": text }] });
1234            if !ui.has_handler(resource, "on_read") {
1235                let text = r.text.clone();
1236                return reply.send(contents(text));
1237            }
1238            let answer = move |ui: &Ui, answer: Answer| match answer {
1239                Answer::Refused(m) => rpc_failure(-32603, refused(m)),
1240                Answer::Accepted(values) => contents(answer_text(ui, &values).unwrap_or_default()),
1241            };
1242            match ui.ask(resource, "on_read", &EventArgs::Text(args)) {
1243                Asked::Answered(a) => reply.send(answer(ui, a)),
1244                Asked::Deferred(token) => ui.on_answer(token, move |ui, a| reply.send(answer(ui, a))),
1245            }
1246        },
1247    );
1248}
1249
1250/// `prompts/get`: o `on_call`, depois o `on_get` (ou o `text` com os argumentos).
1251fn get_prompt(ui: &mut Ui, server: ComponentId, name: String, args: Map<String, Value>, reply: Reply) {
1252    let Some((prompt, _)) = app_prompts(ui, server).into_iter().find(|(_, n)| *n == name) else {
1253        return reply.send(rpc_failure(-32602, format!("prompt desconhecido: {name}")));
1254    };
1255    if let Some(p) = ui.get::<McpPrompt>(prompt) {
1256        if let Some((missing, _, _)) = p.argument_list().into_iter().find(|(n, _, required)| *required && args.get(n).is_none_or(|v| v.as_str() == Some(""))) {
1257            return reply.send(rpc_failure(-32602, format!("falta o argumento \"{missing}\"")));
1258        }
1259    }
1260    let reply = std::rc::Rc::new(std::cell::RefCell::new(Some(reply)));
1261    let (refuse, go) = (reply.clone(), reply);
1262    gate(
1263        ui,
1264        server,
1265        json!({ "prompt": name, "arguments": args }),
1266        move |_, message| {
1267            if let Some(r) = refuse.borrow_mut().take() {
1268                r.send(rpc_failure(-32603, message));
1269            }
1270        },
1271        move |ui| {
1272            let Some(reply) = go.borrow_mut().take() else { return };
1273            let Some(p) = ui.get::<McpPrompt>(prompt) else { return reply.send(rpc_failure(-32602, "o prompt foi liberado")) };
1274            let description = p.description.clone();
1275            let messages = move |text: String| json!({ "description": description, "messages": [{ "role": "user", "content": { "type": "text", "text": text } }] });
1276            if !ui.has_handler(prompt, "on_get") {
1277                let text = p.fill(&args);
1278                return reply.send(messages(text));
1279            }
1280            let answer = move |ui: &Ui, answer: Answer| match answer {
1281                Answer::Refused(m) => rpc_failure(-32603, refused(m)),
1282                Answer::Accepted(values) => messages(answer_text(ui, &values).unwrap_or_default()),
1283            };
1284            match ui.ask(prompt, "on_get", &EventArgs::Text(Value::Object(args).to_string())) {
1285                Asked::Answered(a) => reply.send(answer(ui, a)),
1286                Asked::Deferred(token) => ui.on_answer(token, move |ui, a| reply.send(answer(ui, a))),
1287            }
1288        },
1289    );
1290}
1291
1292// ---------------------------------------------------------------------------
1293// As ferramentas de tela
1294
1295/// O componente do alvo, se o agente pode chegar nele: nunca o próprio MCP (servidor e
1296/// ferramentas, nem dentro deles), e só os forms de `forms`.
1297fn reach(ui: &Ui, server: ComponentId, value: Option<&Value>) -> Result<ComponentId, String> {
1298    let id = crate::resolve(ui, value.ok_or("falta \"target\"")?)?;
1299    let mut at = Some(id);
1300    while let Some(c) = at {
1301        let class = ui.component(c).map(|c| c.class_name()).unwrap_or_default();
1302        if c == server || matches!(class, "McpServer" | "McpTool" | "McpResource" | "McpPrompt") {
1303            return Err("o servidor MCP e as ferramentas dele não podem ser comandados por aqui".into());
1304        }
1305        at = ui.parent(c);
1306    }
1307    form_allowed(ui, server, ui.root_of(id))?;
1308    Ok(id)
1309}
1310
1311fn form_allowed(ui: &Ui, server: ComponentId, form: ComponentId) -> Result<(), String> {
1312    let allowed = ui.get::<McpServer>(server).map(McpServer::allowed_forms).unwrap_or_default();
1313    let name = ui.name(form).unwrap_or_default();
1314    if allowed.is_empty() || allowed.iter().any(|f| f.eq_ignore_ascii_case(name)) {
1315        Ok(())
1316    } else {
1317        Err(format!("o form '{name}' não está liberado para o agente"))
1318    }
1319}
1320
1321fn ui_tool(ui: &mut Ui, server: ComponentId, name: &str, args: &Value) -> Result<Value, String> {
1322    let read_only = ui.get::<McpServer>(server).is_some_and(|s| s.read_only);
1323    let str_arg = |key: &str| args.get(key).and_then(Value::as_str).unwrap_or_default().to_string();
1324    match name {
1325        "ui_forms" => Ok(Value::Array(
1326            ui.roots()
1327                .iter()
1328                .filter(|&&r| form_allowed(ui, server, r).is_ok() && !ui.name(r).unwrap_or_default().is_empty())
1329                .map(|&r| {
1330                    let class = ui.component(r).map(|c| c.class_name()).unwrap_or_default();
1331                    let caption = ui.get_prop(r, "caption").ok().and_then(|v| v.to_str().ok().map(str::to_string));
1332                    // `open`: a janela está aberta. Um form criado no início e não mostrado
1333                    // existe mas não aparece: `visible` só vale aberto
1334                    // (antes dizia `true` para todos, e parecia que tinham aberto).
1335                    let open = ui.is_open(r);
1336                    json!({ "name": ui.name(r), "class": class, "caption": caption, "open": open, "visible": open && ui.control(r).is_some_and(|c| c.visible()) })
1337                })
1338                .collect(),
1339        )),
1340        "ui_tree" => {
1341            let form = str_arg("form");
1342            if form.is_empty() {
1343                let roots: Vec<ComponentId> = ui.roots().iter().copied().filter(|&r| form_allowed(ui, server, r).is_ok()).collect();
1344                return Ok(Value::Array(roots.into_iter().map(|r| crate::inspect::tree(ui, Some(r))).collect()));
1345            }
1346            let id = reach(ui, server, Some(&Value::String(form)))?;
1347            Ok(crate::inspect::tree(ui, Some(id)))
1348        }
1349        "ui_get" => {
1350            let id = reach(ui, server, args.get("target"))?;
1351            match args.get("prop").and_then(Value::as_str).filter(|p| !p.is_empty()) {
1352                Some(prop) => crate::get(ui, id, prop),
1353                None => Ok(crate::inspect::props(ui, id)),
1354            }
1355        }
1356        "ui_items" => {
1357            let id = reach(ui, server, args.get("target"))?;
1358            crate::execute(ui, &json!({ "cmd": "items", "target": id.to_u64() }))
1359        }
1360        "ui_rows" => {
1361            let id = reach(ui, server, args.get("target"))?;
1362            rows(ui, id, args)
1363        }
1364        "ui_data" => {
1365            let id = reach(ui, server, args.get("target"))?;
1366            let op = str_arg("op");
1367            if read_only && !READ_DATA_OPS.contains(&op.as_str()) {
1368                return Err(format!("o servidor está só para leitura: a operação '{op}' não vale"));
1369            }
1370            let mut command = args.as_object().cloned().unwrap_or_default();
1371            command.insert("cmd".into(), "data".into());
1372            command.insert("target".into(), id.to_u64().into());
1373            crate::execute(ui, &Value::Object(command))
1374        }
1375        _ if read_only => Err(format!("o servidor está só para leitura: '{name}' não vale")),
1376        "ui_set" => {
1377            let id = reach(ui, server, args.get("target"))?;
1378            let prop = str_arg("prop");
1379            if prop.is_empty() {
1380                return Err("falta \"prop\"".into());
1381            }
1382            let value = args.get("value").cloned().unwrap_or(Value::Null);
1383            crate::execute(ui, &json!({ "cmd": "set", "target": id.to_u64(), "props": { prop: value } }))
1384        }
1385        "ui_click" => {
1386            let id = reach(ui, server, args.get("target"))?;
1387            // As opções do clique (o mouse de verdade) passam como estão ao protocolo, o mesmo
1388            // caminho do `app_command` da IDE.
1389            let mut command = json!({ "cmd": "click", "target": id.to_u64() });
1390            for key in ["modifiers", "x", "y", "button", "double"] {
1391                if let Some(v) = args.get(key) {
1392                    command[key] = v.clone();
1393                }
1394            }
1395            crate::execute(ui, &command)
1396        }
1397        "ui_drag" => {
1398            // Os dois lados passam pelo alcance do servidor (os forms permitidos, nunca ele).
1399            let (from, to) = (reach(ui, server, args.get("from"))?, reach(ui, server, args.get("to"))?);
1400            let mut command = json!({ "cmd": "drag", "from": from.to_u64(), "to": to.to_u64() });
1401            for key in ["from_x", "from_y", "to_x", "to_y", "steps", "modifiers", "button"] {
1402                if let Some(v) = args.get(key) {
1403                    command[key] = v.clone();
1404                }
1405            }
1406            crate::execute(ui, &command)
1407        }
1408        "ui_click_item" => {
1409            let id = reach(ui, server, args.get("target"))?;
1410            let mut command = json!({ "cmd": "click_item", "target": id.to_u64() });
1411            for key in ["item", "index", "action"] {
1412                if let Some(v) = args.get(key) {
1413                    command[key] = v.clone();
1414                }
1415            }
1416            crate::execute(ui, &command)
1417        }
1418        "ui_type" => {
1419            let id = reach(ui, server, args.get("target"))?;
1420            ui.set_focus(id);
1421            crate::execute(ui, &json!({ "cmd": "type", "target": id.to_u64(), "text": str_arg("text") }))
1422        }
1423        "ui_key" => {
1424            let id = reach(ui, server, args.get("target"))?;
1425            if ui.root_of(id) != id {
1426                ui.set_focus(id);
1427            }
1428            let mut command = json!({ "cmd": "key", "target": id.to_u64(), "key": str_arg("key") });
1429            if let Some(v) = args.get("modifiers") {
1430                command["modifiers"] = v.clone();
1431            }
1432            crate::execute(ui, &command)
1433        }
1434        "ui_invoke" => {
1435            let id = reach(ui, server, args.get("target"))?;
1436            crate::execute(ui, &json!({ "cmd": "invoke", "target": id.to_u64(), "method": str_arg("method"), "args": args.get("args").cloned().unwrap_or_else(|| json!([])) }))
1437        }
1438        _ => Err(format!("ferramenta desconhecida: {name}")),
1439    }
1440}
1441
1442/// Os registros de um ClientDataSet, de `offset` até `limit`.
1443fn rows(ui: &Ui, id: ComponentId, args: &Value) -> Result<Value, String> {
1444    if ui.get::<aylis_data::ClientDataSet>(id).is_none() {
1445        return Err(format!("'{}' não é um ClientDataSet", ui.name(id).unwrap_or("?")));
1446    }
1447    let v = aylis_data::view(ui, id);
1448    let count = v.record_count();
1449    let offset = args.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
1450    let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 1000) as usize;
1451    let names = v.field_names();
1452    let list: Vec<Value> = (offset..count.min(offset.saturating_add(limit)))
1453        .map(|i| {
1454            let mut row = Map::new();
1455            for name in &names {
1456                let value = v.value_at(i, name).map(|x| aylis_data::json::value_to_json(&x)).unwrap_or(Value::Null);
1457                row.insert(name.clone(), value);
1458            }
1459            Value::Object(row)
1460        })
1461        .collect();
1462    Ok(json!({ "count": count, "offset": offset, "rows": list }))
1463}