Skip to main content

trusty_code/mcp/
mod.rs

1//! Loading and running the MCP servers a `tcode` task run is configured with
2//! (#5428, slice 1).
3//!
4//! Why: `tcode` could reach exactly one MCP server before this — `search_code`,
5//! which hard-codes `trusty-search` (`crate::tools::trusty_search`). Every
6//! other connector the operator configures in the file `trusty-agents` already
7//! reads (`~/.trusty-tools/mcp/servers.toml`, ADR-0060 decision 2) was
8//! invisible here. This module is the loader that closes that gap: shared
9//! config in, registered tools out.
10//!
11//! What: [`McpToolSet::load`](crate::mcp::McpToolSet::load) is the whole
12//! lifecycle and runs ONCE per task run, before the agent loop — resolve the
13//! two tiers ([`config`](crate::mcp::config)), gate the untrusted project tier
14//! ([`trust`](crate::mcp::trust)), spawn each enabled stdio server in isolation
15//! ([`spawn`](crate::mcp::spawn)), and wrap each advertised tool as a
16//! `ToolExecutor` ([`tool`](crate::mcp::tool)).
17//! [`register_configured_tools`](crate::mcp::register_configured_tools) is the
18//! cheap per-registry half, and is what the two registry-building sites call.
19//! The set is shared across every registry a run builds, so the servers are
20//! spawned once and the client handles stay alive exactly as long as a tool
21//! that can call them.
22//!
23//! Every link above is spelled `crate::mcp::…` rather than module-relative:
24//! `pub mod mcp;` in `lib.rs` carries its own `///` block, and rustdoc merges
25//! that with this `//!` one and resolves the whole thing in the CRATE ROOT's
26//! scope, where a bare `config` or `trust` names nothing (#5428).
27//!
28//! What this slice does NOT do: no catalog over the API or CLI (slice 2), and
29//! no remote transports — an `http` or `sse` entry is recognised and reported
30//! as not usable, never silently dropped.
31//!
32//! Test: `tests` — the unit modules, which are `#[cfg(test)]` and so cannot be
33//! a link target in rustdoc's public pass; `crates/trusty-code/tests/mcp_loader_e2e.rs`
34//! — spawn, register and dispatch against a real stdio MCP server.
35
36pub mod config;
37pub mod spawn;
38pub mod tool;
39pub mod trust;
40
41#[cfg(test)]
42mod tests;
43
44use std::path::Path;
45use std::sync::Arc;
46
47use crate::tools::registry::ToolRegistry;
48use crate::tools::traits::ToolExecutor;
49
50pub use config::{McpIssue, McpTier, ProjectOverrides, ResolvedMcp, ServerStatus};
51pub use tool::{McpBridgeTool, composed_name};
52
53/// Why a recognised but unimplemented transport is not connected.
54///
55/// Why: one string, so the config-time grading and the spawn-time refusal
56/// cannot describe the same condition two different ways.
57/// Test: `tests::config_tests::a_remote_transport_is_reported_not_usable`.
58pub const REMOTE_UNSUPPORTED: &str = "remote transports not supported in this slice";
59
60/// What a run should say about its MCP configuration.
61///
62/// Why: the Fail-Open Check — a caller must be able to tell "no servers are
63/// configured" from "the configuration is broken", and that difference is only
64/// legible if the findings travel with the result. `statuses` is the
65/// per-server answer; `issues` is everything wrong with a FILE or refused by
66/// the trust gate.
67/// What: `tools` names every tool actually registered, in registration order.
68/// Test: `tests::set_tests::a_malformed_global_file_reaches_the_diagnostics`.
69#[derive(Debug, Clone, Default)]
70pub struct McpDiagnostics {
71    /// One entry per configured server, in resolver order.
72    pub statuses: Vec<ServerStatus>,
73    /// Everything wrong with either tier's file, or refused by the trust gate.
74    pub issues: Vec<McpIssue>,
75    /// The composed names of every tool registered.
76    pub tools: Vec<String>,
77}
78
79impl McpDiagnostics {
80    /// How many configured servers this run is actually connected to.
81    ///
82    /// Test: `tests::set_tests::an_unconfigured_run_registers_nothing_and_reports_nothing`.
83    pub fn usable_count(&self) -> usize {
84        self.statuses.iter().filter(|s| s.usable).count()
85    }
86
87    /// Emit the run's MCP state: `info` for what worked, `warn` for what did not.
88    ///
89    /// Why: the two registry-building sites should not each decide how to
90    /// narrate this, and a broken config must reach stderr whether or not the
91    /// caller renders the struct.
92    /// Test: `tests::set_tests::a_malformed_global_file_reaches_the_diagnostics`
93    /// covers the data; the log calls themselves carry no branching logic.
94    pub fn log(&self) {
95        tracing::info!(
96            servers = self.statuses.len(),
97            usable = self.usable_count(),
98            tools = self.tools.len(),
99            "mcp: configured servers loaded",
100        );
101        for status in self.statuses.iter().filter(|s| !s.usable) {
102            tracing::warn!(
103                server = %status.name,
104                tier = status.tier.as_str(),
105                detail = status.detail.as_deref().unwrap_or(""),
106                "mcp: server not usable",
107            );
108        }
109        for issue in &self.issues {
110            tracing::warn!(
111                tier = issue.tier.as_str(),
112                path = %issue.path.display(),
113                detail = %issue.detail,
114                remedy = %issue.remedy,
115                "mcp: configuration problem",
116            );
117        }
118    }
119}
120
121/// Every MCP tool a task run can dispatch, plus why any server is missing.
122///
123/// Why: the lifecycle is per-RUN, not per-registry. A `RegistryFactory` builds
124/// a fresh registry for each delegation, and spawning the operator's servers
125/// again on each of those would multiply child processes and startup latency
126/// for no gain. Loading once and sharing `Arc`s keeps the spawn off every hot
127/// path, and — because each tool holds its server's client handle — keeps the
128/// children alive for exactly as long as something can call them.
129/// What: construct with [`McpToolSet::load`], then hand it to
130/// [`register_configured_tools`] at each registry site.
131/// Test: `tests::set_tests`, `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry`.
132#[derive(Default)]
133pub struct McpToolSet {
134    tools: Vec<Arc<dyn ToolExecutor>>,
135    diagnostics: McpDiagnostics,
136}
137
138impl McpToolSet {
139    /// Resolve, spawn and discover, against the live global config path.
140    ///
141    /// Why: the production entry point. A home directory that does not resolve
142    /// is a configuration problem, not a fatal one, so it becomes an empty set
143    /// rather than an error a task run has to handle.
144    /// What: delegates to [`McpToolSet::load_at`] with
145    /// `trusty_mcp::config::default_path()`. Under a cargo test harness it
146    /// loads NOTHING: this is the one path that reads the OPERATOR's real
147    /// `servers.toml`, and honouring it from a test run would spawn their
148    /// actual daemons as a side effect of `cargo test` — the production-state
149    /// mutation `trusty_common::running_under_test_harness` exists to refuse
150    /// (#4255). A test that wants a real server injects its own config through
151    /// [`McpToolSet::load_at`].
152    /// Test: `tests::set_tests::the_live_path_loads_nothing_under_a_test_harness`;
153    /// `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry` covers
154    /// the real transport through `load_at`.
155    pub async fn load(project_root: &Path) -> Self {
156        if trusty_common::running_under_test_harness() {
157            tracing::debug!("mcp: test harness detected; not reading the operator's server file");
158            return Self::default();
159        }
160        match trusty_mcp::config::default_path() {
161            Ok(path) => Self::load_at(&path, project_root).await,
162            Err(e) => {
163                tracing::warn!(error = %e, "mcp: no shared MCP server file path resolves; no servers configured");
164                Self::default()
165            }
166        }
167    }
168
169    /// [`McpToolSet::load`] with both tier locations injected.
170    ///
171    /// Why: every test points this at a tempdir, so no test run can read — or
172    /// spawn anything named by — the developer's real configuration.
173    /// What: resolves both tiers, then attempts each usable server
174    /// INDEPENDENTLY. A server that fails to connect downgrades its own status
175    /// and contributes no tools; it never affects another server or the run. A
176    /// tool whose composed name is already taken within this set, or whose
177    /// schema is over the cap, is skipped with an issue rather than silently
178    /// shadowing or bloating the surface.
179    /// Test: `tests::set_tests::a_failed_server_does_not_stop_the_others`,
180    /// `mcp_loader_e2e::spawn_failure_isolates_the_healthy_server`.
181    pub async fn load_at(global_path: &Path, project_root: &Path) -> Self {
182        Self::load_within(global_path, project_root, spawn::HANDSHAKE_TIMEOUT).await
183    }
184
185    /// [`McpToolSet::load_at`] with the per-server startup bound supplied.
186    ///
187    /// Why: `budget` is per SERVER, and the servers are connected CONCURRENTLY
188    /// — sequentially, N wedged connectors would cost N × the bound at task
189    /// startup, so the worst case grew with the operator's config. Injecting
190    /// the bound is what lets a test prove that in a second or two instead of
191    /// waiting out two real timeouts.
192    /// What: `futures_util::future::join_all` preserves its input's order, so
193    /// the results are applied in CONFIG order and `statuses`/`tools` stay
194    /// deterministic regardless of which server answered first.
195    /// Test: `mcp_loader_e2e::a_hung_server_does_not_serialise_its_siblings`,
196    /// `tests::set_tests::a_failed_server_does_not_stop_the_others`.
197    pub async fn load_within(
198        global_path: &Path,
199        project_root: &Path,
200        budget: std::time::Duration,
201    ) -> Self {
202        let resolved = config::resolve_at(global_path, project_root);
203        let mut set = Self {
204            tools: Vec::new(),
205            diagnostics: McpDiagnostics {
206                statuses: resolved.statuses,
207                issues: resolved.issues,
208                tools: Vec::new(),
209            },
210        };
211
212        let attempts: Vec<(usize, &trusty_mcp::config::McpServerConfig)> = resolved
213            .servers
214            .iter()
215            .enumerate()
216            .filter(|(index, _)| set.diagnostics.statuses[*index].usable)
217            .collect();
218        let outcomes = futures_util::future::join_all(
219            attempts
220                .iter()
221                .map(|(_, server)| spawn::connect_within(server, budget)),
222        )
223        .await;
224
225        for ((index, server), outcome) in attempts.into_iter().zip(outcomes) {
226            match outcome {
227                Ok(connected) => set.absorb(&server.name, connected),
228                Err(reason) => {
229                    tracing::warn!(
230                        server = %server.name,
231                        reason = %reason,
232                        "mcp: server unavailable; the rest of this run is unaffected",
233                    );
234                    let status = &mut set.diagnostics.statuses[index];
235                    status.usable = false;
236                    status.detail = Some(reason);
237                }
238            }
239        }
240        set
241    }
242
243    /// Turn one connected server's advertised tools into registrable executors.
244    ///
245    /// What: skips, with an issue, a tool whose composed name this set already
246    /// carries and a tool whose schema [`tool::build_schema`] refused.
247    /// Test: `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry`.
248    fn absorb(&mut self, server: &str, connected: spawn::Connected) {
249        for advertised in &connected.tools {
250            let name = composed_name(server, &advertised.name);
251            if self.diagnostics.tools.contains(&name) {
252                self.diagnostics.issues.push(McpIssue {
253                    tier: McpTier::Global,
254                    path: std::path::PathBuf::from(server),
255                    detail: format!("the tool {name:?} is advertised more than once"),
256                    remedy: "Only the first was registered. Check the server for a duplicate \
257                             tool name."
258                        .to_string(),
259                });
260                continue;
261            }
262            match McpBridgeTool::new(server, advertised, Arc::clone(&connected.client)) {
263                Ok(bridge) => {
264                    self.diagnostics.tools.push(name);
265                    self.tools.push(Arc::new(bridge));
266                }
267                Err(reason) => self.diagnostics.issues.push(McpIssue {
268                    tier: McpTier::Global,
269                    path: std::path::PathBuf::from(server),
270                    detail: format!("the tool {name:?} was not registered because {reason}"),
271                    remedy: "Ask the server's author to shrink the advertised inputSchema."
272                        .to_string(),
273                }),
274            }
275        }
276    }
277
278    /// What this run should say about its MCP configuration.
279    pub fn diagnostics(&self) -> &McpDiagnostics {
280        &self.diagnostics
281    }
282
283    /// Whether any tool was loaded at all.
284    pub fn is_empty(&self) -> bool {
285        self.tools.is_empty()
286    }
287
288    /// The composed name of every tool this set carries, for assertions.
289    ///
290    /// Test: `tests::set_tests::a_failed_server_does_not_stop_the_others`.
291    #[cfg(test)]
292    pub(crate) fn tool_names(&self) -> Vec<&str> {
293        self.tools.iter().map(|t| t.name()).collect()
294    }
295}
296
297/// Register every loaded MCP tool into `registry`.
298///
299/// Why: the single call the two registry-building sites make, so neither has
300/// to know anything about MCP beyond "hand it the set". Kept separate from
301/// [`McpToolSet::load`] because a registry is built per delegation while the
302/// servers are spawned per run.
303/// What: returns the set's diagnostics plus any collision found HERE — a
304/// composed name already registered is skipped rather than overwriting a tool
305/// the run depends on. `ToolRegistry::register` would otherwise replace it
306/// silently outside a debug build.
307/// Test: `mcp_loader_e2e::a_name_already_in_the_registry_is_skipped`,
308/// `mcp_loader_e2e::end_to_end_dispatch_echoes_through_the_registry`.
309pub fn register_configured_tools(registry: &mut ToolRegistry, set: &McpToolSet) -> McpDiagnostics {
310    let mut diagnostics = set.diagnostics.clone();
311    for tool in &set.tools {
312        let name = tool.name().to_string();
313        if registry.contains(&name) {
314            tracing::warn!(tool = %name, "mcp: a tool of this name is already registered; skipping");
315            diagnostics.tools.retain(|t| t != &name);
316            diagnostics.issues.push(McpIssue {
317                tier: McpTier::Global,
318                path: std::path::PathBuf::from(&name),
319                detail: format!("the tool {name:?} collides with one already registered"),
320                remedy: "Rename the server in ~/.trusty-tools/mcp/servers.toml so its tools \
321                         compose to a free name."
322                    .to_string(),
323            });
324            continue;
325        }
326        registry.register(Arc::clone(tool));
327    }
328    diagnostics
329}