Skip to main content

agentmux_mcp/tools/
family.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The action router behind a family tool (one tool with an `action`,
5//! docs/specs/SPEC_MUXAPI_TOOL_CONSOLIDATION_2026_10_15.md §4.1). Each action
6//! names the internal handler it runs, by that handler's old tool name, and
7//! the parameters the family tool calls differently, so one handler serves the
8//! action unchanged.
9
10use super::*;
11
12/// One action of a family tool.
13#[derive(Debug)]
14pub(super) struct Act {
15    pub(super) action: &'static str,
16    /// The internal tool name its handler answers to.
17    pub(super) tool: &'static str,
18    /// `(family name, handler name)` for parameters named differently.
19    pub(super) rename: &'static [(&'static str, &'static str)],
20}
21
22/// The action `arguments` asks for, with its arguments as the handler takes
23/// them: `action` removed, renamed parameters under their handler names. An
24/// unknown or missing action is an error that lists the actions.
25pub(super) fn pick<'a>(family: &str, acts: &'a [Act], arguments: &Value) -> Result<(&'a Act, Value)> {
26    let names = || acts.iter().map(|a| a.action).collect::<Vec<_>>().join(", ");
27    let action = arguments.get("action").and_then(|v| v.as_str()).unwrap_or("");
28    if action.is_empty() {
29        anyhow::bail!("{family}: missing required parameter: action (one of {})", names());
30    }
31    let Some(act) = acts.iter().find(|a| a.action == action) else {
32        anyhow::bail!("{family}: unknown action {action:?}: use one of {}", names());
33    };
34    let mut args = match arguments {
35        Value::Object(m) => m.clone(),
36        _ => serde_json::Map::new(),
37    };
38    args.remove("action");
39    for (ours, theirs) in act.rename {
40        if let Some(v) = args.remove(*ours) {
41            args.insert((*theirs).to_string(), v);
42        }
43    }
44    Ok((act, Value::Object(args)))
45}
46
47/// `text` with the internal tool name it starts with replaced by the public
48/// one ("BrowserClick e12: done" → "Browser click e12: done"): a handler
49/// names the tool it ran as at the start of its output and errors, and that
50/// name isn't advertised. Only that label changes: what follows is the
51/// page, a script's value or a window's title, and is returned exactly.
52pub(super) fn relabel(family: &str, acts: &[Act], text: &str) -> String {
53    for act in acts {
54        let Some(rest) = text.strip_prefix(act.tool) else { continue };
55        if rest.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
56            continue;
57        }
58        return format!("{family} {}{rest}", act.action);
59    }
60    text.to_string()
61}
62
63/// A handler's error about a parameter the family tool renamed, under the
64/// name the caller passes it by ("missing required parameter: target_agent"
65/// → "... agent"): the caller can't pass the handler's name.
66pub(super) fn public_params(message: &str, rename: &[(&str, &str)]) -> String {
67    let mut out = message.to_string();
68    for (ours, theirs) in rename {
69        for (from, to) in [
70            (format!("missing required parameter: {theirs}"), format!("missing required parameter: {ours}")),
71            (format!("invalid {theirs}:"), format!("invalid {ours}:")),
72        ] {
73            out = out.replace(&from, &to);
74        }
75    }
76    out
77}
78
79/// A handler's result, output and error alike, under the public names.
80pub(super) fn relabeled(family: &str, acts: &[Act], result: Result<String>) -> Result<String> {
81    match result {
82        Ok(text) => Ok(relabel(family, acts, &text)),
83        Err(e) => Err(anyhow::anyhow!(relabel(family, acts, &format!("{e:#}")))),
84    }
85}
86
87/// The actions' names, for a schema test.
88#[cfg(test)]
89pub(super) fn action_names(acts: &[Act]) -> Vec<&'static str> {
90    acts.iter().map(|a| a.action).collect()
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    const ACTS: &[Act] = &[
98        Act { action: "fill", tool: "BrowserFill", rename: &[] },
99        Act { action: "wait", tool: "BrowserWaitFor", rename: &[("until_text", "text"), ("until_url", "url_contains")] },
100    ];
101
102    #[test]
103    fn an_action_runs_its_handler_with_renamed_arguments() {
104        let (act, args) = pick("Browser", ACTS, &json!({ "action": "wait", "until_text": "Done", "pane": "p1" })).unwrap();
105        assert_eq!(act.tool, "BrowserWaitFor");
106        assert_eq!(args, json!({ "text": "Done", "pane": "p1" }));
107        let (act, args) = pick("Browser", ACTS, &json!({ "action": "fill", "ref": "e3", "text": "x" })).unwrap();
108        assert_eq!(act.tool, "BrowserFill");
109        assert_eq!(args, json!({ "ref": "e3", "text": "x" }));
110    }
111
112    #[test]
113    fn handler_output_names_the_action_not_the_internal_tool() {
114        assert_eq!(relabel("Browser", ACTS, "BrowserFill e12: done"), "Browser fill e12: done");
115        assert_eq!(relabel("Browser", ACTS, "BrowserWaitFor failed: HTTP 504"), "Browser wait failed: HTTP 504");
116        // Only a whole name at the start: what follows is returned exactly.
117        assert_eq!(relabel("Browser", ACTS, "BrowserFillAll"), "BrowserFillAll");
118        assert_eq!(relabel("Browser", ACTS, "page: BrowserFill BrowserWaitFor"), "page: BrowserFill BrowserWaitFor");
119        assert_eq!(relabel("Browser", ACTS, "BrowserFill e1: done. The element now: BrowserFill"), "Browser fill e1: done. The element now: BrowserFill");
120        let e = relabeled("Browser", ACTS, Err(anyhow::anyhow!("BrowserFill e3 failed"))).unwrap_err();
121        assert_eq!(e.to_string(), "Browser fill e3 failed");
122    }
123
124    #[test]
125    fn a_renamed_parameter_is_named_as_the_caller_passes_it() {
126        let rename = &[("agent", "agent_id"), ("view", "kind")][..];
127        assert_eq!(public_params("missing required parameter: agent_id", rename), "missing required parameter: agent");
128        assert_eq!(public_params("missing required parameter: kind", rename), "missing required parameter: view");
129        assert_eq!(
130            public_params("invalid kind: maybe (expected \"editor\" or \"files\")", rename),
131            "invalid view: maybe (expected \"editor\" or \"files\")"
132        );
133        assert_eq!(public_params("missing required parameter: reason", rename), "missing required parameter: reason");
134    }
135
136    #[test]
137    fn a_missing_or_unknown_action_lists_the_actions() {
138        let e = pick("Browser", ACTS, &json!({})).unwrap_err().to_string();
139        assert_eq!(e, "Browser: missing required parameter: action (one of fill, wait)");
140        let e = pick("Browser", ACTS, &json!({ "action": "type" })).unwrap_err().to_string();
141        assert_eq!(e, "Browser: unknown action \"type\": use one of fill, wait");
142    }
143}