trusty_code/mcp/spawn.rs
1//! Spawning one configured MCP server, in isolation (#5428).
2//!
3//! Why: a task run may have several connectors configured and exactly one of
4//! them broken — a typo'd command, a server that hangs on `initialize`, a
5//! binary that exits immediately. None of that may abort the run or the other
6//! servers, so every connection attempt is independently bounded and every
7//! failure is a value, never an error that propagates.
8//! What: [`connect`] spawns the child through the SHARED
9//! `trusty_common::stdio_mcp_client::StdioMcpClient` (never a bespoke
10//! transport), runs the handshake and `tools/list` under one
11//! [`HANDSHAKE_TIMEOUT`], and returns either the live client plus its tools or
12//! a one-line reason. A remote transport is refused here with the same shape,
13//! because "slice 1 does not speak HTTP" is a status, not a fault.
14//! Test: `super::tests::spawn_tests`, `mcp_loader_e2e::spawn_failure_isolates_the_healthy_server`.
15
16use std::collections::HashMap;
17use std::sync::Arc;
18use std::time::Duration;
19
20use tokio::sync::Mutex;
21use tokio::time::timeout;
22use trusty_common::stdio_mcp_client::{McpTool, StdioMcpClient};
23use trusty_mcp::config::{McpServerConfig, McpTransport};
24
25/// Wall-clock bound on one server's whole startup: handshake plus `tools/list`.
26///
27/// Why: `StdioMcpClient` bounds each REQUEST at 30s, which is far too long to
28/// wait at task startup and, with two requests, twice as long again. A server
29/// that cannot introduce itself in ten seconds is not one this run should
30/// block on.
31/// Test: `super::tests::spawn_tests::handshake_timeout_is_ten_seconds`.
32pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
33
34/// `clientInfo.name` advertised during the MCP handshake.
35const CLIENT_NAME: &str = "trusty-code";
36
37/// A live server: its client handle and the tools it advertised.
38///
39/// What: the client is already behind the `Arc<Mutex<_>>` every
40/// [`super::tool::McpBridgeTool`] for this server shares, because that shared
41/// handle is also what keeps the child process alive.
42pub struct Connected {
43 /// The shared, live client.
44 pub client: Arc<Mutex<StdioMcpClient>>,
45 /// Everything `tools/list` advertised.
46 pub tools: Vec<McpTool>,
47}
48
49/// Spawn one server and discover its tools, or say why not.
50///
51/// Why: the isolation boundary. Every failure mode — an unsupported transport,
52/// a command that does not exist, a handshake that times out, a server that
53/// will not list its tools — comes back as `Err(reason)` for the caller to
54/// record as a per-server status, so one bad entry costs exactly itself.
55/// What: stdio only. `env` is overlaid on the inherited environment through
56/// `spawn_with_env`; its VALUES are never logged, here or in the returned
57/// reason, because they are credentials.
58/// Test: `super::tests::spawn_tests::a_remote_transport_is_refused_with_a_reason`,
59/// `super::tests::spawn_tests::a_missing_binary_is_refused_with_a_reason`,
60/// `mcp_loader_e2e::spawn_failure_isolates_the_healthy_server`.
61pub async fn connect(server: &McpServerConfig) -> Result<Connected, String> {
62 connect_within(server, HANDSHAKE_TIMEOUT).await
63}
64
65/// [`connect`] with the startup bound supplied.
66///
67/// Why: a test that proves the per-server bound is real — that a hung server
68/// costs one timeout, not one per sibling — cannot afford to wait
69/// [`HANDSHAKE_TIMEOUT`] to do it. Injecting the bound keeps the proof to a
70/// second or two without weakening what production uses.
71/// Test: `mcp_loader_e2e::a_hung_server_does_not_serialise_its_siblings`.
72pub async fn connect_within(
73 server: &McpServerConfig,
74 budget: Duration,
75) -> Result<Connected, String> {
76 let McpTransport::Stdio { command, args, env } = &server.transport else {
77 return Err(super::REMOTE_UNSUPPORTED.to_string());
78 };
79
80 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
81 let envs: HashMap<String, String> = env.clone().into_iter().collect();
82 let mut client = StdioMcpClient::spawn_with_env(command, &arg_refs, CLIENT_NAME, &envs)
83 .await
84 .map_err(|e| format!("could not start {command:?}: {e}"))?;
85
86 let tools = match timeout(budget, handshake(&mut client)).await {
87 Ok(Ok(tools)) => tools,
88 Ok(Err(reason)) => return Err(reason),
89 // Dropping `client` here kills the child (`kill_on_drop` plus its own
90 // `Drop`), so a hung server does not outlive the attempt to use it.
91 Err(_) => {
92 return Err(format!(
93 "did not finish the MCP handshake within {}s",
94 budget.as_secs()
95 ));
96 }
97 };
98
99 tracing::info!(
100 server = %server.name,
101 command = %command,
102 tools = tools.len(),
103 "mcp: server connected",
104 );
105 Ok(Connected {
106 client: Arc::new(Mutex::new(client)),
107 tools,
108 })
109}
110
111/// `initialize` then `tools/list`, as one bounded unit.
112///
113/// Why: both are startup, and a server that handshakes but will not list its
114/// tools contributes nothing — so one timeout covers the pair rather than
115/// letting a slow server spend the budget twice.
116/// Test: covered through [`connect`].
117async fn handshake(client: &mut StdioMcpClient) -> Result<Vec<McpTool>, String> {
118 client
119 .initialize()
120 .await
121 .map_err(|e| format!("the MCP handshake failed: {e}"))?;
122 client
123 .list_tools()
124 .await
125 .map_err(|e| format!("tools/list failed: {e}"))
126}