Skip to main content

agentmux_mcp/tools/
remote_op.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The `host` argument of the MuxAPI tools: run an operation on another machine
5//! (`docs/specs/SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md` ยง4.8).
6//!
7//! This machine's srv builds the request, signs it with the agent's own key and sends it
8//! (`POST /api/v1/agent/remote/op`); the other machine's srv carries it out. The host must be
9//! named on each call, never inherited from an earlier one, so a local action can't silently
10//! become a remote one, and the answer says which machine gave it.
11
12use super::*;
13
14/// The `host` argument: a machine's name as `Agents list` shows it. Absent or blank means this machine.
15pub(super) fn host_arg(arguments: &Value) -> Option<String> {
16    arguments.get("host").and_then(Value::as_str).map(str::trim).filter(|h| !h.is_empty()).map(str::to_string)
17}
18
19/// Run `op` with `params` on `host` as this agent. The answer is srv's `RemoteOpResult` as JSON
20/// (`status`, `result`, `audit_id`, `refused_reason`); an error is only a failure to ask.
21pub(crate) async fn remote_op_call(cx: &ToolCtx<'_>, host: &str, op: &str, params: Value, reason: &str) -> Result<Value> {
22    require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
23    let url = format!("{}/api/v1/agent/remote/op", cx.local_url.trim_end_matches('/'));
24    let body = json!({ "agent_id": agent_slug()?, "host": host, "op": op, "params": params, "reason": reason });
25    let resp = cx
26        .client
27        .post(&url)
28        .header(AUTH_KEY_HEADER, cx.auth_key)
29        .json(&body)
30        .send()
31        .await
32        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
33    let status = resp.status();
34    let answer: Value = resp.json().await.unwrap_or(Value::Null);
35    if !status.is_success() {
36        anyhow::bail!("{op} on {host}: srv answered {status}: {}", answer["error"].as_str().unwrap_or(&answer.to_string()));
37    }
38    Ok(answer)
39}
40
41/// What a non-`done` answer says, for the agent to read; `None` when the operation ran.
42pub(crate) fn explain_not_done(host: &str, op: &str, answer: &Value) -> Option<String> {
43    match answer["status"].as_str() {
44        Some("done") => None,
45        Some("queued") | Some("pending_veto") => None,
46        Some("refused") => {
47            let why = answer["refused_reason"].as_str().unwrap_or("no reason given");
48            let message = answer["result"]["message"].as_str().map(|m| format!(": {m}")).unwrap_or_default();
49            // For a machine too old for this, the message already names both versions.
50            let hint = if message.is_empty() { refusal_hint(why) } else if matches!(why, "unknown_op" | "peer_cannot_do_remote_ops") { String::new() } else { refusal_hint(why) };
51            // One full stop: a message that ends with one (the sentence for an older machine does) doesn't get a second.
52            let head = format!("{host} refused {op} ({why}){message}");
53            let head = head.trim_end().trim_end_matches('.');
54            Some(if hint.is_empty() { format!("{head}.") } else { format!("{head}. {hint}") })
55        }
56        _ => Some(format!("{op} on {host} failed: {}", answer["result"]["error"].as_str().unwrap_or("no reason given"))),
57    }
58}
59
60/// What to do about a refusal the transport itself made.
61fn refusal_hint(reason: &str) -> String {
62    let hint: &str = match reason {
63        "remote_ops_off" => "That machine has turned remote operations off (network:remote_ops in its settings).",
64        "unknown_sender" | "unverified_sender" => "That machine does not yet trust this agent's key: ask one of its agents to jekt you once, so each side pins the other, then retry.",
65        "bad_signature" | "wrong_audience" | "stale_request" => "Check that both machines' clocks are right and both run a build with remote operations.",
66        "needs_certificate" => "That machine holds no certificate from your agent's install. Approve this install on that machine (the instance is listed there), then retry; a first-seen peer is not enough for account data or changes.",
67        "install_not_trusted" => "That machine has not approved the install your agent runs on. Approve this instance on that machine, then retry.",
68        "unknown_op" | "peer_cannot_do_remote_ops" => {
69            return format!("That machine's AgentMux is too old for this: update it to AgentMux {} or newer.", env!("CARGO_PKG_VERSION"));
70        }
71        _ => "",
72    };
73    hint.to_string()
74}
75
76/// `answer` as text, headed by the machine that gave it.
77pub(crate) fn pretty(host: &str, answer: &Value) -> String {
78    let body = serde_json::to_string_pretty(&answer["result"]).unwrap_or_else(|_| answer["result"].to_string());
79    let status = answer["status"].as_str().unwrap_or("done");
80    let mark = if status == "done" { String::new() } else { format!(" [{status}]") };
81    format!("From {host}{mark}:\n{body}")
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn a_refusal_for_an_older_machine_names_the_version_to_update_to_once() {
90        let own = env!("CARGO_PKG_VERSION");
91        // With the sending machine's sentence (it names both versions), the hint is not said again.
92        let with = json!({ "status": "refused", "refused_reason": "peer_cannot_do_remote_ops", "result": { "message": "Area54 runs AgentMux 0.60.31, which is too old to do remote operations: update it to AgentMux 0.60.53 or newer." } });
93        let said = explain_not_done("Area54", "agents.list", &with).unwrap();
94        assert!(said.contains("0.60.31") && said.matches("update it to").count() == 1, "{said}");
95        assert!(!said.contains(".."), "{said}");
96        // Without one, this machine's version is still named.
97        for reason in ["peer_cannot_do_remote_ops", "unknown_op"] {
98            let bare = json!({ "status": "refused", "refused_reason": reason, "result": null });
99            let said = explain_not_done("Area54", "agents.list", &bare).unwrap();
100            assert!(said.ends_with(&format!("update it to AgentMux {own} or newer.")), "{said}");
101        }
102    }
103
104    #[test]
105    fn a_blank_host_is_this_machine() {
106        assert_eq!(host_arg(&json!({})), None);
107        assert_eq!(host_arg(&json!({ "host": "  " })), None);
108        assert_eq!(host_arg(&json!({ "host": " narko " })), Some("narko".to_string()));
109    }
110
111    #[test]
112    fn a_refusal_says_who_refused_why_and_what_to_do() {
113        let answer = json!({ "status": "refused", "refused_reason": "remote_ops_off", "result": null });
114        let text = explain_not_done("narko", "app.version", &answer).unwrap();
115        assert!(text.contains("narko refused app.version (remote_ops_off)") && text.contains("network:remote_ops"), "{text}");
116        let none = json!({ "status": "refused", "result": null });
117        assert!(explain_not_done("narko", "app.version", &none).unwrap().contains("no reason given"));
118    }
119
120    #[test]
121    fn a_done_or_waiting_answer_is_not_an_error() {
122        for status in ["done", "queued", "pending_veto"] {
123            assert!(explain_not_done("narko", "x", &json!({ "status": status })).is_none(), "{status}");
124        }
125        assert!(explain_not_done("narko", "x", &json!({ "status": "failed", "result": { "error": "boom" } })).unwrap().contains("boom"));
126    }
127
128    #[test]
129    fn the_answer_names_the_machine() {
130        let text = pretty("narko", &json!({ "status": "done", "result": { "version": "0.60.7" } }));
131        assert!(text.starts_with("From narko:") && text.contains("0.60.7"), "{text}");
132        assert!(pretty("narko", &json!({ "status": "queued", "result": {} })).starts_with("From narko [queued]:"));
133    }
134}