Skip to main content

blyte_cli/mcp/
config.rs

1//! MCP server configuration (`mcpServers` JSON), `${ENV_VAR}` expansion, and project trust tracking.
2
3use std::collections::BTreeMap;
4use std::fmt;
5use std::io::ErrorKind;
6use std::path::{Path, PathBuf};
7
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10
11/// Default transport kind for an MCP server.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
13#[serde(rename_all = "lowercase")]
14#[value(rename_all = "lowercase")]
15pub enum TransportKind {
16    Stdio,
17    #[serde(alias = "streamable-http", alias = "streamable_http")]
18    Http,
19}
20
21impl TransportKind {
22    pub fn as_str(&self) -> &'static str {
23        match self {
24            Self::Stdio => "stdio",
25            Self::Http => "http",
26        }
27    }
28}
29
30impl fmt::Display for TransportKind {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str(self.as_str())
33    }
34}
35
36/// Tool approval policy for an MCP server.
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
38#[serde(rename_all = "snake_case")]
39pub enum ApprovalPolicy {
40    #[default]
41    #[value(name = "read_only")]
42    ReadOnly,
43    #[value(name = "auto")]
44    Auto,
45    #[value(name = "ask")]
46    Ask,
47}
48
49impl ApprovalPolicy {
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            Self::ReadOnly => "read_only",
53            Self::Auto => "auto",
54            Self::Ask => "ask",
55        }
56    }
57}
58
59impl fmt::Display for ApprovalPolicy {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(self.as_str())
62    }
63}
64
65/// Origin of a configured MCP server.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "lowercase")]
68pub enum ServerSource {
69    User,
70    Project,
71}
72
73impl ServerSource {
74    pub fn as_str(&self) -> &'static str {
75        match self {
76            Self::User => "user",
77            Self::Project => "project",
78        }
79    }
80}
81
82impl fmt::Display for ServerSource {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(self.as_str())
85    }
86}
87
88fn default_enabled() -> bool {
89    true
90}
91
92/// Standard `mcpServers.<name>` entry compatible with Claude Code / Cursor configs.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94pub struct ServerConfig {
95    #[serde(default, skip_serializing_if = "Option::is_none", alias = "type")]
96    pub transport: Option<TransportKind>,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub command: Option<String>,
99    #[serde(default, skip_serializing_if = "Vec::is_empty")]
100    pub args: Vec<String>,
101    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
102    pub env: BTreeMap<String, String>,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub url: Option<String>,
105    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
106    pub headers: BTreeMap<String, String>,
107    #[serde(default = "default_enabled")]
108    pub enabled: bool,
109    #[serde(default)]
110    pub approval: ApprovalPolicy,
111}
112
113impl ServerConfig {
114    /// Creates a new stdio server configuration.
115    pub fn stdio(
116        command: impl Into<String>,
117        args: Vec<String>,
118        env: BTreeMap<String, String>,
119        approval: ApprovalPolicy,
120    ) -> Self {
121        Self {
122            transport: Some(TransportKind::Stdio),
123            command: Some(command.into()),
124            args,
125            env,
126            url: None,
127            headers: BTreeMap::new(),
128            enabled: true,
129            approval,
130        }
131    }
132
133    /// Creates a new Streamable HTTP server configuration.
134    pub fn http(
135        url: impl Into<String>,
136        headers: BTreeMap<String, String>,
137        approval: ApprovalPolicy,
138    ) -> Self {
139        Self {
140            transport: Some(TransportKind::Http),
141            command: None,
142            args: Vec::new(),
143            env: BTreeMap::new(),
144            url: Some(url.into()),
145            headers,
146            enabled: true,
147            approval,
148        }
149    }
150
151    /// Infers and validates the transport kind for this server entry.
152    pub fn resolve_transport_kind(
153        &self,
154        server_name: &str,
155    ) -> Result<TransportKind, McpConfigError> {
156        let has_command = self
157            .command
158            .as_deref()
159            .is_some_and(|c| !c.trim().is_empty());
160        let has_url = self.url.as_deref().is_some_and(|u| !u.trim().is_empty());
161
162        let kind = match self.transport {
163            Some(TransportKind::Stdio) => {
164                if !has_command {
165                    return Err(McpConfigError::InvalidServer {
166                        name: server_name.to_string(),
167                        reason: "stdio server must specify a non-empty 'command'".to_string(),
168                    });
169                }
170                if has_url {
171                    return Err(McpConfigError::InvalidServer {
172                        name: server_name.to_string(),
173                        reason: "stdio server cannot also specify 'url'".to_string(),
174                    });
175                }
176                TransportKind::Stdio
177            }
178            Some(TransportKind::Http) => {
179                if !has_url {
180                    return Err(McpConfigError::InvalidServer {
181                        name: server_name.to_string(),
182                        reason: "http server must specify a non-empty 'url'".to_string(),
183                    });
184                }
185                if has_command {
186                    return Err(McpConfigError::InvalidServer {
187                        name: server_name.to_string(),
188                        reason: "http server cannot also specify 'command'".to_string(),
189                    });
190                }
191                TransportKind::Http
192            }
193            None => match (has_command, has_url) {
194                (true, true) => {
195                    return Err(McpConfigError::InvalidServer {
196                        name: server_name.to_string(),
197                        reason: "server specifies both 'command' and 'url'; remove one or set 'transport'".to_string(),
198                    });
199                }
200                (true, false) => TransportKind::Stdio,
201                (false, true) => TransportKind::Http,
202                (false, false) => {
203                    return Err(McpConfigError::InvalidServer {
204                        name: server_name.to_string(),
205                        reason: "server must specify either 'command' or 'url'".to_string(),
206                    });
207                }
208            },
209        };
210
211        if kind == TransportKind::Http {
212            let url = self.url.as_deref().unwrap_or("");
213            if !url.starts_with("http://") && !url.starts_with("https://") {
214                return Err(McpConfigError::InvalidServer {
215                    name: server_name.to_string(),
216                    reason: format!("http server url must start with http:// or https://: {url}"),
217                });
218            }
219        }
220
221        Ok(kind)
222    }
223
224    /// Computes a deterministic SHA-256 fingerprint of the server's executable definition and approval policy.
225    pub fn trust_fingerprint(&self) -> String {
226        let mut hasher = Sha256::new();
227        let update_str = |h: &mut Sha256, s: &str| {
228            h.update((s.len() as u64).to_be_bytes());
229            h.update(s.as_bytes());
230        };
231        let update_opt_str = |h: &mut Sha256, opt: Option<&str>| match opt {
232            Some(s) => {
233                h.update([1u8]);
234                update_str(h, s);
235            }
236            None => h.update([0u8]),
237        };
238
239        update_opt_str(&mut hasher, self.transport.map(|t| t.as_str()));
240        update_opt_str(&mut hasher, self.command.as_deref());
241        hasher.update((self.args.len() as u64).to_be_bytes());
242        for arg in &self.args {
243            update_str(&mut hasher, arg);
244        }
245        hasher.update((self.env.len() as u64).to_be_bytes());
246        for (k, v) in &self.env {
247            update_str(&mut hasher, k);
248            update_str(&mut hasher, v);
249        }
250        update_opt_str(&mut hasher, self.url.as_deref());
251        hasher.update((self.headers.len() as u64).to_be_bytes());
252        for (k, v) in &self.headers {
253            update_str(&mut hasher, k);
254            update_str(&mut hasher, v);
255        }
256        update_str(&mut hasher, self.approval.as_str());
257
258        let digest = hasher.finalize();
259        format!("{digest:x}")
260    }
261
262    /// Short display target (URL for HTTP, command + args for stdio).
263    pub fn target_display(&self) -> String {
264        if let Some(url) = &self.url {
265            return url.clone();
266        }
267        if let Some(cmd) = &self.command {
268            if self.args.is_empty() {
269                return cmd.clone();
270            }
271            return format!("{cmd} {}", self.args.join(" "));
272        }
273        String::new()
274    }
275}
276
277/// Top-level `mcp.json` / `.mcp.json` file format.
278#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
279pub struct McpConfigFile {
280    #[serde(rename = "mcpServers", default)]
281    pub mcp_servers: BTreeMap<String, ServerConfig>,
282}
283
284/// Resolved, environment-expanded transport configuration ready to connect.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub enum ServerTransport {
287    Stdio {
288        command: String,
289        args: Vec<String>,
290        env: BTreeMap<String, String>,
291    },
292    Http {
293        url: String,
294        headers: BTreeMap<String, String>,
295    },
296}
297
298/// A validated MCP server loaded from user or project configuration.
299#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct ConfiguredServer {
301    pub name: String,
302    pub source: ServerSource,
303    pub source_path: PathBuf,
304    pub enabled: bool,
305    pub approval: ApprovalPolicy,
306    pub trusted: bool,
307    pub transport_kind: TransportKind,
308    pub config: ServerConfig,
309}
310
311impl ConfiguredServer {
312    /// Expands `${ENV_VAR}` references in `env` or `headers` and returns the concrete transport.
313    pub fn resolve_transport(
314        &self,
315        env_lookup: &EnvLookup,
316    ) -> Result<ServerTransport, McpConfigError> {
317        match self.transport_kind {
318            TransportKind::Stdio => {
319                let command =
320                    self.config
321                        .command
322                        .clone()
323                        .ok_or_else(|| McpConfigError::InvalidServer {
324                            name: self.name.clone(),
325                            reason: "stdio server missing 'command'".to_string(),
326                        })?;
327                let mut expanded_env = BTreeMap::new();
328                for (k, v) in &self.config.env {
329                    let expanded = expand_env_vars(v, env_lookup)
330                        .map_err(|err| err.with_context(&self.name, &format!("env.{k}")))?;
331                    expanded_env.insert(k.clone(), expanded);
332                }
333                Ok(ServerTransport::Stdio {
334                    command,
335                    args: self.config.args.clone(),
336                    env: expanded_env,
337                })
338            }
339            TransportKind::Http => {
340                let url = self
341                    .config
342                    .url
343                    .clone()
344                    .ok_or_else(|| McpConfigError::InvalidServer {
345                        name: self.name.clone(),
346                        reason: "http server missing 'url'".to_string(),
347                    })?;
348                let mut expanded_headers = BTreeMap::new();
349                for (k, v) in &self.config.headers {
350                    let expanded = expand_env_vars(v, env_lookup)
351                        .map_err(|err| err.with_context(&self.name, &format!("headers.{k}")))?;
352                    expanded_headers.insert(k.clone(), expanded);
353                }
354                Ok(ServerTransport::Http {
355                    url,
356                    headers: expanded_headers,
357                })
358            }
359        }
360    }
361
362    /// Expands `${ENV_VAR}` references using process environment and blyte's env file.
363    pub fn resolve_transport_from_system(&self) -> Result<ServerTransport, McpConfigError> {
364        let lookup = EnvLookup::from_system()?;
365        self.resolve_transport(&lookup)
366    }
367}
368
369/// Errors returned while loading, validating, expanding, or saving MCP configuration.
370#[derive(Debug)]
371pub enum McpConfigError {
372    ConfigDirUnavailable,
373    Io {
374        path: PathBuf,
375        source: std::io::Error,
376    },
377    Parse {
378        path: PathBuf,
379        message: String,
380    },
381    InvalidServer {
382        name: String,
383        reason: String,
384    },
385    MissingEnvVar {
386        server: Option<String>,
387        field: Option<String>,
388        var: String,
389    },
390    InvalidEnvSyntax {
391        server: Option<String>,
392        field: Option<String>,
393        detail: String,
394    },
395    EnvFile(String),
396    DuplicateServer(String),
397    ServerNotFound(String),
398}
399
400impl McpConfigError {
401    fn with_context(self, server: &str, field: &str) -> Self {
402        match self {
403            Self::MissingEnvVar { var, .. } => Self::MissingEnvVar {
404                server: Some(server.to_string()),
405                field: Some(field.to_string()),
406                var,
407            },
408            Self::InvalidEnvSyntax { detail, .. } => Self::InvalidEnvSyntax {
409                server: Some(server.to_string()),
410                field: Some(field.to_string()),
411                detail,
412            },
413            other => other,
414        }
415    }
416}
417
418impl fmt::Display for McpConfigError {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        match self {
421            Self::ConfigDirUnavailable => {
422                write!(f, "cannot determine blyte config directory (neither XDG_CONFIG_HOME nor HOME is set)")
423            }
424            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
425            Self::Parse { path, message } => {
426                write!(f, "failed to parse {}: {message}", path.display())
427            }
428            Self::InvalidServer { name, reason } => {
429                write!(f, "invalid MCP server '{name}': {reason}")
430            }
431            Self::MissingEnvVar { server, field, var } => match (server, field) {
432                (Some(s), Some(fld)) => write!(
433                    f,
434                    "MCP server '{s}' ({fld}) references missing environment variable '${{{var}}}'"
435                ),
436                _ => write!(f, "missing environment variable '${{{var}}}'"),
437            },
438            Self::InvalidEnvSyntax {
439                server,
440                field,
441                detail,
442            } => match (server, field) {
443                (Some(s), Some(fld)) => {
444                    write!(
445                        f,
446                        "MCP server '{s}' ({fld}) has invalid variable syntax: {detail}"
447                    )
448                }
449                _ => write!(f, "invalid environment variable syntax: {detail}"),
450            },
451            Self::EnvFile(msg) => write!(f, "failed to load blyte env file: {msg}"),
452            Self::DuplicateServer(name) => {
453                write!(
454                    f,
455                    "MCP server '{name}' already exists (pass --replace to overwrite)"
456                )
457            }
458            Self::ServerNotFound(name) => write!(f, "MCP server '{name}' not found"),
459        }
460    }
461}
462
463impl std::error::Error for McpConfigError {}
464
465/// Source for `${ENV_VAR}` expansion combining process environment and blyte's env file.
466#[derive(Debug, Clone, Default)]
467pub struct EnvLookup {
468    process_env: Option<BTreeMap<String, String>>,
469    file_env: BTreeMap<String, String>,
470}
471
472impl EnvLookup {
473    /// Builds an `EnvLookup` reading from the live process environment and blyte's default env file.
474    pub fn from_system() -> Result<Self, McpConfigError> {
475        let mut file_env = BTreeMap::new();
476        if let Some(path) = crate::env_file::default_path() {
477            file_env = read_env_file_map(&path)?;
478        }
479        Ok(Self {
480            process_env: None,
481            file_env,
482        })
483    }
484
485    /// Builds an `EnvLookup` reading from live process environment and a specific env file path.
486    pub fn from_process_and_file(env_file_path: &Path) -> Result<Self, McpConfigError> {
487        let file_env = read_env_file_map(env_file_path)?;
488        Ok(Self {
489            process_env: None,
490            file_env,
491        })
492    }
493
494    /// Builds an isolated `EnvLookup` from explicit maps (useful for deterministic testing).
495    pub fn from_maps(
496        process_env: BTreeMap<String, String>,
497        file_env: BTreeMap<String, String>,
498    ) -> Self {
499        Self {
500            process_env: Some(process_env),
501            file_env,
502        }
503    }
504
505    /// Resolves a variable name: process environment takes precedence over env file.
506    pub fn get(&self, name: &str) -> Option<String> {
507        match &self.process_env {
508            Some(map) => {
509                if let Some(val) = map.get(name) {
510                    return Some(val.clone());
511                }
512            }
513            None => {
514                if let Ok(val) = std::env::var(name) {
515                    return Some(val);
516                }
517            }
518        }
519        self.file_env.get(name).cloned()
520    }
521}
522
523fn read_env_file_map(path: &Path) -> Result<BTreeMap<String, String>, McpConfigError> {
524    let meta = match std::fs::metadata(path) {
525        Ok(m) => m,
526        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
527        Err(e) => {
528            return Err(McpConfigError::Io {
529                path: path.to_path_buf(),
530                source: e,
531            });
532        }
533    };
534    #[cfg(unix)]
535    {
536        use std::os::unix::fs::PermissionsExt;
537        if meta.permissions().mode() & 0o077 != 0 {
538            return Err(McpConfigError::EnvFile(format!(
539                "{} can be read by other users, so it was not loaded; run: chmod 600 {}",
540                path.display(),
541                path.display()
542            )));
543        }
544    }
545    #[cfg(not(unix))]
546    let _ = meta;
547
548    let text = std::fs::read_to_string(path).map_err(|source| McpConfigError::Io {
549        path: path.to_path_buf(),
550        source,
551    })?;
552    let mut map = BTreeMap::new();
553    for (k, v) in crate::env_file::parse(&text) {
554        map.insert(k, v);
555    }
556    Ok(map)
557}
558
559/// Expands all `${ENV_VAR}` placeholders in `input` using `lookup`.
560/// Returns an error if syntax is malformed or any referenced variable is missing.
561pub fn expand_env_vars(input: &str, lookup: &EnvLookup) -> Result<String, McpConfigError> {
562    let mut out = String::with_capacity(input.len());
563    let mut rest = input;
564    while let Some(idx) = rest.find("${") {
565        out.push_str(&rest[..idx]);
566        let after_open = &rest[idx + 2..];
567        let Some(end) = after_open.find('}') else {
568            return Err(McpConfigError::InvalidEnvSyntax {
569                server: None,
570                field: None,
571                detail: format!("unclosed '${{' in '{input}'"),
572            });
573        };
574        let var_name = &after_open[..end];
575        if !is_valid_env_name(var_name) {
576            return Err(McpConfigError::InvalidEnvSyntax {
577                server: None,
578                field: None,
579                detail: format!("invalid environment variable name '${{{var_name}}}'"),
580            });
581        }
582        let value = lookup
583            .get(var_name)
584            .ok_or_else(|| McpConfigError::MissingEnvVar {
585                server: None,
586                field: None,
587                var: var_name.to_string(),
588            })?;
589        out.push_str(&value);
590        rest = &after_open[end + 1..];
591    }
592    out.push_str(rest);
593    Ok(out)
594}
595
596fn is_valid_env_name(name: &str) -> bool {
597    let mut chars = name.chars();
598    let Some(first) = chars.next() else {
599        return false;
600    };
601    (first.is_ascii_alphabetic() || first == '_')
602        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
603}
604
605/// Returns blyte's user configuration directory (`$XDG_CONFIG_HOME/blyte` or `~/.config/blyte`).
606pub fn user_config_dir() -> Result<PathBuf, McpConfigError> {
607    if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
608        return Ok(PathBuf::from(x).join("blyte"));
609    }
610    std::env::var_os("HOME")
611        .filter(|h| !h.is_empty())
612        .map(|h| PathBuf::from(h).join(".config/blyte"))
613        .ok_or(McpConfigError::ConfigDirUnavailable)
614}
615
616/// Returns the user-level MCP configuration file path (`<config_dir>/mcp.json`).
617pub fn user_config_path() -> Result<PathBuf, McpConfigError> {
618    Ok(user_config_dir()?.join("mcp.json"))
619}
620
621/// Returns the user-level project-server trust store path (`<config_dir>/mcp-trust.json`).
622pub fn trust_store_path() -> Result<PathBuf, McpConfigError> {
623    Ok(user_config_dir()?.join("mcp-trust.json"))
624}
625
626/// Returns the project-level `.mcp.json` path under `project_root`.
627pub fn project_config_path(project_root: &Path) -> PathBuf {
628    project_root.join(".mcp.json")
629}
630
631/// Loads a single `mcp.json` or `.mcp.json` file.
632/// A missing file returns an empty configuration; unreadable or malformed files return an error.
633pub fn load_config_file(path: &Path) -> Result<McpConfigFile, McpConfigError> {
634    let text = match std::fs::read_to_string(path) {
635        Ok(s) => s,
636        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(McpConfigFile::default()),
637        Err(source) => {
638            return Err(McpConfigError::Io {
639                path: path.to_path_buf(),
640                source,
641            });
642        }
643    };
644    let parsed: McpConfigFile = serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
645        path: path.to_path_buf(),
646        message: e.to_string(),
647    })?;
648    for (name, cfg) in &parsed.mcp_servers {
649        if name.trim().is_empty() {
650            return Err(McpConfigError::InvalidServer {
651                name: name.clone(),
652                reason: "server name cannot be empty".to_string(),
653            });
654        }
655        cfg.resolve_transport_kind(name)?;
656    }
657    Ok(parsed)
658}
659
660/// Writes `config` to `path` with mode `0600` on Unix, creating parent directories if needed.
661pub fn save_config_file(path: &Path, config: &McpConfigFile) -> Result<(), McpConfigError> {
662    let mut rendered = serde_json::to_string_pretty(config).map_err(|e| McpConfigError::Parse {
663        path: path.to_path_buf(),
664        message: e.to_string(),
665    })?;
666    rendered.push('\n');
667    write_restricted_file(path, rendered.as_bytes())
668}
669
670fn write_restricted_file(path: &Path, bytes: &[u8]) -> Result<(), McpConfigError> {
671    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
672        std::fs::create_dir_all(parent).map_err(|source| McpConfigError::Io {
673            path: parent.to_path_buf(),
674            source,
675        })?;
676    }
677
678    #[cfg(unix)]
679    {
680        use std::io::Write;
681        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
682        let mut file = std::fs::OpenOptions::new()
683            .write(true)
684            .create(true)
685            .truncate(true)
686            .mode(0o600)
687            .open(path)
688            .map_err(|source| McpConfigError::Io {
689                path: path.to_path_buf(),
690                source,
691            })?;
692        file.write_all(bytes).map_err(|source| McpConfigError::Io {
693            path: path.to_path_buf(),
694            source,
695        })?;
696        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
697            |source| McpConfigError::Io {
698                path: path.to_path_buf(),
699                source,
700            },
701        )?;
702    }
703    #[cfg(not(unix))]
704    {
705        std::fs::write(path, bytes).map_err(|source| McpConfigError::Io {
706            path: path.to_path_buf(),
707            source,
708        })?;
709    }
710
711    Ok(())
712}
713
714/// Persistent record of explicitly approved project-level MCP servers.
715#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
716pub struct ProjectTrustStore {
717    #[serde(default)]
718    pub projects: BTreeMap<String, BTreeMap<String, String>>,
719}
720
721impl ProjectTrustStore {
722    /// Loads the trust store from `path`. Missing file means no trusted project servers.
723    pub fn load(path: &Path) -> Result<Self, McpConfigError> {
724        let text = match std::fs::read_to_string(path) {
725            Ok(s) => s,
726            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Self::default()),
727            Err(source) => {
728                return Err(McpConfigError::Io {
729                    path: path.to_path_buf(),
730                    source,
731                });
732            }
733        };
734        serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
735            path: path.to_path_buf(),
736            message: e.to_string(),
737        })
738    }
739
740    /// Saves the trust store to `path` with mode `0600` on Unix.
741    pub fn save(&self, path: &Path) -> Result<(), McpConfigError> {
742        let mut rendered =
743            serde_json::to_string_pretty(self).map_err(|e| McpConfigError::Parse {
744                path: path.to_path_buf(),
745                message: e.to_string(),
746            })?;
747        rendered.push('\n');
748        write_restricted_file(path, rendered.as_bytes())
749    }
750
751    /// Checks whether `server_name` in `project_root` is explicitly trusted for its current config.
752    pub fn is_trusted(
753        &self,
754        project_root: &Path,
755        server_name: &str,
756        config: &ServerConfig,
757    ) -> Result<bool, McpConfigError> {
758        let key = project_key(project_root)?;
759        let expected = config.trust_fingerprint();
760        Ok(self
761            .projects
762            .get(&key)
763            .and_then(|servers| servers.get(server_name))
764            .is_some_and(|stored| stored == &expected))
765    }
766
767    /// Records explicit user approval for a project-level server's current configuration.
768    pub fn trust(
769        &mut self,
770        project_root: &Path,
771        server_name: &str,
772        config: &ServerConfig,
773    ) -> Result<(), McpConfigError> {
774        let key = project_key(project_root)?;
775        self.projects
776            .entry(key)
777            .or_default()
778            .insert(server_name.to_string(), config.trust_fingerprint());
779        Ok(())
780    }
781
782    /// Revokes trust for a project-level server.
783    pub fn revoke(
784        &mut self,
785        project_root: &Path,
786        server_name: &str,
787    ) -> Result<bool, McpConfigError> {
788        let key = project_key(project_root)?;
789        let Some(servers) = self.projects.get_mut(&key) else {
790            return Ok(false);
791        };
792        let removed = servers.remove(server_name).is_some();
793        if servers.is_empty() {
794            self.projects.remove(&key);
795        }
796        Ok(removed)
797    }
798}
799
800fn project_key(project_root: &Path) -> Result<String, McpConfigError> {
801    let canonical = std::fs::canonicalize(project_root).map_err(|source| McpConfigError::Io {
802        path: project_root.to_path_buf(),
803        source,
804    })?;
805    Ok(canonical.to_string_lossy().into_owned())
806}
807
808/// Loads all configured servers from user config and optional project `.mcp.json`,
809/// tagging each with its source and trust status.
810/// User servers are always trusted; project servers default to untrusted unless present
811/// with a matching fingerprint in `trust_path`.
812pub fn load_configured_servers(
813    user_path: &Path,
814    project_root: Option<&Path>,
815    trust_path: &Path,
816) -> Result<Vec<ConfiguredServer>, McpConfigError> {
817    let user_file = load_config_file(user_path)?;
818    let mut servers = Vec::new();
819    let mut seen_names = std::collections::BTreeSet::new();
820
821    for (name, config) in user_file.mcp_servers {
822        let transport_kind = config.resolve_transport_kind(&name)?;
823        seen_names.insert(name.clone());
824        servers.push(ConfiguredServer {
825            name,
826            source: ServerSource::User,
827            source_path: user_path.to_path_buf(),
828            enabled: config.enabled,
829            approval: config.approval,
830            trusted: true,
831            transport_kind,
832            config,
833        });
834    }
835
836    if let Some(root) = project_root {
837        let proj_path = project_config_path(root);
838        let proj_file = load_config_file(&proj_path)?;
839        if !proj_file.mcp_servers.is_empty() {
840            let trust_store = ProjectTrustStore::load(trust_path)?;
841            for (name, config) in proj_file.mcp_servers {
842                if seen_names.contains(&name) {
843                    continue;
844                }
845                let transport_kind = config.resolve_transport_kind(&name)?;
846                let trusted = trust_store.is_trusted(root, &name, &config)?;
847                servers.push(ConfiguredServer {
848                    name,
849                    source: ServerSource::Project,
850                    source_path: proj_path.clone(),
851                    enabled: config.enabled,
852                    approval: config.approval,
853                    trusted,
854                    transport_kind,
855                    config,
856                });
857            }
858        }
859    }
860
861    servers.sort_by(|a, b| a.name.cmp(&b.name));
862    Ok(servers)
863}
864
865/// Adds or replaces a server entry in `user_path`.
866pub fn add_user_server(
867    user_path: &Path,
868    name: &str,
869    config: ServerConfig,
870    replace: bool,
871) -> Result<(), McpConfigError> {
872    validate_server_name(name)?;
873    config.resolve_transport_kind(name)?;
874    let mut file = load_config_file(user_path)?;
875    if !replace && file.mcp_servers.contains_key(name) {
876        return Err(McpConfigError::DuplicateServer(name.to_string()));
877    }
878    file.mcp_servers.insert(name.to_string(), config);
879    save_config_file(user_path, &file)
880}
881
882/// Removes a server entry from `user_path`. Returns `ServerNotFound` if absent.
883pub fn remove_user_server(user_path: &Path, name: &str) -> Result<(), McpConfigError> {
884    let mut file = load_config_file(user_path)?;
885    if file.mcp_servers.remove(name).is_none() {
886        return Err(McpConfigError::ServerNotFound(name.to_string()));
887    }
888    save_config_file(user_path, &file)
889}
890
891/// Validates a server name for `blyte mcp add`.
892pub fn validate_server_name(name: &str) -> Result<(), McpConfigError> {
893    if name.trim().is_empty() {
894        return Err(McpConfigError::InvalidServer {
895            name: name.to_string(),
896            reason: "server name cannot be empty".to_string(),
897        });
898    }
899    if name.chars().any(|c| c.is_whitespace()) {
900        return Err(McpConfigError::InvalidServer {
901            name: name.to_string(),
902            reason: "server name cannot contain whitespace".to_string(),
903        });
904    }
905    if name.contains("__") {
906        return Err(McpConfigError::InvalidServer {
907            name: name.to_string(),
908            reason: "server name cannot contain '__'".to_string(),
909        });
910    }
911    Ok(())
912}