Skip to main content

agentmux_mcp/tools/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `call_tool`'s handlers, one file per tool family
5//! (docs/specs/SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.2 (a)).
6//! Each family's `call` handles the tools it owns and returns
7//! `not_in_family()` for any other name, so no tool list is written twice.
8
9use super::*;
10use args::{arg_str, str_arg};
11use srv_calls::Named;
12
13mod accounts;
14mod aws_grants;
15mod agents_hosts;
16mod args;
17mod agents_tool;
18mod app_record;
19mod app_workspace;
20mod app_tool;
21mod browser;
22mod browser_account;
23mod browser_key_text;
24mod browser_locate;
25mod browser_open;
26mod browser_tool;
27mod browser_waiting;
28mod browser_sessions;
29mod browser_canvas;
30mod browser_scroll;
31mod browser_zoom;
32mod cron;
33mod desktop;
34mod drone_tool;
35mod family;
36mod fleet;
37mod global_memory;
38pub(crate) mod google_tool;
39mod history;
40mod identity_tool;
41mod loops;
42mod memory;
43mod memory_tool;
44mod message_tool;
45mod open_prs;
46mod overlap;
47mod pane_tool;
48mod panes;
49mod presence_tool;
50mod presets;
51pub(crate) mod remote_op;
52mod pty_shell;
53mod schedule_tool;
54mod sensitive_tool;
55mod send_files;
56mod shell;
57mod skills_tool;
58mod srv_calls;
59mod stop_tool;
60mod tasks_tool;
61mod terminal;
62mod ui;
63mod ui_tool;
64mod vault_tool;
65mod widget_tool;
66mod widgets;
67mod work;
68mod zoom_tool;
69
70#[cfg(test)]
71mod test_stub;
72#[cfg(test)]
73mod srv_calls_tests;
74
75/// What every handler may need from the MCP process.
76#[derive(Clone, Copy)]
77pub(crate) struct ToolCtx<'a> {
78    pub(crate) local_url: &'a str,
79    pub(crate) auth_key: &'a str,
80    pub(crate) block_id: &'a str,
81    pub(crate) client: &'a reqwest::Client,
82    pub(crate) loops: &'a LoopRegistry,
83    pub(crate) loop_counter: &'a AtomicU64,
84}
85
86/// The optional `pane` argument: a browser pane this agent opened with
87/// `OpenBrowser`. srv checks ownership; absent = the agent's own pane.
88fn pane_arg(arguments: &Value) -> Option<String> {
89    str_arg(arguments, "pane")
90}
91
92/// A path the agent gave, made absolute against its own workspace
93/// (`AGENTMUX_AGENT_WORKDIR`, else this process's directory). It doesn't
94/// follow a `cd` in the agent's shell, so tools ask for absolute paths.
95fn resolve_workdir_path(path: &str) -> String {
96    let p = std::path::Path::new(path);
97    if p.is_absolute() {
98        return path.to_string();
99    }
100    let base = std::env::var("AGENTMUX_AGENT_WORKDIR")
101        .ok()
102        .filter(|s| !s.is_empty())
103        .map(std::path::PathBuf::from)
104        .or_else(|| std::env::current_dir().ok())
105        .unwrap_or_default();
106    base.join(p).to_string_lossy().into_owned()
107}
108
109/// A family's answer for a tool it doesn't own.
110#[derive(Debug)]
111struct NotInFamily;
112
113impl std::fmt::Display for NotInFamily {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.write_str("not in this tool family")
116    }
117}
118
119impl std::error::Error for NotInFamily {}
120
121fn not_in_family() -> anyhow::Error {
122    anyhow::Error::new(NotInFamily)
123}
124
125/// Tools a family tool replaced (SPEC_MUXAPI_TOOL_CONSOLIDATION_2026_10_15.md
126/// §6): the model only sees listed tools, but a memory, a skill or a script
127/// may still name an old one, so the error says what to use instead.
128const REPLACED: &[(&str, &str)] = &[
129    ("Shell", "Terminal with action \"run\" and background: true"),
130    ("ShellInput", "Terminal with action \"type\""),
131    ("ShellStatus", "Terminal with action \"wait\" and until \"exit\", or \"read\""),
132    ("ShellStop", "Terminal with action \"close\""),
133    ("PtyShell", "Terminal with action \"open\""),
134    ("PtyShellInput", "Terminal with action \"type\" (keys by name; submit presses Enter)"),
135    ("PtyShellResize", "Terminal with action \"type\" and rows/cols"),
136    ("PtyShellRead", "Terminal with action \"read\""),
137    ("PtyShellStatus", "Terminal with action \"read\" (running, exit_code)"),
138    ("PtyShellStop", "Terminal with action \"close\""),
139    ("ConnList", "Terminal with action \"connections\""),
140    ("OpenBrowser", "Browser with action \"open\""),
141    ("BrowserSnapshot", "Browser with action \"snapshot\""),
142    ("BrowserFind", "Browser with action \"find\""),
143    ("BrowserClick", "Browser with action \"click\""),
144    ("BrowserFill", "Browser with action \"fill\""),
145    ("BrowserRequestValue", "Browser with action \"request_value\""),
146    ("BrowserCapture", "Browser with action \"capture\""),
147    ("BrowserSignin", "Browser with action \"signin\""),
148    ("BrowserGeneratePassword", "Browser with action \"generate_password\""),
149    ("BrowserSelect", "Browser with action \"select\""),
150    ("BrowserCheck", "Browser with action \"check\""),
151    ("BrowserSetFiles", "Browser with action \"set_files\""),
152    ("BrowserWaitFor", "Browser with action \"wait\" (until_text, until_url, until_gone, until_state)"),
153    ("BrowserHandoff", "Browser with action \"handoff\""),
154    ("BrowserHandoffStatus", "Browser with action \"handoff_status\""),
155    ("BrowserRetake", "Browser with action \"retake\""),
156    ("BrowserTakeControl", "Browser with action \"take_control\""),
157    ("BrowserRelease", "Browser with action \"release\""),
158    ("BrowserTerminal", "Browser with action \"terminal\""),
159    ("BrowserRequestBypass", "Browser with action \"request_auto_approve\""),
160    ("BrowserEndBypass", "Browser with action \"stop_auto_approve\""),
161    ("BrowserLog", "Browser with action \"log\""),
162    ("BrowserList", "Browser with action \"list\""),
163    ("BrowserShow", "Browser with action \"show\""),
164    ("BrowserHide", "Browser with action \"hide\""),
165    ("BrowserClose", "Browser with action \"close\""),
166    ("BrowserNavigate", "Browser with action \"navigate\""),
167    ("BrowserBack", "Browser with action \"back\""),
168    ("BrowserForward", "Browser with action \"forward\""),
169    ("BrowserReload", "Browser with action \"reload\""),
170    ("BrowserZoom", "Browser with action \"zoom\""),
171    ("BrowserScroll", "Browser with action \"scroll\""),
172    ("BrowserDrag", "Browser with action \"drag\""),
173    ("BrowserLocate", "Browser with action \"locate\""),
174    ("BrowserClickAt", "Browser with action \"click_at\""),
175    ("BrowserRequestStatus", "Browser with action \"request_status\""),
176    ("BrowserCancelRequest", "Browser with action \"cancel_request\""),
177    ("BrowserEval", "Browser with action \"eval\""),
178    ("BrowserDispatchKey", "Browser with action \"key\""),
179    ("BrowserFocusElement", "Browser with action \"focus\""),
180    ("BrowserFocusInfo", "Browser with action \"focus_info\""),
181    ("UIScreenshot", "UI with action \"screenshot\""),
182    ("UIQuery", "UI with action \"query\""),
183    ("UIClick", "UI with action \"click\""),
184    ("ListShortcuts", "UI with action \"shortcuts\""),
185    ("RunCommand", "UI with action \"command\""),
186    ("PressKeys", "UI with action \"keys\""),
187    ("SetShortcut", "UI with action \"bind\""),
188    ("ResetShortcuts", "UI with action \"reset\""),
189    ("DiscoverWindows", "UI with action \"windows\""),
190    ("CaptureWindow", "UI with action \"window\""),
191    ("UIRecord", "UI with action \"record\""),
192    ("MemoryList", "Memory with action \"list\""),
193    ("MemoryRead", "Memory with action \"read\""),
194    ("MemoryWrite", "Memory with action \"write\""),
195    ("MemoryHistory", "Memory with action \"history\""),
196    ("MemoryDiff", "Memory with action \"diff\""),
197    ("MemoryRevert", "Memory with action \"revert\" (version_id)"),
198    ("GlobalMemoryList", "Memory with action \"list\" and scope \"global\""),
199    ("GlobalMemoryRead", "Memory with action \"read\" and scope \"global\""),
200    ("GlobalMemoryWrite", "Memory with action \"write\" and scope \"global\""),
201    ("GlobalMemoryRemove", "Memory with action \"remove\" and scope \"global\""),
202    ("GlobalMemoryReach", "Memory with action \"reach\" and scope \"global\""),
203    ("GlobalMemoryHistory", "Memory with action \"history\" and scope \"global\""),
204    ("GlobalMemoryDiff", "Memory with action \"diff\" and scope \"global\""),
205    ("GlobalMemoryRevert", "Memory with action \"revert\" and scope \"global\""),
206    ("WorkEnqueue", "Tasks with action \"enqueue\""),
207    ("WorkClaim", "Tasks with action \"claim\""),
208    ("WorkHeartbeat", "Tasks with action \"heartbeat\""),
209    ("WorkComplete", "Tasks with action \"complete\""),
210    ("WorkRelease", "Tasks with action \"release\""),
211    ("WorkList", "Tasks with action \"list\""),
212    ("WorkGet", "Tasks with action \"get\""),
213    ("WorkTokens", "Tasks with action \"tokens\""),
214    ("WorkUpdate", "Tasks with action \"update\""),
215    ("WorkAsk", "Tasks with action \"ask\""),
216    ("WorkSubmit", "Tasks with action \"submit\""),
217    ("WorkHold", "Tasks with action \"hold\""),
218    ("WorkUnhold", "Tasks with action \"unhold\""),
219    ("WorkAccept", "Tasks with action \"accept\""),
220    ("WorkSendBack", "Tasks with action \"send_back\""),
221    ("WorkEdit", "Tasks with action \"edit\""),
222    ("WorkMove", "Tasks with action \"move\""),
223    ("WorkStart", "Tasks with action \"start\""),
224    ("WorkAnswer", "Tasks with action \"answer\""),
225    ("WorkCancel", "Tasks with action \"cancel\""),
226    ("WorkReopen", "Tasks with action \"reopen\""),
227    ("WorkRetry", "Tasks with action \"retry\""),
228    ("WorkTakeBack", "Tasks with action \"take_back\""),
229    ("WorkReassign", "Tasks with action \"reassign\""),
230    ("WhoIsWorkingOn", "Presence with action \"who\""),
231    ("ClaimWork", "Presence with action \"claim\""),
232    ("ReleaseWork", "Presence with action \"release\""),
233    ("SetStatus", "Presence with action \"status\" (line, state)"),
234    ("CronCreate", "Schedule with action \"create\" and cron"),
235    ("CronList", "Schedule with action \"list\""),
236    ("CronPause", "Schedule with action \"pause\""),
237    ("CronResume", "Schedule with action \"resume\""),
238    ("CronDelete", "Schedule with action \"delete\""),
239    ("CronHistory", "Schedule with action \"history\""),
240    ("CronRunNow", "Schedule with action \"run_now\""),
241    ("CronReport", "Schedule with action \"report\""),
242    ("Loop", "Schedule with action \"create\" and every"),
243    ("LoopList", "Schedule with action \"list\""),
244    ("LoopStop", "Schedule with action \"delete\""),
245    ("WhoAmI", "Pane with action \"whoami\""),
246    ("Layout", "Pane with action \"layout\""),
247    ("OpenEditor", "Pane with action \"open\" and view \"editor\""),
248    ("OpenMedia", "Pane with action \"open\" and view \"media\""),
249    ("OpenFiles", "Pane with action \"open\" and view \"files\""),
250    ("OpenLink", "Pane with action \"open\" and link"),
251    ("NewTab", "Pane with action \"new_tab\""),
252    ("SetActiveTab", "Pane with action \"activate_tab\""),
253    ("FocusWindow", "Pane with action \"focus_window\""),
254    ("SetName", "Pane with action \"rename\""),
255    ("ResizePane", "Pane with action \"resize\""),
256    ("MovePane", "Pane with action \"move\""),
257    ("PlacePane", "Pane with action \"place\""),
258    ("DockPane", "Pane with action \"dock\""),
259    ("FloatPane", "Pane with action \"float\""),
260    ("PinPane", "Pane with action \"pin\""),
261    ("UnpinPane", "Pane with action \"unpin\""),
262    ("QuitSelf", "Stop with action \"self\""),
263    ("FleetBulkStop", "Stop with action \"agents\""),
264    ("ClosePane", "Stop with action \"pane\" (and block_id; to end your own session, action \"self\")"),
265    ("WidgetList", "Widget with action \"list\""),
266    ("WidgetInstall", "Widget with action \"install\""),
267    ("OpenWidget", "Widget with action \"open\""),
268    ("PresetList", "Identity with action \"presets\""),
269    ("PresetGet", "Identity with action \"preset\""),
270    ("IdentityAccounts", "Identity with action \"accounts\""),
271    ("IdentityValidate", "Identity with action \"validate\""),
272    ("IdentitySwitch", "Identity with action \"switch\""),
273    ("IdentityCheckLimits", "Identity with action \"check_limits\""),
274    ("IdentitySignin", "Identity with action \"signin\""),
275    ("DiscoverAgents", "Agents with action \"list\""),
276    ("FleetList", "Agents with action \"list\""),
277    ("ListConversations", "Agents with action \"conversations\""),
278    ("GetAgentTranscript", "Agents with action \"transcript\""),
279    ("OpenAgent", "Agents with action \"open\""),
280    ("SearchHistory", "Agents with action \"search_history\""),
281    ("SendMessage", "Message with action \"send\""),
282    ("FleetBroadcast", "Message with action \"broadcast\""),
283    ("PostToChannel", "Message with action \"post\""),
284    ("ReadChannel", "Message with action \"read\""),
285    ("PostBulletin", "Message with action \"bulletin\""),
286    ("ReadBulletin", "Message with action \"read_bulletin\""),
287    ("QuotaMode", "Message with action \"quota_mode\""),
288];
289
290/// Try each family in turn; the first that owns `name` answers.
291pub(crate) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
292    macro_rules! route {
293        ($($family:ident),*) => {$(
294            match $family::call(name, arguments, cx).await {
295                Err(e) if e.is::<NotInFamily>() => {}
296                answered => return answered,
297            }
298        )*};
299    }
300    route!(
301        terminal,
302        pane_tool,
303        stop_tool,
304        agents_tool,
305        message_tool,
306        presence_tool,
307        ui_tool,
308        browser_tool,
309        schedule_tool,
310        tasks_tool,
311        memory_tool,
312        identity_tool,
313        skills_tool,
314        widget_tool,
315        vault_tool,
316        app_tool,
317        desktop,
318        sensitive_tool,
319        drone_tool,
320        google_tool,
321        zoom_tool
322    );
323    if let Some((_, instead)) = REPLACED.iter().find(|(old, _)| *old == name) {
324        anyhow::bail!("{name} was replaced: use {instead}");
325    }
326    anyhow::bail!("unknown tool: {name}")
327}
328
329#[cfg(test)]
330mod tests {
331    use std::collections::BTreeMap;
332
333    /// Families `call` routes to: each of their tools is advertised.
334    const FAMILIES: &[(&str, &str)] = &[
335        ("agents_tool", include_str!("agents_tool.rs")),
336        ("app_tool", include_str!("app_tool.rs")),
337        ("browser_tool", include_str!("browser_tool.rs")),
338        ("desktop", include_str!("desktop.rs")),
339        ("drone_tool", include_str!("drone_tool.rs")),
340        ("google_tool", include_str!("google_tool.rs")),
341        ("identity_tool", include_str!("identity_tool.rs")),
342        ("memory_tool", include_str!("memory_tool.rs")),
343        ("message_tool", include_str!("message_tool.rs")),
344        ("pane_tool", include_str!("pane_tool.rs")),
345        ("presence_tool", include_str!("presence_tool.rs")),
346        ("schedule_tool", include_str!("schedule_tool.rs")),
347        ("sensitive_tool", include_str!("sensitive_tool.rs")),
348        ("skills_tool", include_str!("skills_tool.rs")),
349        ("stop_tool", include_str!("stop_tool.rs")),
350        ("tasks_tool", include_str!("tasks_tool.rs")),
351        ("terminal", include_str!("terminal.rs")),
352        ("ui_tool", include_str!("ui_tool.rs")),
353        ("vault_tool", include_str!("vault_tool.rs")),
354        ("widget_tool", include_str!("widget_tool.rs")),
355        ("zoom_tool", include_str!("zoom_tool.rs")),
356    ];
357
358    /// Families a family tool calls into, never routed to: their names are
359    /// not advertised, and each is in `REPLACED`.
360    const INTERNAL: &[(&str, &str)] = &[
361        ("accounts", include_str!("accounts.rs")),
362        ("browser", include_str!("browser.rs")),
363        ("cron", include_str!("cron.rs")),
364        ("fleet", include_str!("fleet.rs")),
365        ("global_memory", include_str!("global_memory.rs")),
366        ("history", include_str!("history.rs")),
367        ("loops", include_str!("loops.rs")),
368        ("memory", include_str!("memory.rs")),
369        ("overlap", include_str!("overlap.rs")),
370        ("panes", include_str!("panes.rs")),
371        ("presets", include_str!("presets.rs")),
372        ("pty_shell", include_str!("pty_shell.rs")),
373        ("shell", include_str!("shell.rs")),
374        ("ui", include_str!("ui.rs")),
375        ("widgets", include_str!("widgets.rs")),
376        ("work", include_str!("work.rs")),
377    ];
378
379    /// The tool names in a family's `match name` arms (`"A" | "B" => ...`),
380    /// read from its `call` function only, so another `match` in the file
381    /// (an action, an option) isn't taken for a tool.
382    fn arm_names(src: &str) -> Vec<String> {
383        let start = src.find("pub(super) async fn call(").expect("a family has a call function");
384        let body = &src[start..];
385        let body = &body[..body.find("\n}\n").map(|e| e + 2).unwrap_or(body.len())];
386        body.lines()
387            .filter_map(|l| l.strip_prefix("        \""))
388            .filter_map(|l| l.split_once("\" => ").map(|(pat, _)| pat))
389            .flat_map(|pat| pat.split(" | ").map(|n| n.trim_matches('"').to_string()))
390            .collect()
391    }
392
393    /// Every tool `tools/list` can advertise has exactly one handler, and
394    /// every handler belongs to an advertised tool. A name in two families
395    /// would make the later one unreachable.
396    #[test]
397    fn every_advertised_tool_has_exactly_one_handler() {
398        let mut owner: BTreeMap<String, &str> = BTreeMap::new();
399        for (family, src) in FAMILIES {
400            let names = arm_names(src);
401            assert!(!names.is_empty(), "{family} has no arms");
402            for n in names {
403                if let Some(prev) = owner.insert(n.clone(), family) {
404                    panic!("{n} is handled by both {prev} and {family}");
405                }
406            }
407        }
408        let schemas = include_str!("../tool_schemas.rs");
409        let advertised: Vec<String> = schemas
410            .lines()
411            .filter_map(|l| l.trim().strip_prefix("\"name\": \""))
412            .filter_map(|l| l.split('"').next())
413            .map(str::to_string)
414            .collect();
415        assert!(!advertised.is_empty());
416        for n in &advertised {
417            assert!(owner.contains_key(n), "{n} is advertised but has no handler");
418        }
419        for n in owner.keys() {
420            assert!(advertised.contains(n), "{n} has a handler but no schema");
421        }
422        for (family, src) in INTERNAL {
423            for n in arm_names(src) {
424                // Either replaced (not advertised, named in REPLACED) or still
425                // advertised and passed through by a routed family.
426                if advertised.contains(&n) {
427                    assert!(owner.contains_key(&n), "{n} ({family}) is advertised but no routed family passes it through");
428                } else {
429                    assert!(super::REPLACED.iter().any(|(old, _)| *old == n), "{n} ({family}) has no REPLACED entry");
430                }
431            }
432        }
433    }
434
435    #[tokio::test]
436    async fn a_replaced_tool_names_its_replacement() {
437        let client = reqwest::Client::new();
438        let loops = super::LoopRegistry::default();
439        let counter = std::sync::atomic::AtomicU64::new(0);
440        let cx = super::ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
441        let err = super::call("PtyShellInput", &serde_json::json!({}), &cx).await.unwrap_err();
442        assert!(err.to_string().starts_with("PtyShellInput was replaced: use Terminal"), "{err}");
443    }
444
445    #[tokio::test]
446    async fn an_unknown_tool_is_reported_by_name() {
447        let client = reqwest::Client::new();
448        let loops = super::LoopRegistry::default();
449        let counter = std::sync::atomic::AtomicU64::new(0);
450        let cx = super::ToolCtx {
451            local_url: "",
452            auth_key: "",
453            block_id: "",
454            client: &client,
455            loops: &loops,
456            loop_counter: &counter,
457        };
458        let err = super::call("NoSuchTool", &serde_json::json!({}), &cx)
459            .await
460            .unwrap_err();
461        assert_eq!(err.to_string(), "unknown tool: NoSuchTool");
462    }
463}