1pub 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#[derive(Clone, Debug, PartialEq)]
34pub struct ClaudeCode {
35 pub path: std::path::PathBuf,
36 pub in_path: bool,
38}
39
40pub 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 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
83pub const PROTOCOL: &str = "2025-06-18";
85
86const DEFAULT_TIMEOUT: u32 = 30_000;
88
89const READ_TOOLS: &[&str] = &["ui_forms", "ui_tree", "ui_get", "ui_items", "ui_rows"];
91
92const READ_DATA_OPS: &[&str] = &["first", "prior", "next", "last", "move_to", "locate", "value", "text", "record", "info", "field_texts", "field_error", "lookup"];
94
95pub struct McpServer {
110 pub active: bool,
112 pub port: u32,
114 pub token: String,
116 pub server_name: String,
118 pub instructions: String,
120 pub expose_ui: bool,
123 pub read_only: bool,
125 pub forms: String,
127 pub call_timeout: u32,
129 running: Option<http::HttpServer>,
130 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 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 pub fn last_error(&self) -> String {
166 self.last_error.clone()
167 }
168
169 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 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 self.running = None;
277 self.attempted = false;
278 }
279 if name == "active" {
280 self.attempted = false;
281 }
282 self.sync(ctx);
283 }
284
285 }
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
311pub struct McpTool {
325 pub tool_name: String,
327 pub description: String,
329 pub params: String,
332 pub read_only: bool,
334 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 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 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 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 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 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
427pub fn register(ui: &mut Ui) {
429 ui.register_class::<McpServer>("System");
430 ui.register_class::<McpTool>("System");
431}
432
433fn handle_message(message: Value, poster: &Poster, server: ComponentId, timeout: Duration) -> Option<Value> {
438 let id = message.get("id").cloned()?; 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, ¶ms))),
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
458struct Reply(mpsc::Sender<Value>);
460
461impl Reply {
462 fn send(&self, value: Value) {
463 let _ = self.0.send(value);
464 }
465}
466
467fn 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
505fn 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
523pub 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
586fn 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 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
656fn 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 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 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 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
806fn 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}