Skip to main content

agentmux_mcp/tools/
shell.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pipe shells (background jobs) in the agent pane, and the connections a
5//! terminal can run on. Not advertised: `Terminal` (terminal.rs) calls these
6//! by their old names for its `run` with `background`, `close`, `type` to a
7//! job, and `connections`.
8
9use super::*;
10
11pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
12    match name {
13        "Shell" => run_shell(arguments, cx).await,
14        "ShellStop" => run_shell_stop(arguments, cx).await,
15        "ShellInput" => run_shell_input(arguments, cx).await,
16        "ShellStatus" => run_shell_status(arguments, cx).await,
17        "ConnList" => run_conn_list(arguments, cx).await,
18        _ => Err(not_in_family()),
19    }
20}
21
22async fn run_shell(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
23    Ok(create(arguments, cx).await?.shell_id)
24}
25
26/// Starts a job: srv asks the person first for any Vault secrets it names.
27pub(super) async fn create(arguments: &Value, cx: &ToolCtx<'_>) -> Result<ShellCreateResponse> {
28    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
29    let cmd = arguments
30        .get("cmd")
31        .and_then(|v| v.as_str())
32        .ok_or_else(|| anyhow::anyhow!("missing required parameter: cmd"))?;
33
34    if local_url.is_empty() || auth_key.is_empty() {
35        anyhow::bail!(
36            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
37             Is this agent pane opened via AgentMux?"
38        );
39    }
40    if block_id.is_empty() {
41        anyhow::bail!(
42            "neither AGENTMUX_AGENT_BUS_ID nor AGENTMUX_BLOCKID is set \
43             — cannot associate the shell with a conversation pane. \
44             Is this agent pane opened via AgentMux?"
45        );
46    }
47
48    let title = arguments
49        .get("title")
50        .and_then(|v| v.as_str())
51        .unwrap_or(cmd);
52    let cwd = arguments.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
53    let env = arguments
54        .get("env")
55        .and_then(|v| serde_json::from_value(v.clone()).ok());
56
57    let capture_stdin = arguments.get("capture_stdin").and_then(|v| v.as_bool());
58    let connection = arguments.get("connection").and_then(|v| v.as_str()).map(str::to_string);
59    let req = ShellCreateRequest {
60        agent_block_id: block_id.to_string(),
61        cmd: cmd.to_string(),
62        title: Some(title.to_string()),
63        cwd,
64        env,
65        capture_stdin,
66        connection,
67        // Proves which agent is asking; srv requires it for SSH. An
68        // agent without a key still runs locally and in WSL.
69        auth: sign_ui_automation_auth().ok(),
70        secrets: match arguments.get("secrets").filter(|v| !v.is_null()) {
71            Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| anyhow::anyhow!("secrets must be an object of environment variable names to Vault entry ids, e.g. {{\"STRIPE_API_KEY\": \"api-key-stripe\"}}"))?),
72            None => None,
73        },
74        stdin_secret: arguments.get("stdin_secret").and_then(|v| v.as_str()).map(str::to_string),
75        secret_files: match arguments.get("secret_files").filter(|v| !v.is_null()) {
76            Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| anyhow::anyhow!("secret_files must be an object of environment variable names to Vault entry ids, e.g. {{\"GOOGLE_APPLICATION_CREDENTIALS\": \"api-key-gcp\"}}"))?),
77            None => None,
78        },
79        reason: arguments.get("reason").and_then(|v| v.as_str()).map(str::to_string),
80        capture: match arguments.get("capture").filter(|v| !v.is_null()) {
81            Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| anyhow::anyhow!("capture is a list of {{\"as\": {{\"kind\", \"label\"}} or {{\"id\"}}, \"from\": {{\"stdout\": \"all\"}} or {{\"json\": \"$.path\"}} or {{\"regex\": \"...(group)...\"}} or {{\"line\": n}}}}: {e}"))?),
82            None => None,
83        },
84    };
85
86    cx.post_as_within("/api/v1/shell/create", &req, "shell/create", crate::srv_http::SHELL_CREATE_TIMEOUT).await
87}
88
89async fn run_shell_stop(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
90    let ToolCtx { local_url, auth_key, .. } = *cx;
91    let shell_id = arguments
92        .get("shell_id")
93        .and_then(|v| v.as_str())
94        .ok_or_else(|| anyhow::anyhow!("missing required parameter: shell_id"))?;
95
96    if local_url.is_empty() || auth_key.is_empty() {
97        anyhow::bail!(
98            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
99             Is this agent pane opened via AgentMux?"
100        );
101    }
102
103    let result: ShellStopResponse = cx.post_as("/api/v1/shell/stop", &ShellStopRequest { shell_id: shell_id.to_string() }, "shell/stop").await?;
104    Ok(if result.stopped {
105        format!("stopped shell {shell_id}")
106    } else {
107        format!("shell {shell_id} was not running (unknown or already exited)")
108    })
109}
110
111async fn run_shell_input(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
112    let ToolCtx { local_url, auth_key, .. } = *cx;
113    let shell_id = arguments
114        .get("shell_id")
115        .and_then(|v| v.as_str())
116        .ok_or_else(|| anyhow::anyhow!("missing required parameter: shell_id"))?;
117    let text = arguments
118        .get("text")
119        .and_then(|v| v.as_str())
120        .ok_or_else(|| anyhow::anyhow!("missing required parameter: text"))?;
121
122    if local_url.is_empty() || auth_key.is_empty() {
123        anyhow::bail!(
124            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
125             Is this agent pane opened via AgentMux?"
126        );
127    }
128
129    let result: ShellInputResponse = cx.post_as("/api/v1/shell/input", &ShellInputRequest { shell_id: shell_id.to_string(), text: text.to_string() }, "shell/input").await?;
130    Ok(if result.written {
131        format!("wrote to shell {shell_id}")
132    } else {
133        match result.reason {
134            Some(ShellInputFailure::StdinNotCaptured) => format!(
135                "shell {shell_id} is running but was started without capture_stdin=true — \
136                 its stdin is /dev/null. Recreate the shell with Shell(..., capture_stdin=true) \
137                 to send input."
138            ),
139            Some(ShellInputFailure::WriteFailed) => format!(
140                "shell {shell_id} closed its stdin — input discarded"
141            ),
142            Some(ShellInputFailure::NotRunning) | None => format!(
143                "shell {shell_id} is not running — input discarded"
144            ),
145        }
146    })
147}
148
149async fn run_shell_status(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
150    let ToolCtx { local_url, auth_key, .. } = *cx;
151    let shell_id = arguments
152        .get("shell_id")
153        .and_then(|v| v.as_str())
154        .ok_or_else(|| anyhow::anyhow!("missing required parameter: shell_id"))?;
155
156    if local_url.is_empty() || auth_key.is_empty() {
157        anyhow::bail!(
158            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
159             Is this agent pane opened via AgentMux?"
160        );
161    }
162
163    let result: ShellStatusResponse = cx.post_as("/api/v1/shell/status", &ShellStatusRequest { shell_id: shell_id.to_string() }, "shell/status").await?;
164    Ok(if result.running {
165        format!("shell {shell_id} is running ({} lines so far)", result.line_count)
166    } else {
167        let code = result.exit_code.map(|c| c.to_string()).unwrap_or_else(|| "unknown".to_string());
168        format!("shell {shell_id} has exited — exit_code: {code}, {} lines total", result.line_count)
169    })
170}
171
172async fn run_conn_list(_arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
173    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
174    crate::srv_http::require_agent_env(local_url, auth_key, block_id)?;
175    let url = format!("{}/api/v1/conn/list", local_url.trim_end_matches('/'));
176    let result = crate::srv_http::srv_get_json(client, &url, auth_key, &[], "Terminal connections").await?;
177    Ok(serde_json::to_string_pretty(&result)?)
178}
179
180#[cfg(test)]
181mod call_tests;