Skip to main content

agentmux_mcp/tools/
zoom_tool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Zoom: read and set the zoom of the panes in the caller's own tab and of its own window's chrome
5//! (docs/specs/SPEC_MUXAPI_ZOOM_2026_11_24.md). srv decides which panes are the caller's and the window applies the
6//! change and tells the person; this only carries the call, as the agent its token names.
7
8use super::*;
9
10const ACTIONS: &[&str] = &["get", "set", "reset", "undo", "fit", "check"];
11
12pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
13    match name {
14        "Zoom" => {
15            require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
16            let action = arguments.get("action").and_then(Value::as_str).map(str::trim).unwrap_or("");
17            if !ACTIONS.contains(&action) {
18                anyhow::bail!("Zoom: unknown action {action:?}; use {}", ACTIONS.join(", "));
19            }
20            let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty()).ok_or_else(|| anyhow::anyhow!("AGENTMUX_AGENT_ID is not set"))?;
21            let body = body_of(&self_id, arguments)?;
22            if let Some(host) = remote_op::host_arg(arguments) {
23                return remote(action, body, arguments, cx, &host).await;
24            }
25            let url = format!("{}/api/v1/ui/zoom/{action}", cx.local_url.trim_end_matches('/'));
26            let reply = crate::srv_http::srv_post_json(cx.client, &url, cx.auth_key, &body, &format!("Zoom {action}")).await?;
27            Ok(serde_json::to_string_pretty(&reply).unwrap_or_default())
28        }
29        _ => Err(not_in_family()),
30    }
31}
32
33/// An action on another machine, as the same agent: `zoom.<action>` over remote ops. That machine decides the window and
34/// tab (the one the person is on), so a call other than `get` carries the `window` and `tab` its `get` answered.
35async fn remote(action: &str, body: Value, arguments: &Value, cx: &ToolCtx<'_>, host: &str) -> Result<String> {
36    let body = remote_body(body, arguments);
37    let op = format!("zoom.{action}");
38    let reason = arguments.get("reason").and_then(Value::as_str).map(str::trim).filter(|r| !r.is_empty()).map_or_else(|| format!("Zoom {action}"), str::to_string);
39    let answer = remote_op::remote_op_call(cx, host, &op, body, &reason).await?;
40    if let Some(problem) = remote_op::explain_not_done(host, &op, &answer) {
41        anyhow::bail!("{problem}");
42    }
43    Ok(remote_op::pretty(host, &answer))
44}
45
46/// What goes to the other machine: the arguments, with the window and tab of its `get` and without the caller (that
47/// machine knows who asks from the key the call is signed with).
48fn remote_body(mut body: Value, arguments: &Value) -> Value {
49    if let Some(m) = body.as_object_mut() {
50        m.remove("agent_id");
51        for key in ["window", "tab"] {
52            if let Some(v) = arguments.get(key).filter(|v| v.is_string()) {
53                m.insert(key.into(), v.clone());
54            }
55        }
56    }
57    body
58}
59
60/// `value` as a factor: a number (1.0 is 100%), or a string like `"83%"` or `"0.83"`.
61fn parse_value(v: &Value) -> Result<f64> {
62    let bad = || anyhow::anyhow!("value is a zoom factor from 0.5 to 2.0 (1.0 is 100%), or a percentage like \"83%\"");
63    match v {
64        Value::Number(n) => n.as_f64().ok_or_else(bad),
65        Value::String(s) => {
66            let s = s.trim();
67            match s.strip_suffix('%') {
68                Some(p) => p.trim().parse::<f64>().map(|p| p / 100.0).map_err(|_| bad()),
69                None => s.parse::<f64>().map_err(|_| bad()),
70            }
71        }
72        _ => Err(bad()),
73    }
74}
75
76/// What srv is sent: the caller, and the arguments the actions take. Nothing in it says whose pane is whose.
77fn body_of(self_id: &str, arguments: &Value) -> Result<Value> {
78    let mut body = json!({ "agent_id": self_id });
79    for key in ["scope", "target", "block", "blocks", "token", "chrome", "axis", "apply", "max", "min_text_px"] {
80        if let Some(v) = arguments.get(key).filter(|v| !v.is_null()) {
81            body[key] = v.clone();
82        }
83    }
84    if let Some(v) = arguments.get("value").filter(|v| !v.is_null()) {
85        body["value"] = json!(parse_value(v)?);
86    }
87    Ok(body)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn every_action_is_in_the_schema() {
96        let schema: Value = serde_json::from_str(crate::tool_schemas::ZOOM_TOOL).unwrap();
97        let mut listed: Vec<&str> = schema["inputSchema"]["properties"]["action"]["enum"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
98        let mut want = ACTIONS.to_vec();
99        listed.sort();
100        want.sort();
101        assert_eq!(listed, want);
102    }
103
104    #[test]
105    fn a_value_is_a_factor_or_a_percentage() {
106        assert_eq!(parse_value(&json!(0.83)).unwrap(), 0.83);
107        assert_eq!(parse_value(&json!("83%")).unwrap(), 0.83);
108        assert_eq!(parse_value(&json!(" 125 % ")).unwrap(), 1.25);
109        assert_eq!(parse_value(&json!("0.8")).unwrap(), 0.8);
110        assert!(parse_value(&json!("big")).is_err());
111        assert!(parse_value(&json!(true)).is_err());
112    }
113
114    #[test]
115    fn the_caller_is_the_agent_and_only_the_known_arguments_go_to_srv() {
116        let args = json!({ "action": "set", "target": "pane", "block": "b1", "value": "80%", "agent_id": "someone-else", "tab": "t9", "extra": 1 });
117        let body = body_of("loap", &args).unwrap();
118        assert_eq!(body["agent_id"], "loap", "an argument can't name another caller");
119        assert_eq!((body["target"].as_str(), body["block"].as_str(), body["value"].as_f64()), (Some("pane"), Some("b1"), Some(0.8)));
120        assert!(body.get("extra").is_none() && body.get("action").is_none() && body.get("tab").is_none());
121    }
122
123    #[test]
124    fn a_call_over_host_carries_the_window_and_tab_but_not_the_caller() {
125        let args = json!({ "action": "set", "host": "charlie", "target": "pane", "block": "b1", "value": 0.8, "window": "w1", "tab": "t1" });
126        let local = body_of("loap", &args).unwrap();
127        assert!(local.get("window").is_none(), "a local call does not carry them");
128        let body = remote_body(local, &args);
129        assert_eq!(body, json!({ "target": "pane", "block": "b1", "value": 0.8, "window": "w1", "tab": "t1" }));
130    }
131
132    #[tokio::test]
133    async fn an_unknown_action_is_refused_before_anything_is_sent() {
134        let client = reqwest::Client::new();
135        let loops = LoopRegistry::default();
136        let counter = std::sync::atomic::AtomicU64::new(0);
137        let cx = ToolCtx { local_url: "http://127.0.0.1:1", auth_key: "k", block_id: "b", client: &client, loops: &loops, loop_counter: &counter };
138        let e = call("Zoom", &json!({ "action": "delete" }), &cx).await.unwrap_err().to_string();
139        assert!(e.starts_with("Zoom: unknown action"), "{e}");
140    }
141}