Skip to main content

trusty_code/mcp/
config.rs

1//! The two configuration tiers a `tcode` run reads MCP servers from (#5428).
2//!
3//! Why: ADR-0060 decision 2 puts ONE list of configured MCP servers at
4//! `~/.trusty-tools/mcp/servers.toml`, owned by `trusty-mcp` and read by both
5//! harnesses. `trusty-agents` already reads it (`crate::mcp::shared` there);
6//! this is `trusty-code`'s half. The second tier is the project, because a
7//! repo is where "this codebase needs that connector" is actually known — but
8//! a repo is also UNTRUSTED content, so the project tier passes through
9//! [`super::trust`] before it reaches the resolver.
10//!
11//! What: [`resolve_at`] loads the global file, reads
12//! `<project>/.trusty-code/mcp.toml` through [`crate::paths::resolve_project_entry`]
13//! (which brings the `.claude/` compatibility lookup with it), runs the trust
14//! gate, and hands both to `trusty_mcp::config::resolve` — the ONE resolver
15//! (ADR-0060 decision 5). Nothing here does precedence arithmetic of its own.
16//!
17//! Failure is fail-open-and-visible, never a silent empty catalog: a file that
18//! exists and does not parse yields zero servers from that tier PLUS an
19//! [`McpIssue`] and a `tracing::warn!` naming the path. See
20//! `super::tests::config_tests::a_malformed_global_file_yields_zero_servers_and_an_issue`
21//! — a plain code span, not a link: the test modules are `#[cfg(test)]` and do
22//! not exist in rustdoc's public pass.
23//!
24//! Test: `super::tests::config_tests` — the whole module.
25
26use std::path::{Path, PathBuf};
27
28use serde::Deserialize;
29use trusty_mcp::config::{McpConfigFile, McpServerConfig, McpTransport};
30
31use crate::paths::{EntryKind, resolve_project_entry};
32
33/// The project-tier file name, resolved beneath the winning config root.
34///
35/// Why: named once so `.trusty-code/mcp.toml` and its `.claude/mcp.toml`
36/// compatibility twin cannot drift apart — [`resolve_project_entry`] walks
37/// `crate::paths::SEARCH_ROOTS` for both.
38/// Test: `super::tests::config_tests::a_project_disable_hides_a_global_server`.
39pub const PROJECT_MCP_FILE: &str = "mcp.toml";
40
41/// Which configuration tier a server or a finding came from.
42///
43/// Test: `super::tests::config_tests::a_project_set_with_a_new_command_is_refused`.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum McpTier {
46    /// `~/.trusty-tools/mcp/servers.toml`, the file shared with `trusty-agents`.
47    Global,
48    /// `<project>/.trusty-code/mcp.toml` (or its `.claude/` compatibility twin).
49    Project,
50}
51
52impl McpTier {
53    /// A stable lowercase token for logs and diagnostics.
54    ///
55    /// Test: `super::tests::config_tests::tier_tokens_are_stable`.
56    pub fn as_str(self) -> &'static str {
57        match self {
58            Self::Global => "global",
59            Self::Project => "project",
60        }
61    }
62}
63
64/// One thing wrong with an MCP configuration file, or one entry refused.
65///
66/// Why: the Fail-Open Check this slice is gated on — a broken file must never
67/// be indistinguishable from "no servers configured". A log line alone is not
68/// enough, because the caller has to be able to RENDER the difference; so the
69/// finding is data, with the remedy attached.
70/// What: which tier, which file, what is wrong, and what would fix it — the
71/// same reason-plus-remedy shape `trusty_agents::mcp::shared::McpIssue` uses.
72/// Test: `super::tests::config_tests::a_malformed_global_file_yields_zero_servers_and_an_issue`.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct McpIssue {
75    /// Which configuration tier the finding belongs to.
76    pub tier: McpTier,
77    /// The file the finding is about.
78    pub path: PathBuf,
79    /// What is wrong, phrased for a person.
80    pub detail: String,
81    /// What would fix it.
82    pub remedy: String,
83}
84
85/// Whether one resolved server can actually be connected to.
86///
87/// Why: "configured" and "usable" are different facts. A server whose command
88/// does not exist, or whose transport this slice cannot speak, must render as
89/// present-and-broken with the reason — never as absent, and never as live.
90/// What: `enabled` is the config flag; `usable` is the runtime answer, which
91/// [`super::spawn`] downgrades after a failed handshake. `detail` is `None`
92/// only when `usable`.
93/// Test: `super::tests::config_tests::a_disabled_server_is_reported_not_dropped`,
94/// `mcp_loader_e2e::spawn_failure_isolates_the_healthy_server`.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct ServerStatus {
97    /// The server's name.
98    pub name: String,
99    /// Which tier supplied the entry that won.
100    pub tier: McpTier,
101    /// The resolved `enabled` flag.
102    pub enabled: bool,
103    /// Whether the runtime should connect to it.
104    pub usable: bool,
105    /// Why not, when it is not usable.
106    pub detail: Option<String>,
107}
108
109/// The project tier's override table, as written in `mcp.toml`.
110///
111/// Why: two lists rather than one tagged enum list, for the reason
112/// `trusty_agents::assistants::mcp::McpOverrides` gives — `disabled = ["x"]`
113/// is one line a person will actually hand-write, and the tagged
114/// array-of-tables spelling is four.
115/// What: `servers` are candidate `Set` overrides (each subject to the trust
116/// gate in [`super::trust`]); `disabled` names global servers this project
117/// does not connect to. The file's ROOT is this table — the file is already
118/// named `mcp.toml`, so a wrapping `[mcp]` table would be redundant.
119/// `deny_unknown_fields` is deliberate: a mistyped key that silently dropped a
120/// `disabled` entry would be exactly the invisible failure this module exists
121/// to prevent, so it surfaces as an [`McpIssue`] instead.
122/// Test: `super::tests::config_tests::a_project_disable_hides_a_global_server`,
123/// `super::tests::config_tests::a_misspelled_key_is_refused_with_an_issue`.
124#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
125#[serde(deny_unknown_fields)]
126pub struct ProjectOverrides {
127    /// Servers this project asks for, by name, subject to the trust gate.
128    #[serde(default)]
129    pub servers: Vec<McpServerConfig>,
130    /// Global servers this project does not connect to.
131    // `disable` is accepted as an alias so the singular spelling a person
132    // reaches for first is not silently swallowed by `deny_unknown_fields`.
133    #[serde(default, alias = "disable")]
134    pub disabled: Vec<String>,
135}
136
137impl ProjectOverrides {
138    /// Whether this project overrides nothing.
139    pub fn is_empty(&self) -> bool {
140        self.servers.is_empty() && self.disabled.is_empty()
141    }
142}
143
144/// Both tiers, layered, with everything that went wrong on the way.
145///
146/// Why: the caller renders the difference between what is configured and what
147/// is live, not just the answer — so all three views travel together.
148/// What: `global` is the shared file before overrides, `overrides` the
149/// project's table as written, `servers` the effective list in
150/// `trusty_mcp::config::resolve`'s order, and `statuses` one entry per
151/// effective server in the same order.
152/// Test: `super::tests::config_tests` — the whole module.
153#[derive(Debug, Clone, Default)]
154pub struct ResolvedMcp {
155    /// The global tier, before overrides.
156    pub global: Vec<McpServerConfig>,
157    /// The project's own table, as parsed.
158    pub overrides: ProjectOverrides,
159    /// The effective set, in resolver order.
160    pub servers: Vec<McpServerConfig>,
161    /// One entry per effective server, in the same order.
162    pub statuses: Vec<ServerStatus>,
163    /// Everything wrong with either tier, or refused by the trust gate.
164    pub issues: Vec<McpIssue>,
165}
166
167impl ResolvedMcp {
168    /// The servers the runtime should try to connect to.
169    ///
170    /// Test: `super::tests::config_tests::a_disabled_server_is_reported_not_dropped`.
171    pub fn usable(&self) -> Vec<&McpServerConfig> {
172        self.servers
173            .iter()
174            .zip(&self.statuses)
175            .filter(|(_, status)| status.usable)
176            .map(|(server, _)| server)
177            .collect()
178    }
179}
180
181/// Load the global tier, fail-open with a visible finding.
182///
183/// Why: ABSENCE is not a fault — a fresh install has no connectors. A file
184/// that EXISTS and does not parse is, and collapsing the two would start a run
185/// with its connectors quietly gone. `load_or_default` draws exactly that line.
186/// What: returns the servers plus any issue. Never `Err`: no configuration
187/// problem is fatal to a task run.
188/// Test: `super::tests::config_tests::a_malformed_global_file_yields_zero_servers_and_an_issue`,
189/// `super::tests::config_tests::an_absent_global_file_is_empty_without_an_issue`.
190pub fn load_global(path: &Path) -> (Vec<McpServerConfig>, Vec<McpIssue>) {
191    match McpConfigFile::load_or_default(path) {
192        Ok(file) => (file.servers, Vec::new()),
193        Err(e) => {
194            // Deliberately loud: a run about to start with zero connectors
195            // because this file is broken must say so, not merely look empty.
196            tracing::warn!(
197                path = %path.display(),
198                error = %e,
199                "mcp: the shared MCP server file could not be read; starting with ZERO MCP servers",
200            );
201            (
202                Vec::new(),
203                vec![McpIssue {
204                    tier: McpTier::Global,
205                    path: path.to_path_buf(),
206                    detail: format!("the shared MCP server file could not be read: {e}"),
207                    remedy: "Fix the TOML in that file, or delete it to start from no configured \
208                             MCP servers. Until then this run connects to none."
209                        .to_string(),
210                }],
211            )
212        }
213    }
214}
215
216/// Read `<project>/.trusty-code/mcp.toml`, fail-open with a visible finding.
217///
218/// Why: the project file is optional and user-editable; a typo in it must not
219/// end a task run, but must not vanish either.
220/// What: resolves the path through [`resolve_project_entry`], so a project
221/// that still carries `.claude/mcp.toml` is read without a second lookup here.
222/// An absent file is no overrides and no issue; an unreadable or unparseable
223/// one is no overrides WITH an issue.
224/// Test: `super::tests::config_tests::an_absent_project_file_is_no_overrides`,
225/// `super::tests::config_tests::a_misspelled_key_is_refused_with_an_issue`.
226pub fn read_project_overrides(project_root: &Path) -> (ProjectOverrides, Vec<McpIssue>) {
227    let resolved = resolve_project_entry(project_root, PROJECT_MCP_FILE, EntryKind::File);
228    let path = resolved.path;
229    let Ok(raw) = std::fs::read_to_string(&path) else {
230        return (ProjectOverrides::default(), Vec::new());
231    };
232    match toml::from_str::<ProjectOverrides>(&raw) {
233        Ok(overrides) => (overrides, Vec::new()),
234        Err(e) => {
235            tracing::warn!(
236                path = %path.display(),
237                error = %e,
238                "mcp: the project MCP override file could not be read; using the global set alone",
239            );
240            (
241                ProjectOverrides::default(),
242                vec![McpIssue {
243                    tier: McpTier::Project,
244                    path,
245                    detail: format!("the project MCP override file could not be read: {e}"),
246                    remedy: "Fix the TOML in that file. Until then this project's MCP overrides \
247                             are ignored and the global servers are used unchanged."
248                        .to_string(),
249                }],
250            )
251        }
252    }
253}
254
255/// Layer the global tier with the project tier's TRUSTED overrides.
256///
257/// Why: the one entry point [`super::McpToolSet`] calls, and the one place the
258/// two tiers meet. `global_path` is a parameter so tests point at a tempdir
259/// and never touch the real tree.
260/// What: loads both tiers, runs [`super::trust::gate`] over the project's
261/// `Set` entries, calls `trusty_mcp::config::resolve`, and grades each
262/// survivor. Grading here (rather than at the consumer) is what keeps the
263/// statuses a caller renders and the servers it connects to from disagreeing.
264/// Test: `super::tests::config_tests` — the whole module.
265pub fn resolve_at(global_path: &Path, project_root: &Path) -> ResolvedMcp {
266    let (global, mut issues) = load_global(global_path);
267    let (overrides, project_issues) = read_project_overrides(project_root);
268    issues.extend(project_issues);
269
270    let project_path = resolve_project_entry(project_root, PROJECT_MCP_FILE, EntryKind::File).path;
271    let (accepted, refused) = super::trust::gate(&global, &overrides, &project_path);
272    issues.extend(refused);
273
274    let overridden: Vec<&str> = accepted.iter().map(|o| o.name()).collect();
275    let servers = trusty_mcp::config::resolve(&global, &accepted);
276    let statuses = servers
277        .iter()
278        .map(|server| grade(server, &overridden))
279        .collect();
280
281    ResolvedMcp {
282        global,
283        overrides,
284        servers,
285        statuses,
286        issues,
287    }
288}
289
290/// One server's config-time [`ServerStatus`].
291///
292/// What: a disabled server is REPORTED, never dropped — a caller must be able
293/// to show what it is choosing not to connect to. A remote transport is
294/// reported too, as not-usable: this slice speaks stdio only, and silently
295/// omitting an `http` entry would read as a missing config rather than an
296/// unimplemented one.
297/// Test: `super::tests::config_tests::a_disabled_server_is_reported_not_dropped`,
298/// `super::tests::config_tests::a_remote_transport_is_reported_not_usable`.
299fn grade(server: &McpServerConfig, overridden: &[&str]) -> ServerStatus {
300    let tier = if overridden.contains(&server.name.as_str()) {
301        McpTier::Project
302    } else {
303        McpTier::Global
304    };
305    let status = |usable: bool, detail: Option<&str>| ServerStatus {
306        name: server.name.clone(),
307        tier,
308        enabled: server.enabled,
309        usable,
310        detail: detail.map(str::to_string),
311    };
312    if !server.enabled {
313        return status(false, Some("disabled in configuration"));
314    }
315    match server.transport {
316        McpTransport::Stdio { .. } => status(true, None),
317        // #5428: recognized, not an error — slice 1 spawns local subprocesses
318        // only. Slice 2 is where a remote client would land.
319        _ => status(false, Some(super::REMOTE_UNSUPPORTED)),
320    }
321}