Skip to main content

agentmux_srv_core/backend/
mcp_probe.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MCP server health/prerequisite probe
5//! (docs/specs/SPEC_MCP_INTEGRATION_PARITY_ABLETON_PILOT_2026_07_08.md §4.4).
6//!
7//! Opens a short-lived MCP client connection to a configured server — spawns
8//! the stdio process (or POSTs to the http url), performs the `initialize`
9//! handshake, then `tools/list` — and reports whether it's reachable at all.
10//!
11//! This is a protocol-level probe only. For a server like ableton-mcp, a
12//! successful probe means the MCP process itself started and speaks the
13//! protocol — NOT that the underlying app (Ableton Live) is running, since
14//! that dependency is only exercised when a tool is actually called. That
15//! gap is why the catalog's `prereqNote` (static remediation text, §4.6)
16//! exists alongside this dynamic check, not instead of it.
17//!
18//! Deliberately hand-rolled rather than pulling in an MCP client SDK crate
19//! (e.g. `rmcp`): `crates/mcp/src/main.rs` already hand-rolls the *server*
20//! side of this exact newline-delimited JSON-RPC 2.0 wire format, so a
21//! probe-only client follows the same house style instead of adding a new
22//! dependency for a handshake this small.
23
24#[cfg(windows)]
25use agentmux_common::win32::NoWindow;
26use std::process::Stdio;
27use std::time::Duration;
28
29use serde::Serialize;
30use serde_json::{json, Value};
31use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};
32use tokio::process::Command;
33use tokio::time::timeout;
34
35const PROBE_TIMEOUT: Duration = Duration::from_secs(8);
36const PROTOCOL_VERSION: &str = "2024-11-05";
37
38#[derive(Debug, Clone, Copy, Serialize, ts_rs::TS)]
39#[ts(export, export_to = "../../../frontend/types/rpc/")]
40#[serde(rename_all = "snake_case")]
41pub enum ProbeStatus {
42    Connected,
43    Unreachable,
44    HandshakeFailed,
45    InvalidConfig,
46}
47
48#[derive(Debug, Clone, Serialize, ts_rs::TS)]
49#[ts(export, export_to = "../../../frontend/types/rpc/")]
50pub struct ProbeResult {
51    pub status: ProbeStatus,
52    #[ts(type = "number | null")]
53    pub tool_count: Option<usize>,
54    pub server_name: Option<String>,
55    pub server_version: Option<String>,
56    pub error: Option<String>,
57}
58
59/// What a probe of a server that runs only in containers answers: nothing is started on this computer for it.
60pub const RUNS_IN_CONTAINER: &str = "runs in the container: this server is started in its agent's container, not on this computer, so it is not started here";
61
62impl ProbeResult {
63    /// The answer for a server that runs only in containers, in place of starting its command here.
64    pub fn runs_in_container() -> Self {
65        Self::unreachable(RUNS_IN_CONTAINER)
66    }
67
68    fn empty(status: ProbeStatus, error: Option<String>) -> Self {
69        Self { status, tool_count: None, server_name: None, server_version: None, error }
70    }
71    fn invalid(msg: impl Into<String>) -> Self {
72        Self::empty(ProbeStatus::InvalidConfig, Some(msg.into()))
73    }
74    fn unreachable(msg: impl Into<String>) -> Self {
75        Self::empty(ProbeStatus::Unreachable, Some(msg.into()))
76    }
77    fn handshake_failed(msg: impl Into<String>) -> Self {
78        Self::empty(ProbeStatus::HandshakeFailed, Some(msg.into()))
79    }
80    fn connected(server_name: Option<String>, server_version: Option<String>, tool_count: Option<usize>) -> Self {
81        Self { status: ProbeStatus::Connected, tool_count, server_name, server_version, error: None }
82    }
83}
84
85/// Probe a server given its `transport` (`"stdio"` | `"http"` | `"sse"` |
86/// any other free-text value from the pre-v11 field, treated as stdio for
87/// back-compat) and its raw `config` JSON blob — the exact object
88/// `agent_config::build_mcp_config_from_refs` merges into `.mcp.json`.
89pub async fn probe(transport: &str, config_json: &str) -> ProbeResult {
90    let config: Value = match serde_json::from_str(config_json) {
91        Ok(v) => v,
92        Err(e) => return ProbeResult::invalid(format!("config is not valid JSON: {e}")),
93    };
94
95    let is_http = matches!(transport, "http" | "sse" | "streamable-http") || config.get("url").is_some();
96
97    let outcome = if is_http {
98        timeout(PROBE_TIMEOUT, probe_http(&config)).await
99    } else {
100        timeout(PROBE_TIMEOUT, probe_stdio(&config)).await
101    };
102
103    match outcome {
104        Ok(result) => result,
105        Err(_) => ProbeResult::handshake_failed(format!("no response within {}s", PROBE_TIMEOUT.as_secs())),
106    }
107}
108
109fn initialize_request() -> Value {
110    json!({
111        "jsonrpc": "2.0",
112        "id": 1,
113        "method": "initialize",
114        "params": {
115            "protocolVersion": PROTOCOL_VERSION,
116            "capabilities": {},
117            "clientInfo": { "name": "agentmux-probe", "version": env!("CARGO_PKG_VERSION") },
118        },
119    })
120}
121
122fn tools_list_request() -> Value {
123    json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} })
124}
125
126// ── stdio ────────────────────────────────────────────────────────────────
127
128async fn probe_stdio(config: &Value) -> ProbeResult {
129    let command = match config.get("command").and_then(|v| v.as_str()) {
130        Some(c) if !c.is_empty() => c,
131        _ => return ProbeResult::invalid("stdio config missing a non-empty \"command\" string"),
132    };
133    let args: Vec<String> = config
134        .get("args")
135        .and_then(|v| v.as_array())
136        .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())
137        .unwrap_or_default();
138    let env: Vec<(String, String)> = config
139        .get("env")
140        .and_then(|v| v.as_object())
141        .map(|m| m.iter().filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))).collect())
142        .unwrap_or_default();
143
144    let mut cmd = Command::new(command);
145    // An arbitrary command from MCP server config — third-party by definition.
146    crate::backend::pane_env::sanitize_external_command(&mut cmd);
147    cmd.args(&args)
148        .envs(env)
149        .stdin(Stdio::piped())
150        .stdout(Stdio::piped())
151        .stderr(Stdio::null())
152        .kill_on_drop(true);
153    // Where the server starts, when the caller says (the launch self-test: the agent's workspace).
154    if let Some(dir) = config.get("cwd").and_then(Value::as_str).filter(|d| !d.is_empty()) {
155        cmd.current_dir(dir);
156    }
157    // CREATE_NO_WINDOW: console-flash suppression, see crates/common/src/cli.rs
158    #[cfg(windows)]
159    {
160        cmd.no_window();
161    }
162
163    let mut child = match cmd.spawn() {
164        Ok(c) => c,
165        Err(e) => return ProbeResult::unreachable(format!("failed to start \"{command}\": {e}")),
166    };
167
168    let mut stdin = match child.stdin.take() {
169        Some(s) => s,
170        None => return ProbeResult::unreachable("failed to open child stdin"),
171    };
172    let stdout = match child.stdout.take() {
173        Some(s) => s,
174        None => return ProbeResult::unreachable("failed to open child stdout"),
175    };
176    let mut reader = BufReader::new(stdout);
177
178    let result = run_stdio_handshake(&mut stdin, &mut reader).await;
179    let _ = child.start_kill(); // probe is ephemeral — never leave it running
180    result
181}
182
183async fn run_stdio_handshake<W, R>(stdin: &mut W, reader: &mut R) -> ProbeResult
184where
185    W: AsyncWrite + Unpin,
186    R: AsyncBufRead + Unpin,
187{
188    if let Err(e) = write_line(stdin, &initialize_request()).await {
189        return ProbeResult::unreachable(format!("failed to write initialize request: {e}"));
190    }
191    let init_resp = match read_json_line(reader).await {
192        Ok(Some(v)) => v,
193        Ok(None) => return ProbeResult::handshake_failed("process closed stdout before responding to initialize"),
194        Err(e) => return ProbeResult::handshake_failed(format!("failed to read initialize response: {e}")),
195    };
196    if let Some(err) = init_resp.get("error") {
197        return ProbeResult::handshake_failed(format!("server rejected initialize: {err}"));
198    }
199    let server_info = init_resp.pointer("/result/serverInfo").cloned().unwrap_or(Value::Null);
200    let server_name = server_info.get("name").and_then(|v| v.as_str()).map(str::to_string);
201    let server_version = server_info.get("version").and_then(|v| v.as_str()).map(str::to_string);
202
203    // notifications/initialized has no id and expects no response — best-effort.
204    let _ = write_line(stdin, &json!({"jsonrpc": "2.0", "method": "notifications/initialized"})).await;
205
206    if write_line(stdin, &tools_list_request()).await.is_err() {
207        // The handshake itself already succeeded even if tools/list couldn't be sent.
208        return ProbeResult::connected(server_name, server_version, None);
209    }
210    let tool_count = match read_json_line(reader).await {
211        Ok(Some(v)) => v.pointer("/result/tools").and_then(|t| t.as_array()).map(|a| a.len()),
212        _ => None,
213    };
214
215    ProbeResult::connected(server_name, server_version, tool_count)
216}
217
218async fn write_line<W: AsyncWrite + Unpin>(w: &mut W, v: &Value) -> std::io::Result<()> {
219    let s = serde_json::to_string(v).unwrap_or_default();
220    w.write_all(s.as_bytes()).await?;
221    w.write_all(b"\n").await?;
222    w.flush().await
223}
224
225/// Reads lines until one parses as JSON (skipping blank lines or stray
226/// non-JSON output, e.g. a server printing a startup banner to stdout),
227/// or the stream closes.
228async fn read_json_line<R: AsyncBufRead + Unpin>(r: &mut R) -> std::io::Result<Option<Value>> {
229    let mut line = String::new();
230    loop {
231        line.clear();
232        let n = r.read_line(&mut line).await?;
233        if n == 0 {
234            return Ok(None);
235        }
236        let trimmed = line.trim();
237        if trimmed.is_empty() {
238            continue;
239        }
240        if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
241            return Ok(Some(v));
242        }
243    }
244}
245
246// ── http (Streamable HTTP transport) ────────────────────────────────────
247
248async fn probe_http(config: &Value) -> ProbeResult {
249    let url = match config.get("url").and_then(|v| v.as_str()) {
250        Some(u) if !u.is_empty() => u,
251        _ => return ProbeResult::invalid("http config missing a non-empty \"url\" string"),
252    };
253
254    let mut headers = reqwest::header::HeaderMap::new();
255    if let Some(h) = config.get("headers").and_then(|v| v.as_object()) {
256        for (k, v) in h {
257            let (Ok(name), Some(val)) = (reqwest::header::HeaderName::from_bytes(k.as_bytes()), v.as_str()) else {
258                continue;
259            };
260            if let Ok(hv) = reqwest::header::HeaderValue::from_str(val) {
261                headers.insert(name, hv);
262            }
263        }
264    }
265    let client = match crate::http_client::builder().default_headers(headers).timeout(PROBE_TIMEOUT).build() {
266        Ok(c) => c,
267        Err(e) => return ProbeResult::invalid(format!("failed to build http client: {e}")),
268    };
269
270    let init_resp = match post_jsonrpc(&client, url, &initialize_request()).await {
271        Ok(v) => v,
272        Err(e) => return e,
273    };
274    if let Some(err) = init_resp.get("error") {
275        return ProbeResult::handshake_failed(format!("server rejected initialize: {err}"));
276    }
277    let server_info = init_resp.pointer("/result/serverInfo").cloned().unwrap_or(Value::Null);
278    let server_name = server_info.get("name").and_then(|v| v.as_str()).map(str::to_string);
279    let server_version = server_info.get("version").and_then(|v| v.as_str()).map(str::to_string);
280
281    let tool_count = match post_jsonrpc(&client, url, &tools_list_request()).await {
282        Ok(v) => v.pointer("/result/tools").and_then(|t| t.as_array()).map(|a| a.len()),
283        Err(_) => None, // reachability + handshake already proven above
284    };
285
286    ProbeResult::connected(server_name, server_version, tool_count)
287}
288
289/// POSTs one JSON-RPC request and returns the first JSON object in the
290/// response body — handling both a plain `application/json` body and a
291/// Streamable HTTP `text/event-stream` framing (`event: message\ndata:
292/// {...}\n\n`), since a probe only needs the first frame either way.
293async fn post_jsonrpc(client: &reqwest::Client, url: &str, req: &Value) -> Result<Value, ProbeResult> {
294    let resp = client
295        .post(url)
296        .header("Content-Type", "application/json")
297        .header("Accept", "application/json, text/event-stream")
298        .json(req)
299        .send()
300        .await
301        .map_err(|e| ProbeResult::unreachable(format!("request failed: {e}")))?;
302
303    if !resp.status().is_success() {
304        return Err(ProbeResult::handshake_failed(format!("server returned HTTP {}", resp.status())));
305    }
306    let body = resp.text().await.map_err(|e| ProbeResult::handshake_failed(format!("failed to read response body: {e}")))?;
307    let json_line = body.lines().find(|l| l.trim_start().starts_with('{')).unwrap_or(body.trim());
308    serde_json::from_str(json_line).map_err(|e| ProbeResult::handshake_failed(format!("non-JSON response: {e}")))
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[tokio::test]
316    async fn invalid_json_config_is_reported_as_invalid_config() {
317        let result = probe("stdio", "{not json").await;
318        assert!(matches!(result.status, ProbeStatus::InvalidConfig));
319        assert!(result.error.unwrap().contains("not valid JSON"));
320    }
321
322    #[tokio::test]
323    async fn stdio_config_missing_command_is_invalid() {
324        let result = probe("stdio", "{}").await;
325        assert!(matches!(result.status, ProbeStatus::InvalidConfig));
326        assert!(result.error.unwrap().contains("command"));
327    }
328
329    #[tokio::test]
330    async fn stdio_config_with_unresolvable_binary_is_unreachable() {
331        let config = json!({ "command": "definitely-not-a-real-agentmux-probe-binary-xyz" }).to_string();
332        let result = probe("stdio", &config).await;
333        assert!(matches!(result.status, ProbeStatus::Unreachable), "expected Unreachable, got {:?}", result.status);
334    }
335
336    #[tokio::test]
337    async fn http_config_missing_url_is_invalid() {
338        let result = probe("http", "{}").await;
339        assert!(matches!(result.status, ProbeStatus::InvalidConfig));
340        assert!(result.error.unwrap().contains("url"));
341    }
342
343    #[tokio::test]
344    async fn http_transport_is_inferred_from_url_field_even_without_explicit_kind() {
345        // transport is still the free-text pre-v11 field; a config that
346        // carries "url" should route to the http probe regardless of what
347        // (if anything) the transport string says.
348        let config = json!({ "url": "http://127.0.0.1:1/nonexistent" }).to_string();
349        let result = probe("stdio", &config).await;
350        assert!(matches!(result.status, ProbeStatus::Unreachable), "expected Unreachable, got {:?}", result.status);
351    }
352}