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