Skip to main content

agentmux_mcp/tools/
vault_tool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Vault: the person's secrets, named but never read
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §5.4).
6//! `list` reads entries' names; `request` asks the person for a new entry
7//! and waits for the answer; `generate` creates an entry whose value the
8//! Vault makes (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.1).
9//! No route an agent can call returns a value.
10
11use super::*;
12
13/// How long `request` waits for the person by default, and at most.
14const REQUEST_WAIT_SECS: u64 = 300;
15const REQUEST_WAIT_MAX_SECS: u64 = 600;
16
17/// `history`: an entry's history, for an entry in a Vault this agent may use. No value in it.
18async fn history(arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
19    let id = arguments.get("id").and_then(Value::as_str).unwrap_or("").trim();
20    if id.is_empty() {
21        anyhow::bail!("Vault history needs an id: the entry whose history to read (list shows them)");
22    }
23    let body = json!({
24        "id": id,
25        "limit": arguments.get("limit").and_then(Value::as_i64),
26        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault history needs this agent's signed identity: {e}"))?,
27    });
28    let result = crate::srv_http::srv_post_json(cx.client, &format!("{base}/api/v1/vault/history"), cx.auth_key, &body, "Vault history").await?;
29    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
30}
31
32/// Posts `body` to a Vault route that may wait for the person for `wait` seconds before it answers.
33async fn post_waiting(cx: &ToolCtx<'_>, url: &str, body: &Value, what: &str, wait: u64) -> Result<String> {
34    let resp = cx
35        .client
36        .post(url)
37        .header(AUTH_KEY_HEADER, cx.auth_key)
38        .timeout(std::time::Duration::from_secs(wait + 90))
39        .json(body)
40        .send()
41        .await
42        .map_err(|e| anyhow::anyhow!(crate::srv_http::describe_transport_error(what, url, &e)))?;
43    let status = resp.status();
44    let text = resp.text().await.unwrap_or_default();
45    if !status.is_success() {
46        anyhow::bail!(crate::srv_http::describe_http_error(what, status, &text));
47    }
48    let result: Value = serde_json::from_str(&text).unwrap_or_default();
49    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
50}
51
52/// `share`: ask the person to share a login with this agent's own browser profile. Only for the caller itself: srv
53/// refuses a request that names another agent, and the answer says the login's label and site, never the user name or password.
54async fn share(arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
55    let id = arguments.get("id").and_then(Value::as_str).unwrap_or("").trim();
56    if id.is_empty() {
57        anyhow::bail!("Vault share needs an id: the login to be given (list shows the logins you may use)");
58    }
59    let wait = arguments.get("wait_secs").and_then(Value::as_u64).unwrap_or(REQUEST_WAIT_SECS).min(REQUEST_WAIT_MAX_SECS);
60    let body = json!({
61        "id": id,
62        "reason": arguments.get("reason").and_then(Value::as_str),
63        "agent": arguments.get("agent").and_then(Value::as_str),
64        "wait_secs": wait,
65        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault share needs this agent's signed identity: {e}"))?,
66    });
67    post_waiting(cx, &format!("{base}/api/v1/vault/share"), &body, "Vault share", wait).await
68}
69
70/// `check`: whether an entry's machine copy still holds the entry's value. The answer is `same`, `different` or
71/// `could not read` with why; neither value comes back.
72async fn check(arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
73    let id = arguments.get("id").and_then(Value::as_str).unwrap_or("").trim();
74    if id.is_empty() {
75        anyhow::bail!("Vault check needs an id: the entry whose machine copy to check (list shows which have a source)");
76    }
77    let body = json!({
78        "id": id,
79        "reason": arguments.get("reason").and_then(Value::as_str),
80        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault check needs this agent's signed identity: {e}"))?,
81    });
82    // The read of the other place: the CLI's wait (`RECIPE_TIMEOUT`, 50 s) and some room.
83    post_waiting(cx, &format!("{base}/api/v1/vault/check"), &body, "Vault check", 0).await
84}
85
86/// `show`, `verify` and `health` read the Vault; `update` changes an entry's details and asks nobody. None returns a value.
87async fn inspect(action: &str, arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
88    let text = |k: &str| arguments.get(k).and_then(Value::as_str);
89    let auth = crate::identity::sign_ui_automation_auth();
90    let body = match action {
91        "show" | "verify" => {
92            if action == "show" && text("id").is_none_or(|i| i.trim().is_empty()) {
93                anyhow::bail!("Vault show needs an id: the entry to look at (list shows them)");
94            }
95            json!({ "id": text("id"), "auth": auth.ok() })
96        }
97        "update" => json!({
98            "id": text("id").filter(|i| !i.trim().is_empty()).ok_or_else(|| anyhow::anyhow!("Vault update needs an id: the entry to change (list shows them)"))?,
99            "label": text("label"),
100            "fields": arguments.get("fields").filter(|f| f.is_object()).cloned().unwrap_or_else(|| json!({})),
101            "tags": arguments.get("tags").cloned(),
102            "reason": text("reason"),
103            "auth": auth.map_err(|e| anyhow::anyhow!("Vault update needs this agent's signed identity: {e}"))?,
104        }),
105        _ => json!({ "auth": auth.ok() }),
106    };
107    let what = format!("Vault {action}");
108    let result = crate::srv_http::srv_post_json(cx.client, &format!("{base}/api/v1/vault/{action}"), cx.auth_key, &body, &what).await?;
109    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
110}
111
112/// `import`: copy a secret from AWS Secrets Manager into the Vault. Nobody is asked (a login to be shared aside); the agent gets ids and names.
113async fn import(arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
114    let source = arguments.get("source").cloned().unwrap_or(Value::Null);
115    if !source.get("aws_secret_id").is_some_and(Value::is_string) {
116        anyhow::bail!("Vault import needs source.aws_secret_id: the AWS secret to copy (its name or ARN)");
117    }
118    let s = |k: &str| arguments.get(k).and_then(Value::as_str).unwrap_or("").to_string();
119    let wait = arguments.get("wait_secs").and_then(Value::as_u64).unwrap_or(REQUEST_WAIT_SECS).min(REQUEST_WAIT_MAX_SECS);
120    let body = json!({
121        "source": source,
122        "kind": s("kind"),
123        "label": s("label"),
124        "id": arguments.get("id").and_then(Value::as_str),
125        "fields": arguments.get("fields").cloned().unwrap_or_else(|| json!({})),
126        "vault": arguments.get("vault").and_then(Value::as_str),
127        "reason": arguments.get("reason").and_then(Value::as_str),
128        "refs": arguments.get("refs").cloned().unwrap_or_else(|| json!([])),
129        "share": arguments.get("share").and_then(Value::as_bool).unwrap_or(false),
130        "wait_secs": wait,
131        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault import needs this agent's signed identity: {e}"))?,
132    });
133    // The person's answer, then AWS: the wait plus the CLI's wait (`RECIPE_TIMEOUT`, 50 s) and some room.
134    let url = format!("{base}/api/v1/vault/import");
135    let resp = cx
136        .client
137        .post(&url)
138        .header(AUTH_KEY_HEADER, cx.auth_key)
139        .timeout(std::time::Duration::from_secs(wait + 90))
140        .json(&body)
141        .send()
142        .await
143        .map_err(|e| anyhow::anyhow!(crate::srv_http::describe_transport_error("Vault import", &url, &e)))?;
144    let status = resp.status();
145    let text = resp.text().await.unwrap_or_default();
146    if !status.is_success() {
147        anyhow::bail!(crate::srv_http::describe_http_error("Vault import", status, &text));
148    }
149    let result: Value = serde_json::from_str(&text).unwrap_or_default();
150    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
151}
152
153/// `rotate`: give an entry a new value the Vault makes, and set it at its service with the agent's command.
154async fn rotate(arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
155    let s = |k: &str| arguments.get(k).and_then(Value::as_str).unwrap_or("").to_string();
156    let body = json!({
157        "id": s("id"),
158        "set": s("set"),
159        "verify": arguments.get("verify").and_then(Value::as_str),
160        "reason": arguments.get("reason").and_then(Value::as_str),
161        "cwd": arguments.get("cwd").and_then(Value::as_str),
162        "rules": arguments.get("rules").cloned().unwrap_or_else(|| json!({})),
163        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault rotate needs this agent's signed identity: {e}"))?,
164    });
165    // The person's approval, then set and verify, each up to 10 minutes.
166    let url = format!("{base}/api/v1/vault/rotate");
167    let resp = cx
168        .client
169        .post(&url)
170        .header(AUTH_KEY_HEADER, cx.auth_key)
171        .timeout(std::time::Duration::from_secs(32 * 60))
172        .json(&body)
173        .send()
174        .await
175        .map_err(|e| anyhow::anyhow!(crate::srv_http::describe_transport_error("Vault rotate", &url, &e)))?;
176    let status = resp.status();
177    let text = resp.text().await.unwrap_or_default();
178    if !status.is_success() {
179        anyhow::bail!(crate::srv_http::describe_http_error("Vault rotate", status, &text));
180    }
181    let result: Value = serde_json::from_str(&text).unwrap_or_default();
182    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
183}
184
185/// How long srv lets a batch's reads take, after the person's answer.
186const BATCH_READ_SECS: u64 = 300;
187
188/// `import_batch`: copy a named list of secrets from AWS Secrets Manager into one Vault under one approval. The
189/// person sees a row for every secret and may leave rows out; the agent gets a row per secret, never a value.
190async fn import_batch(arguments: &Value, cx: &ToolCtx<'_>, base: &str) -> Result<String> {
191    if !arguments.get("items").and_then(Value::as_array).is_some_and(|items| !items.is_empty()) {
192        anyhow::bail!("Vault import_batch needs items: the secrets to copy, each with aws_secret_id, kind and label (or id, to replace an entry's value)");
193    }
194    let wait = arguments.get("wait_secs").and_then(Value::as_u64).unwrap_or(REQUEST_WAIT_SECS).min(REQUEST_WAIT_MAX_SECS);
195    let body = json!({
196        "batch": arguments.get("batch").and_then(Value::as_str).unwrap_or(""),
197        "vault": arguments.get("vault").and_then(Value::as_str),
198        "reason": arguments.get("reason").and_then(Value::as_str),
199        "source": arguments.get("source").filter(|s| s.is_object()).cloned().unwrap_or_else(|| json!({})),
200        "items": arguments.get("items").cloned().unwrap_or_else(|| json!([])),
201        "refs": arguments.get("refs").cloned().unwrap_or_else(|| json!([])),
202        "wait_secs": wait,
203        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault import_batch needs this agent's signed identity: {e}"))?,
204    });
205    // The person's answer, then every read in turn.
206    post_waiting(cx, &format!("{base}/api/v1/vault/import_batch"), &body, "Vault import_batch", wait + BATCH_READ_SECS).await
207}
208
209pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
210    match name {
211        "Vault" => {
212            if cx.local_url.is_empty() || cx.auth_key.is_empty() {
213                anyhow::bail!("Vault: AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. Is this agent pane opened via AgentMux?");
214            }
215            let base = cx.local_url.trim_end_matches('/');
216            match arguments.get("action").and_then(Value::as_str).unwrap_or("") {
217                "list" => {
218                    // Which entries it sees depends on which Vaults the person made open to this agent.
219                    let body = json!({ "auth": crate::identity::sign_ui_automation_auth().ok() });
220                    let result = crate::srv_http::srv_post_json(cx.client, &format!("{base}/api/v1/vault/list"), cx.auth_key, &body, "Vault list").await?;
221                    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
222                }
223                "request" => {
224                    let s = |k: &str| arguments.get(k).and_then(Value::as_str).unwrap_or("").to_string();
225                    let wait = arguments.get("wait_secs").and_then(Value::as_u64).unwrap_or(REQUEST_WAIT_SECS).min(REQUEST_WAIT_MAX_SECS);
226                    let body = json!({
227                        "kind": s("kind"),
228                        "label": s("label"),
229                        "why": s("why"),
230                        "reason": arguments.get("reason").and_then(Value::as_str),
231                        "vault": arguments.get("vault").and_then(Value::as_str),
232                        "auth": crate::identity::sign_ui_automation_auth().ok(),
233                        "wait_secs": wait,
234                    });
235                    let url = format!("{base}/api/v1/vault/request");
236                    let resp = cx
237                        .client
238                        .post(&url)
239                        .header(AUTH_KEY_HEADER, cx.auth_key)
240                        .timeout(std::time::Duration::from_secs(wait + 60))
241                        .json(&body)
242                        .send()
243                        .await
244                        .map_err(|e| anyhow::anyhow!(crate::srv_http::describe_transport_error("Vault request", &url, &e)))?;
245                    let status = resp.status();
246                    let text = resp.text().await.unwrap_or_default();
247                    if !status.is_success() {
248                        anyhow::bail!(crate::srv_http::describe_http_error("Vault request", status, &text));
249                    }
250                    let result: Value = serde_json::from_str(&text).unwrap_or_default();
251                    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
252                }
253                "generate" => {
254                    let s = |k: &str| arguments.get(k).and_then(Value::as_str).unwrap_or("").to_string();
255                    let body = json!({
256                        "kind": s("kind"),
257                        "label": s("label"),
258                        "why": s("why"),
259                        "reason": arguments.get("reason").and_then(Value::as_str),
260                        "fields": arguments.get("fields").cloned().unwrap_or_else(|| json!({})),
261                        "rules": arguments.get("rules").cloned().unwrap_or_else(|| json!({})),
262                        "expires": arguments.get("expires").and_then(Value::as_str),
263                        "vault": arguments.get("vault").and_then(Value::as_str),
264                        "auth": crate::identity::sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("Vault generate needs this agent's signed identity: {e}"))?,
265                    });
266                    let result = crate::srv_http::srv_post_json(cx.client, &format!("{base}/api/v1/vault/generate"), cx.auth_key, &body, "Vault generate").await?;
267                    Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
268                }
269                "rotate" => rotate(arguments, cx, base).await,
270                "history" => history(arguments, cx, base).await,
271                "import" => import(arguments, cx, base).await,
272                "import_batch" => import_batch(arguments, cx, base).await,
273                "share" => share(arguments, cx, base).await,
274                "check" => check(arguments, cx, base).await,
275                action @ ("show" | "update" | "verify" | "health") => inspect(action, arguments, cx, base).await,
276                other => anyhow::bail!("Vault: unknown action {other:?}; use list, request, generate, share, rotate, history, import, import_batch, check, show, update, verify or health"),
277            }
278        }
279        _ => Err(not_in_family()),
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn the_schema_lists_every_action_and_every_kind_srv_knows() {
289        let schema: Value = serde_json::from_str(crate::tool_schemas::VAULT_TOOL).unwrap();
290        let actions = &schema["inputSchema"]["properties"]["action"]["enum"];
291        assert_eq!(actions, &json!(["list", "request", "generate", "share", "rotate", "history", "import", "import_batch", "check", "show", "update", "verify", "health"]));
292        // srv's catalog (backend/vault/kinds.rs) is the source; this list
293        // must name the same kinds.
294        let srv = include_str!("../../../srv-core/src/backend/vault/kinds.rs");
295        let mut srv_kinds: Vec<&str> = srv.split("name: \"").skip(1).filter_map(|rest| rest.split('"').next()).collect();
296        let mut ours: Vec<&str> = schema["inputSchema"]["properties"]["kind"]["enum"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
297        srv_kinds.sort_unstable();
298        ours.sort_unstable();
299        assert_eq!(ours, srv_kinds);
300    }
301}