Skip to main content

agentmux_mcp/tools/
agents_hosts.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents list` and `Agents status` across machines (docs/specs/SPEC_MUXAPI_AGENT_LIVE_FACTS_2026_11_20.md ยง6):
5//! `host` names one LAN peer, or `all` for this machine and every pinned peer. Each peer is asked `agents.status`
6//! at once with a short wait; a peer that does not answer, or is too old to know the op, is listed by what the LAN
7//! poll already says of it (`facts: "liveness_only"`) and named in the `hosts` block. Nothing is guessed: a missing
8//! field is absent.
9
10use std::collections::{BTreeMap, HashSet};
11use std::time::Duration;
12
13use futures_util::future::join_all;
14
15use super::*;
16
17/// How long a peer has to answer before it is listed as unreachable.
18const PEER_WAIT: Duration = Duration::from_secs(3);
19
20/// What a peer said to `agents.status`, or why it did not.
21#[derive(Debug, Clone, PartialEq)]
22pub(super) struct PeerReply {
23    pub host: String,
24    /// `ok`, `unreachable`, `needs_upgrade` or `refused`.
25    pub state: &'static str,
26    pub detail: Option<String>,
27    pub version: Option<String>,
28    pub as_of_ms: Option<u64>,
29    /// The peer's answer: `{agents, page}` for a list, the compact status for a status.
30    pub answer: Option<Value>,
31}
32
33impl PeerReply {
34    fn failed(host: &str, state: &'static str, detail: String) -> Self {
35        Self { host: host.to_string(), state, detail: Some(detail), version: None, as_of_ms: None, answer: None }
36    }
37}
38
39/// The name a peer is asked by: `name`, or `name/channel[/install]` so two instances of one machine are told apart.
40fn target_of(peer: &Value) -> String {
41    let text = |key: &str| peer.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string();
42    let (name, channel, install) = (text("hostname"), text("channel"), text("install"));
43    match (channel.is_empty(), install.is_empty()) {
44        (true, _) => name,
45        (false, true) => format!("{name}/{channel}"),
46        (false, false) => format!("{name}/{channel}/{install}"),
47    }
48}
49
50/// The peers `host: all` asks, from the local answer's `peers`: one per instance, with what the LAN poll says of each.
51fn peers_of(local: &Value) -> Vec<(String, Value)> {
52    let mut seen = HashSet::new();
53    local
54        .get("peers")
55        .and_then(Value::as_array)
56        .into_iter()
57        .flatten()
58        .filter(|p| {
59            let id = p.get("instance_id").and_then(Value::as_str).filter(|i| !i.is_empty()).map_or_else(|| target_of(p), str::to_string);
60            !target_of(p).is_empty() && seen.insert(id)
61        })
62        .map(|p| (target_of(p), p.clone()))
63        .collect()
64}
65
66/// How a peer's answer to the op reads: its facts, or the state it is in and why.
67fn reply_of(host: &str, answer: &Value) -> PeerReply {
68    if answer["status"].as_str() == Some("done") {
69        let result = &answer["result"];
70        return PeerReply {
71            host: host.to_string(),
72            state: "ok",
73            detail: None,
74            version: result["version"].as_str().map(str::to_string),
75            as_of_ms: result["as_of_ms"].as_u64(),
76            answer: Some(result["answer"].clone()),
77        };
78    }
79    let problem = remote_op::explain_not_done(host, "agents.status", answer).unwrap_or_else(|| format!("{host} did not run agents.status"));
80    let state = match (answer["status"].as_str(), answer["refused_reason"].as_str()) {
81        (Some("refused"), Some("unknown_op" | "peer_cannot_do_remote_ops")) => "needs_upgrade",
82        (Some("refused"), _) => "refused",
83        _ => "unreachable",
84    };
85    PeerReply::failed(host, state, problem)
86}
87
88async fn ask(cx: &ToolCtx<'_>, host: &str, params: &Value, reason: &str) -> PeerReply {
89    match tokio::time::timeout(PEER_WAIT, remote_op::remote_op_call(cx, host, "agents.status", params.clone(), reason)).await {
90        Err(_) => PeerReply::failed(host, "unreachable", format!("{host} did not answer in {} seconds", PEER_WAIT.as_secs())),
91        Ok(Err(e)) => PeerReply::failed(host, "unreachable", format!("{e:#}")),
92        Ok(Ok(answer)) => reply_of(host, &answer),
93    }
94}
95
96/// `Agents list` or `Agents status` with `host`: one peer, or `all`.
97pub(super) async fn across(cx: &ToolCtx<'_>, args: &Value, status: bool, host: &str) -> Result<String> {
98    let (local, targets) = if host.eq_ignore_ascii_case("all") {
99        let local = fleet::discover_value(args, status, true, cx).await?;
100        let targets = peers_of(&local);
101        (Some(local), targets)
102    } else {
103        (None, vec![(host.to_string(), Value::Null)])
104    };
105    let params = Value::Object(fleet::discovery_query(args, status).into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect());
106    let reason = args.get("reason").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("Agents {}", if status { "status" } else { "list" }));
107    let replies = join_all(targets.iter().map(|(name, _)| ask(cx, name, &params, &reason))).await;
108    let peers: Vec<(PeerReply, Value)> = replies.into_iter().zip(targets.into_iter().map(|(_, lan)| lan)).collect();
109    let now_ms = agentmux_common::time::now_ms_u64();
110    let merged = if status { merge_status(local, &peers, now_ms) } else { merge_list(local, &peers, now_ms) };
111    Ok(serde_json::to_string_pretty(&merged).unwrap_or_else(|_| merged.to_string()))
112}
113
114fn tagged(mut row: Value, host: &str) -> Value {
115    if let Some(fields) = row.as_object_mut() {
116        fields.insert("host".to_string(), json!(host));
117    }
118    row
119}
120
121/// A peer's agents as the LAN poll lists them: name, state, provider and kind, and nothing else.
122fn liveness_rows(host: &str, lan: &Value) -> Vec<Value> {
123    lan.get("agents")
124        .and_then(Value::as_array)
125        .into_iter()
126        .flatten()
127        .filter_map(Value::as_str)
128        .map(|name| {
129            let key = name.to_lowercase();
130            let mut row = json!({ "name": name, "host": host, "facts": "liveness_only" });
131            for (field, from) in [("state", "agent_status"), ("provider", "agent_providers"), ("kind", "agent_kinds")] {
132                if let Some(value) = lan.get(from).and_then(|m| m.get(key.as_str())).filter(|v| !v.is_null()) {
133                    row[field] = value.clone();
134                }
135            }
136            row
137        })
138        .collect()
139}
140
141/// One entry of the `hosts` block.
142fn host_entry(reply: &PeerReply, lan: &Value, now_ms: u64) -> Value {
143    let version = reply.version.clone().or_else(|| lan.get("version").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string));
144    let mut entry = json!({ "host": reply.host, "reachable": reply.state == "ok", "state": reply.state });
145    if let Some(v) = version {
146        entry["version"] = json!(v);
147    }
148    if let Some(at) = reply.as_of_ms {
149        entry["as_of_ms"] = json!(at);
150        entry["age_ms"] = json!(now_ms.saturating_sub(at));
151    }
152    if let Some(why) = &reply.detail {
153        entry["error"] = json!(why);
154    }
155    entry
156}
157
158/// This machine's own `hosts` entry.
159fn this_host_entry(local: &Value, now_ms: u64) -> Option<(String, Value)> {
160    let name = local.pointer("/host/hostname").or_else(|| local.get("host")).and_then(Value::as_str)?.to_string();
161    let version = local.pointer("/host/version").cloned();
162    let mut entry = json!({ "host": name, "reachable": true, "state": "ok", "this_machine": true, "as_of_ms": now_ms, "age_ms": 0 });
163    if let Some(v) = version.filter(|v| v.is_string()) {
164        entry["version"] = v;
165    }
166    Some((name, entry))
167}
168
169/// `Agents list` across machines: every machine's rows, each saying which machine it came from, and the `hosts` block.
170pub(super) fn merge_list(local: Option<Value>, peers: &[(PeerReply, Value)], now_ms: u64) -> Value {
171    let mut body = local.unwrap_or_else(|| json!({ "host": {} }));
172    let (mut hosts, mut rows) = (Vec::new(), Vec::new());
173    let mut total = 0u64;
174    if let Some((name, entry)) = this_host_entry(&body, now_ms) {
175        let own = body.pointer("/host/agents").and_then(Value::as_array).cloned().unwrap_or_default();
176        total += body.pointer("/host/page/total").and_then(Value::as_u64).unwrap_or(own.len() as u64);
177        rows.extend(own.into_iter().map(|r| tagged(r, &name)));
178        hosts.push(entry);
179    }
180    for (reply, lan) in peers {
181        match reply.answer.as_ref().filter(|_| reply.state == "ok") {
182            Some(answer) => {
183                let theirs = answer.get("agents").and_then(Value::as_array).cloned().unwrap_or_default();
184                total += answer.pointer("/page/total").and_then(Value::as_u64).unwrap_or(theirs.len() as u64);
185                rows.extend(theirs.into_iter().map(|r| tagged(r, &reply.host)));
186            }
187            None => {
188                let listed = liveness_rows(&reply.host, lan);
189                total += listed.len() as u64;
190                rows.extend(listed);
191            }
192        }
193        hosts.push(host_entry(reply, lan, now_ms));
194    }
195    body["host"]["page"] = json!({ "total": total, "returned": rows.len(), "note": "limit and offset apply to each machine" });
196    body["host"]["agents"] = Value::Array(rows);
197    body["hosts"] = Value::Array(hosts);
198    if let Some(fields) = body.as_object_mut() {
199        fields.remove("peers");
200    }
201    body
202}
203
204/// A status line with its machine as the second column: `name | host | state ...`.
205fn line_with_host(line: &str, host: &str) -> String {
206    match line.split_once(" | ") {
207        Some((name, rest)) => format!("{name} | {host} | {rest}"),
208        None => format!("{line} | {host}"),
209    }
210}
211
212fn add_counts(into: &mut BTreeMap<String, u64>, counts: Option<&Value>) {
213    for (key, n) in counts.and_then(Value::as_object).into_iter().flatten() {
214        *into.entry(key.clone()).or_default() += n.as_u64().unwrap_or(0);
215    }
216}
217
218/// What `Agents status` adds up over the machines.
219#[derive(Default)]
220struct Tally {
221    lines: Vec<String>,
222    by_state: BTreeMap<String, u64>,
223    by_model: BTreeMap<String, u64>,
224    by_host: BTreeMap<String, u64>,
225    groups: BTreeMap<String, Vec<String>>,
226    total: u64,
227    group_by: Option<String>,
228}
229
230impl Tally {
231    /// A machine's own compact status.
232    fn take(&mut self, host: &str, status: &Value) {
233        let theirs: Vec<&str> = status.get("lines").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
234        self.total += status.get("total").and_then(Value::as_u64).unwrap_or(theirs.len() as u64);
235        self.by_host.insert(host.to_string(), theirs.len() as u64);
236        self.lines.extend(theirs.iter().map(|l| line_with_host(l, host)));
237        add_counts(&mut self.by_state, status.pointer("/counts/by_state"));
238        add_counts(&mut self.by_model, status.pointer("/counts/by_model"));
239        for group in status.get("groups").and_then(Value::as_array).into_iter().flatten() {
240            let key = group.get("key").and_then(Value::as_str).unwrap_or("unknown").to_string();
241            let members = group.get("agents").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
242            self.groups.entry(key).or_default().extend(members.map(|m| format!("{m}@{host}")));
243        }
244        if self.group_by.is_none() {
245            self.group_by = status.get("group_by").and_then(Value::as_str).map(str::to_string);
246        }
247    }
248
249    /// A machine that gave no facts: its agents as the LAN poll lists them.
250    fn liveness(&mut self, host: &str, lan: &Value) {
251        let listed = liveness_rows(host, lan);
252        self.total += listed.len() as u64;
253        self.by_host.insert(host.to_string(), listed.len() as u64);
254        self.lines.extend(listed.iter().map(|r| {
255            let state = r.get("state").map_or_else(|| "state unknown".to_string(), |s| s.as_str().map_or_else(|| s.to_string(), str::to_string));
256            format!("{} | {host} | {state} (liveness only)", r["name"].as_str().unwrap_or_default())
257        }));
258    }
259}
260
261/// `Agents status` across machines: the lines with their machine, the counts added up (and by machine), the groups merged.
262pub(super) fn merge_status(local: Option<Value>, peers: &[(PeerReply, Value)], now_ms: u64) -> Value {
263    let (mut tally, mut hosts) = (Tally::default(), Vec::new());
264    if let Some(local) = &local {
265        if let Some((name, entry)) = this_host_entry(local, now_ms) {
266            tally.take(&name, local);
267            hosts.push(entry);
268        }
269    }
270    for (reply, lan) in peers {
271        match reply.answer.as_ref().filter(|_| reply.state == "ok") {
272            Some(status) => tally.take(&reply.host, status),
273            None => tally.liveness(&reply.host, lan),
274        }
275        hosts.push(host_entry(reply, lan, now_ms));
276    }
277    let mut out = json!({
278        "total": tally.total,
279        "returned": tally.lines.len(),
280        "lines": tally.lines,
281        "counts": { "by_state": tally.by_state, "by_model": tally.by_model, "by_host": tally.by_host },
282        "hosts": hosts,
283    });
284    if let Some(g) = tally.group_by {
285        out["group_by"] = json!(g);
286        out["groups"] = json!(tally.groups.into_iter().map(|(k, v)| json!({ "key": k, "count": v.len(), "agents": v })).collect::<Vec<_>>());
287    }
288    out
289}
290
291#[cfg(test)]
292#[path = "agents_hosts_tests.rs"]
293mod tests;