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/// Optional pre-registered OAuth 2.1 client settings for a remote HTTP MCP server.
93#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
94pub struct OAuthClientConfig {
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub client_id: Option<String>,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub client_secret: Option<String>,
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub callback_port: Option<u16>,
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub scopes: Option<Vec<String>>,
103}
104
105impl fmt::Debug for OAuthClientConfig {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.debug_struct("OAuthClientConfig")
108            .field("client_id", &self.client_id)
109            .field(
110                "client_secret",
111                &self.client_secret.as_ref().map(|_| "<redacted>"),
112            )
113            .field("callback_port", &self.callback_port)
114            .field("scopes", &self.scopes)
115            .finish()
116    }
117}
118
119/// Environment-expanded OAuth 2.1 client settings ready for an OAuth flow.
120#[derive(Clone, Default, PartialEq, Eq)]
121pub struct ResolvedOAuthClientConfig {
122    pub client_id: Option<String>,
123    pub client_secret: Option<String>,
124    pub callback_port: Option<u16>,
125    pub scopes: Option<Vec<String>>,
126}
127
128impl fmt::Debug for ResolvedOAuthClientConfig {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.debug_struct("ResolvedOAuthClientConfig")
131            .field("client_id", &self.client_id)
132            .field(
133                "client_secret",
134                &self.client_secret.as_ref().map(|_| "<redacted>"),
135            )
136            .field("callback_port", &self.callback_port)
137            .field("scopes", &self.scopes)
138            .finish()
139    }
140}
141
142impl OAuthClientConfig {
143    /// Returns true when no OAuth client fields are set.
144    pub fn is_empty(&self) -> bool {
145        self.client_id
146            .as_deref()
147            .is_none_or(|s| s.trim().is_empty())
148            && self
149                .client_secret
150                .as_deref()
151                .is_none_or(|s| s.trim().is_empty())
152            && self.callback_port.is_none()
153            && self
154                .scopes
155                .as_ref()
156                .is_none_or(|scopes| scopes.iter().all(|s| s.trim().is_empty()))
157    }
158
159    /// Trims string fields and drops empty entries; returns `None` when nothing remains.
160    pub fn normalized(self) -> Option<Self> {
161        let client_id = self
162            .client_id
163            .map(|s| s.trim().to_string())
164            .filter(|s| !s.is_empty());
165        let client_secret = self
166            .client_secret
167            .map(|s| s.trim().to_string())
168            .filter(|s| !s.is_empty());
169        let scopes = self
170            .scopes
171            .map(|items| {
172                let mut seen = std::collections::BTreeSet::new();
173                let mut cleaned = Vec::new();
174                for item in items {
175                    let trimmed = item.trim();
176                    if !trimmed.is_empty() && seen.insert(trimmed.to_string()) {
177                        cleaned.push(trimmed.to_string());
178                    }
179                }
180                cleaned
181            })
182            .filter(|items| !items.is_empty());
183        let out = Self {
184            client_id,
185            client_secret,
186            callback_port: self.callback_port,
187            scopes,
188        };
189        if out.is_empty() {
190            None
191        } else {
192            Some(out)
193        }
194    }
195
196    /// Validates OAuth client settings for `server_name`.
197    pub fn validate(&self, server_name: &str) -> Result<(), McpConfigError> {
198        if self.callback_port == Some(0) {
199            return Err(McpConfigError::InvalidServer {
200                name: server_name.to_string(),
201                reason: "oauth.callback_port must be between 1 and 65535".to_string(),
202            });
203        }
204        Ok(())
205    }
206
207    /// Returns whether a non-empty `client_secret` value is configured.
208    pub fn has_client_secret(&self) -> bool {
209        self.client_secret
210            .as_deref()
211            .is_some_and(|s| !s.trim().is_empty())
212    }
213
214    /// Expands `${ENV_VAR}` references in `client_id` and `client_secret`.
215    pub fn resolve(
216        &self,
217        server_name: &str,
218        env_lookup: &EnvLookup,
219    ) -> Result<ResolvedOAuthClientConfig, McpConfigError> {
220        let client_id = match self.client_id.as_deref() {
221            Some(raw) if !raw.trim().is_empty() => {
222                let expanded = expand_env_vars(raw.trim(), env_lookup)
223                    .map_err(|err| err.with_context(server_name, "oauth.client_id"))?;
224                let trimmed = expanded.trim();
225                if trimmed.is_empty() {
226                    None
227                } else {
228                    Some(trimmed.to_string())
229                }
230            }
231            _ => None,
232        };
233        let client_secret = match self.client_secret.as_deref() {
234            Some(raw) if !raw.trim().is_empty() => {
235                let expanded = expand_env_vars(raw.trim(), env_lookup)
236                    .map_err(|err| err.with_context(server_name, "oauth.client_secret"))?;
237                let trimmed = expanded.trim();
238                if trimmed.is_empty() {
239                    None
240                } else {
241                    Some(trimmed.to_string())
242                }
243            }
244            _ => None,
245        };
246        let scopes = self
247            .scopes
248            .as_ref()
249            .map(|items| {
250                items
251                    .iter()
252                    .map(|s| s.trim())
253                    .filter(|s| !s.is_empty())
254                    .map(String::from)
255                    .collect::<Vec<_>>()
256            })
257            .filter(|items| !items.is_empty());
258        Ok(ResolvedOAuthClientConfig {
259            client_id,
260            client_secret,
261            callback_port: self.callback_port,
262            scopes,
263        })
264    }
265
266    /// Expands `${ENV_VAR}` references using process environment and blyte's env file.
267    pub fn resolve_from_system(
268        &self,
269        server_name: &str,
270    ) -> Result<ResolvedOAuthClientConfig, McpConfigError> {
271        let lookup = EnvLookup::from_system()?;
272        self.resolve(server_name, &lookup)
273    }
274}
275
276/// Standard `mcpServers.<name>` entry compatible with Claude Code / Cursor configs.
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct ServerConfig {
279    #[serde(default, skip_serializing_if = "Option::is_none", alias = "type")]
280    pub transport: Option<TransportKind>,
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub command: Option<String>,
283    #[serde(default, skip_serializing_if = "Vec::is_empty")]
284    pub args: Vec<String>,
285    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
286    pub env: BTreeMap<String, String>,
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub url: Option<String>,
289    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
290    pub headers: BTreeMap<String, String>,
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub oauth: Option<OAuthClientConfig>,
293    #[serde(default = "default_enabled")]
294    pub enabled: bool,
295    #[serde(default)]
296    pub approval: ApprovalPolicy,
297}
298
299impl ServerConfig {
300    /// Creates a new stdio server configuration.
301    pub fn stdio(
302        command: impl Into<String>,
303        args: Vec<String>,
304        env: BTreeMap<String, String>,
305        approval: ApprovalPolicy,
306    ) -> Self {
307        Self {
308            transport: Some(TransportKind::Stdio),
309            command: Some(command.into()),
310            args,
311            env,
312            url: None,
313            headers: BTreeMap::new(),
314            oauth: None,
315            enabled: true,
316            approval,
317        }
318    }
319
320    /// Creates a new Streamable HTTP server configuration.
321    pub fn http(
322        url: impl Into<String>,
323        headers: BTreeMap<String, String>,
324        approval: ApprovalPolicy,
325    ) -> Self {
326        Self {
327            transport: Some(TransportKind::Http),
328            command: None,
329            args: Vec::new(),
330            env: BTreeMap::new(),
331            url: Some(url.into()),
332            headers,
333            oauth: None,
334            enabled: true,
335            approval,
336        }
337    }
338
339    /// Attaches optional OAuth client settings to this server configuration.
340    pub fn with_oauth(mut self, oauth: Option<OAuthClientConfig>) -> Self {
341        self.oauth = oauth.and_then(OAuthClientConfig::normalized);
342        self
343    }
344
345    /// Infers and validates the transport kind for this server entry.
346    pub fn resolve_transport_kind(
347        &self,
348        server_name: &str,
349    ) -> Result<TransportKind, McpConfigError> {
350        let has_command = self
351            .command
352            .as_deref()
353            .is_some_and(|c| !c.trim().is_empty());
354        let has_url = self.url.as_deref().is_some_and(|u| !u.trim().is_empty());
355
356        let kind = match self.transport {
357            Some(TransportKind::Stdio) => {
358                if !has_command {
359                    return Err(McpConfigError::InvalidServer {
360                        name: server_name.to_string(),
361                        reason: "stdio server must specify a non-empty 'command'".to_string(),
362                    });
363                }
364                if has_url {
365                    return Err(McpConfigError::InvalidServer {
366                        name: server_name.to_string(),
367                        reason: "stdio server cannot also specify 'url'".to_string(),
368                    });
369                }
370                TransportKind::Stdio
371            }
372            Some(TransportKind::Http) => {
373                if !has_url {
374                    return Err(McpConfigError::InvalidServer {
375                        name: server_name.to_string(),
376                        reason: "http server must specify a non-empty 'url'".to_string(),
377                    });
378                }
379                if has_command {
380                    return Err(McpConfigError::InvalidServer {
381                        name: server_name.to_string(),
382                        reason: "http server cannot also specify 'command'".to_string(),
383                    });
384                }
385                TransportKind::Http
386            }
387            None => match (has_command, has_url) {
388                (true, true) => {
389                    return Err(McpConfigError::InvalidServer {
390                        name: server_name.to_string(),
391                        reason: "server specifies both 'command' and 'url'; remove one or set 'transport'".to_string(),
392                    });
393                }
394                (true, false) => TransportKind::Stdio,
395                (false, true) => TransportKind::Http,
396                (false, false) => {
397                    return Err(McpConfigError::InvalidServer {
398                        name: server_name.to_string(),
399                        reason: "server must specify either 'command' or 'url'".to_string(),
400                    });
401                }
402            },
403        };
404
405        if kind == TransportKind::Http {
406            let url = self.url.as_deref().unwrap_or("");
407            if !url.starts_with("http://") && !url.starts_with("https://") {
408                return Err(McpConfigError::InvalidServer {
409                    name: server_name.to_string(),
410                    reason: format!("http server url must start with http:// or https://: {url}"),
411                });
412            }
413            if let Some(oauth) = &self.oauth {
414                if oauth.callback_port == Some(0) {
415                    return Err(McpConfigError::InvalidServer {
416                        name: server_name.to_string(),
417                        reason: "oauth.callback_port must be between 1 and 65535".to_string(),
418                    });
419                }
420            }
421        } else if self.oauth.as_ref().is_some_and(|o| !o.is_empty()) {
422            return Err(McpConfigError::InvalidServer {
423                name: server_name.to_string(),
424                reason: "stdio server cannot specify 'oauth'".to_string(),
425            });
426        }
427
428        Ok(kind)
429    }
430
431    /// Computes a deterministic SHA-256 fingerprint of the server's executable definition and approval policy.
432    pub fn trust_fingerprint(&self) -> String {
433        let mut hasher = Sha256::new();
434        let update_str = |h: &mut Sha256, s: &str| {
435            h.update((s.len() as u64).to_be_bytes());
436            h.update(s.as_bytes());
437        };
438        let update_opt_str = |h: &mut Sha256, opt: Option<&str>| match opt {
439            Some(s) => {
440                h.update([1u8]);
441                update_str(h, s);
442            }
443            None => h.update([0u8]),
444        };
445
446        update_opt_str(&mut hasher, self.transport.map(|t| t.as_str()));
447        update_opt_str(&mut hasher, self.command.as_deref());
448        hasher.update((self.args.len() as u64).to_be_bytes());
449        for arg in &self.args {
450            update_str(&mut hasher, arg);
451        }
452        hasher.update((self.env.len() as u64).to_be_bytes());
453        for (k, v) in &self.env {
454            update_str(&mut hasher, k);
455            update_str(&mut hasher, v);
456        }
457        update_opt_str(&mut hasher, self.url.as_deref());
458        hasher.update((self.headers.len() as u64).to_be_bytes());
459        for (k, v) in &self.headers {
460            update_str(&mut hasher, k);
461            update_str(&mut hasher, v);
462        }
463        update_str(&mut hasher, self.approval.as_str());
464        if let Some(oauth) = &self.oauth {
465            if !oauth.is_empty() {
466                hasher.update([1u8]);
467                update_opt_str(&mut hasher, oauth.client_id.as_deref());
468                update_opt_str(&mut hasher, oauth.client_secret.as_deref());
469                match oauth.callback_port {
470                    Some(port) => {
471                        hasher.update([1u8]);
472                        hasher.update(port.to_be_bytes());
473                    }
474                    None => hasher.update([0u8]),
475                }
476                match &oauth.scopes {
477                    Some(scopes) => {
478                        hasher.update([1u8]);
479                        hasher.update((scopes.len() as u64).to_be_bytes());
480                        for scope in scopes {
481                            update_str(&mut hasher, scope);
482                        }
483                    }
484                    None => hasher.update([0u8]),
485                }
486            }
487        }
488
489        let digest = hasher.finalize();
490        format!("{digest:x}")
491    }
492
493    /// Short display target (URL for HTTP, command + args for stdio).
494    pub fn target_display(&self) -> String {
495        if let Some(url) = &self.url {
496            return url.clone();
497        }
498        if let Some(cmd) = &self.command {
499            if self.args.is_empty() {
500                return cmd.clone();
501            }
502            return format!("{cmd} {}", self.args.join(" "));
503        }
504        String::new()
505    }
506}
507
508/// Top-level `mcp.json` / `.mcp.json` file format.
509#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
510pub struct McpConfigFile {
511    #[serde(rename = "mcpServers", default)]
512    pub mcp_servers: BTreeMap<String, ServerConfig>,
513}
514
515/// Resolved, environment-expanded transport configuration ready to connect.
516#[derive(Debug, Clone, PartialEq, Eq)]
517pub enum ServerTransport {
518    Stdio {
519        command: String,
520        args: Vec<String>,
521        env: BTreeMap<String, String>,
522    },
523    Http {
524        url: String,
525        headers: BTreeMap<String, String>,
526    },
527}
528
529/// A validated MCP server loaded from user or project configuration.
530#[derive(Debug, Clone, PartialEq, Eq)]
531pub struct ConfiguredServer {
532    pub name: String,
533    pub source: ServerSource,
534    pub source_path: PathBuf,
535    pub enabled: bool,
536    pub approval: ApprovalPolicy,
537    pub trusted: bool,
538    pub transport_kind: TransportKind,
539    pub config: ServerConfig,
540}
541
542impl ConfiguredServer {
543    /// Expands `${ENV_VAR}` references in `env` or `headers` and returns the concrete transport.
544    pub fn resolve_transport(
545        &self,
546        env_lookup: &EnvLookup,
547    ) -> Result<ServerTransport, McpConfigError> {
548        match self.transport_kind {
549            TransportKind::Stdio => {
550                let command =
551                    self.config
552                        .command
553                        .clone()
554                        .ok_or_else(|| McpConfigError::InvalidServer {
555                            name: self.name.clone(),
556                            reason: "stdio server missing 'command'".to_string(),
557                        })?;
558                let mut expanded_env = BTreeMap::new();
559                for (k, v) in &self.config.env {
560                    let expanded = expand_env_vars(v, env_lookup)
561                        .map_err(|err| err.with_context(&self.name, &format!("env.{k}")))?;
562                    expanded_env.insert(k.clone(), expanded);
563                }
564                Ok(ServerTransport::Stdio {
565                    command,
566                    args: self.config.args.clone(),
567                    env: expanded_env,
568                })
569            }
570            TransportKind::Http => {
571                let url = self
572                    .config
573                    .url
574                    .clone()
575                    .ok_or_else(|| McpConfigError::InvalidServer {
576                        name: self.name.clone(),
577                        reason: "http server missing 'url'".to_string(),
578                    })?;
579                let mut expanded_headers = BTreeMap::new();
580                for (k, v) in &self.config.headers {
581                    let expanded = expand_env_vars(v, env_lookup)
582                        .map_err(|err| err.with_context(&self.name, &format!("headers.{k}")))?;
583                    expanded_headers.insert(k.clone(), expanded);
584                }
585                Ok(ServerTransport::Http {
586                    url,
587                    headers: expanded_headers,
588                })
589            }
590        }
591    }
592
593    /// Expands `${ENV_VAR}` references using process environment and blyte's env file.
594    pub fn resolve_transport_from_system(&self) -> Result<ServerTransport, McpConfigError> {
595        let lookup = EnvLookup::from_system()?;
596        self.resolve_transport(&lookup)
597    }
598
599    /// Expands `${ENV_VAR}` references in configured OAuth client settings, if any.
600    pub fn resolve_oauth(
601        &self,
602        env_lookup: &EnvLookup,
603    ) -> Result<Option<ResolvedOAuthClientConfig>, McpConfigError> {
604        match &self.config.oauth {
605            Some(oauth) if !oauth.is_empty() => Ok(Some(oauth.resolve(&self.name, env_lookup)?)),
606            _ => Ok(None),
607        }
608    }
609
610    /// Expands `${ENV_VAR}` references in configured OAuth client settings using system env.
611    pub fn resolve_oauth_from_system(
612        &self,
613    ) -> Result<Option<ResolvedOAuthClientConfig>, McpConfigError> {
614        let lookup = EnvLookup::from_system()?;
615        self.resolve_oauth(&lookup)
616    }
617}
618
619/// Errors returned while loading, validating, expanding, or saving MCP configuration.
620#[derive(Debug)]
621pub enum McpConfigError {
622    ConfigDirUnavailable,
623    Io {
624        path: PathBuf,
625        source: std::io::Error,
626    },
627    Parse {
628        path: PathBuf,
629        message: String,
630    },
631    InvalidServer {
632        name: String,
633        reason: String,
634    },
635    MissingEnvVar {
636        server: Option<String>,
637        field: Option<String>,
638        var: String,
639    },
640    InvalidEnvSyntax {
641        server: Option<String>,
642        field: Option<String>,
643        detail: String,
644    },
645    EnvFile(String),
646    DuplicateServer(String),
647    ServerNotFound(String),
648}
649
650impl McpConfigError {
651    fn with_context(self, server: &str, field: &str) -> Self {
652        match self {
653            Self::MissingEnvVar { var, .. } => Self::MissingEnvVar {
654                server: Some(server.to_string()),
655                field: Some(field.to_string()),
656                var,
657            },
658            Self::InvalidEnvSyntax { detail, .. } => Self::InvalidEnvSyntax {
659                server: Some(server.to_string()),
660                field: Some(field.to_string()),
661                detail,
662            },
663            other => other,
664        }
665    }
666}
667
668impl fmt::Display for McpConfigError {
669    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670        match self {
671            Self::ConfigDirUnavailable => {
672                write!(f, "cannot determine blyte config directory (neither XDG_CONFIG_HOME nor HOME is set)")
673            }
674            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
675            Self::Parse { path, message } => {
676                write!(f, "failed to parse {}: {message}", path.display())
677            }
678            Self::InvalidServer { name, reason } => {
679                write!(f, "invalid MCP server '{name}': {reason}")
680            }
681            Self::MissingEnvVar { server, field, var } => match (server, field) {
682                (Some(s), Some(fld)) => write!(
683                    f,
684                    "MCP server '{s}' ({fld}) references missing environment variable '${{{var}}}'"
685                ),
686                _ => write!(f, "missing environment variable '${{{var}}}'"),
687            },
688            Self::InvalidEnvSyntax {
689                server,
690                field,
691                detail,
692            } => match (server, field) {
693                (Some(s), Some(fld)) => {
694                    write!(
695                        f,
696                        "MCP server '{s}' ({fld}) has invalid variable syntax: {detail}"
697                    )
698                }
699                _ => write!(f, "invalid environment variable syntax: {detail}"),
700            },
701            Self::EnvFile(msg) => write!(f, "failed to load blyte env file: {msg}"),
702            Self::DuplicateServer(name) => {
703                write!(
704                    f,
705                    "MCP server '{name}' already exists (pass --replace to overwrite)"
706                )
707            }
708            Self::ServerNotFound(name) => write!(f, "MCP server '{name}' not found"),
709        }
710    }
711}
712
713impl std::error::Error for McpConfigError {}
714
715/// Source for `${ENV_VAR}` expansion combining process environment and blyte's env file.
716#[derive(Debug, Clone, Default)]
717pub struct EnvLookup {
718    process_env: Option<BTreeMap<String, String>>,
719    file_env: BTreeMap<String, String>,
720}
721
722impl EnvLookup {
723    /// Builds an `EnvLookup` reading from the live process environment and blyte's default env file.
724    pub fn from_system() -> Result<Self, McpConfigError> {
725        let mut file_env = BTreeMap::new();
726        if let Some(path) = crate::env_file::default_path() {
727            file_env = read_env_file_map(&path)?;
728        }
729        Ok(Self {
730            process_env: None,
731            file_env,
732        })
733    }
734
735    /// Builds an `EnvLookup` reading from live process environment and a specific env file path.
736    pub fn from_process_and_file(env_file_path: &Path) -> Result<Self, McpConfigError> {
737        let file_env = read_env_file_map(env_file_path)?;
738        Ok(Self {
739            process_env: None,
740            file_env,
741        })
742    }
743
744    /// Builds an isolated `EnvLookup` from explicit maps (useful for deterministic testing).
745    pub fn from_maps(
746        process_env: BTreeMap<String, String>,
747        file_env: BTreeMap<String, String>,
748    ) -> Self {
749        Self {
750            process_env: Some(process_env),
751            file_env,
752        }
753    }
754
755    /// Resolves a variable name: process environment takes precedence over env file.
756    pub fn get(&self, name: &str) -> Option<String> {
757        match &self.process_env {
758            Some(map) => {
759                if let Some(val) = map.get(name) {
760                    return Some(val.clone());
761                }
762            }
763            None => {
764                if let Ok(val) = std::env::var(name) {
765                    return Some(val);
766                }
767            }
768        }
769        self.file_env.get(name).cloned()
770    }
771}
772
773fn read_env_file_map(path: &Path) -> Result<BTreeMap<String, String>, McpConfigError> {
774    let meta = match std::fs::metadata(path) {
775        Ok(m) => m,
776        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
777        Err(e) => {
778            return Err(McpConfigError::Io {
779                path: path.to_path_buf(),
780                source: e,
781            });
782        }
783    };
784    #[cfg(unix)]
785    {
786        use std::os::unix::fs::PermissionsExt;
787        if meta.permissions().mode() & 0o077 != 0 {
788            return Err(McpConfigError::EnvFile(format!(
789                "{} can be read by other users, so it was not loaded; run: chmod 600 {}",
790                path.display(),
791                path.display()
792            )));
793        }
794    }
795    #[cfg(not(unix))]
796    let _ = meta;
797
798    let text = std::fs::read_to_string(path).map_err(|source| McpConfigError::Io {
799        path: path.to_path_buf(),
800        source,
801    })?;
802    let mut map = BTreeMap::new();
803    for (k, v) in crate::env_file::parse(&text) {
804        map.insert(k, v);
805    }
806    Ok(map)
807}
808
809/// Expands all `${ENV_VAR}` placeholders in `input` using `lookup`.
810/// Returns an error if syntax is malformed or any referenced variable is missing.
811pub fn expand_env_vars(input: &str, lookup: &EnvLookup) -> Result<String, McpConfigError> {
812    let mut out = String::with_capacity(input.len());
813    let mut rest = input;
814    while let Some(idx) = rest.find("${") {
815        out.push_str(&rest[..idx]);
816        let after_open = &rest[idx + 2..];
817        let Some(end) = after_open.find('}') else {
818            return Err(McpConfigError::InvalidEnvSyntax {
819                server: None,
820                field: None,
821                detail: format!("unclosed '${{' in '{input}'"),
822            });
823        };
824        let var_name = &after_open[..end];
825        if !is_valid_env_name(var_name) {
826            return Err(McpConfigError::InvalidEnvSyntax {
827                server: None,
828                field: None,
829                detail: format!("invalid environment variable name '${{{var_name}}}'"),
830            });
831        }
832        let value = lookup
833            .get(var_name)
834            .ok_or_else(|| McpConfigError::MissingEnvVar {
835                server: None,
836                field: None,
837                var: var_name.to_string(),
838            })?;
839        out.push_str(&value);
840        rest = &after_open[end + 1..];
841    }
842    out.push_str(rest);
843    Ok(out)
844}
845
846fn is_valid_env_name(name: &str) -> bool {
847    let mut chars = name.chars();
848    let Some(first) = chars.next() else {
849        return false;
850    };
851    (first.is_ascii_alphabetic() || first == '_')
852        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
853}
854
855/// Returns blyte's user configuration directory (`$XDG_CONFIG_HOME/blyte` or `~/.config/blyte`).
856pub fn user_config_dir() -> Result<PathBuf, McpConfigError> {
857    if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
858        return Ok(PathBuf::from(x).join("blyte"));
859    }
860    std::env::var_os("HOME")
861        .filter(|h| !h.is_empty())
862        .map(|h| PathBuf::from(h).join(".config/blyte"))
863        .ok_or(McpConfigError::ConfigDirUnavailable)
864}
865
866/// Returns the user-level MCP configuration file path (`<config_dir>/mcp.json`).
867pub fn user_config_path() -> Result<PathBuf, McpConfigError> {
868    Ok(user_config_dir()?.join("mcp.json"))
869}
870
871/// Returns the user-level project-server trust store path (`<config_dir>/mcp-trust.json`).
872pub fn trust_store_path() -> Result<PathBuf, McpConfigError> {
873    Ok(user_config_dir()?.join("mcp-trust.json"))
874}
875
876/// Returns the project-level `.mcp.json` path under `project_root`.
877pub fn project_config_path(project_root: &Path) -> PathBuf {
878    project_root.join(".mcp.json")
879}
880
881/// Loads a single `mcp.json` or `.mcp.json` file.
882/// A missing file returns an empty configuration; unreadable or malformed files return an error.
883pub fn load_config_file(path: &Path) -> Result<McpConfigFile, McpConfigError> {
884    let text = match std::fs::read_to_string(path) {
885        Ok(s) => s,
886        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(McpConfigFile::default()),
887        Err(source) => {
888            return Err(McpConfigError::Io {
889                path: path.to_path_buf(),
890                source,
891            });
892        }
893    };
894    let parsed: McpConfigFile = serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
895        path: path.to_path_buf(),
896        message: e.to_string(),
897    })?;
898    for (name, cfg) in &parsed.mcp_servers {
899        if name.trim().is_empty() {
900            return Err(McpConfigError::InvalidServer {
901                name: name.clone(),
902                reason: "server name cannot be empty".to_string(),
903            });
904        }
905        cfg.resolve_transport_kind(name)?;
906    }
907    Ok(parsed)
908}
909
910/// Writes `config` to `path` with mode `0600` on Unix, creating parent directories if needed.
911pub fn save_config_file(path: &Path, config: &McpConfigFile) -> Result<(), McpConfigError> {
912    let mut rendered = serde_json::to_string_pretty(config).map_err(|e| McpConfigError::Parse {
913        path: path.to_path_buf(),
914        message: e.to_string(),
915    })?;
916    rendered.push('\n');
917    write_restricted_file(path, rendered.as_bytes())
918}
919
920fn write_restricted_file(path: &Path, bytes: &[u8]) -> Result<(), McpConfigError> {
921    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
922        std::fs::create_dir_all(parent).map_err(|source| McpConfigError::Io {
923            path: parent.to_path_buf(),
924            source,
925        })?;
926    }
927
928    #[cfg(unix)]
929    {
930        use std::io::Write;
931        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
932        let mut file = std::fs::OpenOptions::new()
933            .write(true)
934            .create(true)
935            .truncate(true)
936            .mode(0o600)
937            .open(path)
938            .map_err(|source| McpConfigError::Io {
939                path: path.to_path_buf(),
940                source,
941            })?;
942        file.write_all(bytes).map_err(|source| McpConfigError::Io {
943            path: path.to_path_buf(),
944            source,
945        })?;
946        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
947            |source| McpConfigError::Io {
948                path: path.to_path_buf(),
949                source,
950            },
951        )?;
952    }
953    #[cfg(not(unix))]
954    {
955        std::fs::write(path, bytes).map_err(|source| McpConfigError::Io {
956            path: path.to_path_buf(),
957            source,
958        })?;
959    }
960
961    Ok(())
962}
963
964/// Persistent record of explicitly approved project-level MCP servers.
965#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
966pub struct ProjectTrustStore {
967    #[serde(default)]
968    pub projects: BTreeMap<String, BTreeMap<String, String>>,
969}
970
971impl ProjectTrustStore {
972    /// Loads the trust store from `path`. Missing file means no trusted project servers.
973    pub fn load(path: &Path) -> Result<Self, McpConfigError> {
974        let text = match std::fs::read_to_string(path) {
975            Ok(s) => s,
976            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Self::default()),
977            Err(source) => {
978                return Err(McpConfigError::Io {
979                    path: path.to_path_buf(),
980                    source,
981                });
982            }
983        };
984        serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
985            path: path.to_path_buf(),
986            message: e.to_string(),
987        })
988    }
989
990    /// Saves the trust store to `path` with mode `0600` on Unix.
991    pub fn save(&self, path: &Path) -> Result<(), McpConfigError> {
992        let mut rendered =
993            serde_json::to_string_pretty(self).map_err(|e| McpConfigError::Parse {
994                path: path.to_path_buf(),
995                message: e.to_string(),
996            })?;
997        rendered.push('\n');
998        write_restricted_file(path, rendered.as_bytes())
999    }
1000
1001    /// Checks whether `server_name` in `project_root` is explicitly trusted for its current config.
1002    pub fn is_trusted(
1003        &self,
1004        project_root: &Path,
1005        server_name: &str,
1006        config: &ServerConfig,
1007    ) -> Result<bool, McpConfigError> {
1008        let key = project_key(project_root)?;
1009        let expected = config.trust_fingerprint();
1010        Ok(self
1011            .projects
1012            .get(&key)
1013            .and_then(|servers| servers.get(server_name))
1014            .is_some_and(|stored| stored == &expected))
1015    }
1016
1017    /// Records explicit user approval for a project-level server's current configuration.
1018    pub fn trust(
1019        &mut self,
1020        project_root: &Path,
1021        server_name: &str,
1022        config: &ServerConfig,
1023    ) -> Result<(), McpConfigError> {
1024        let key = project_key(project_root)?;
1025        self.projects
1026            .entry(key)
1027            .or_default()
1028            .insert(server_name.to_string(), config.trust_fingerprint());
1029        Ok(())
1030    }
1031
1032    /// Revokes trust for a project-level server.
1033    pub fn revoke(
1034        &mut self,
1035        project_root: &Path,
1036        server_name: &str,
1037    ) -> Result<bool, McpConfigError> {
1038        let key = project_key(project_root)?;
1039        let Some(servers) = self.projects.get_mut(&key) else {
1040            return Ok(false);
1041        };
1042        let removed = servers.remove(server_name).is_some();
1043        if servers.is_empty() {
1044            self.projects.remove(&key);
1045        }
1046        Ok(removed)
1047    }
1048}
1049
1050fn project_key(project_root: &Path) -> Result<String, McpConfigError> {
1051    let canonical = std::fs::canonicalize(project_root).map_err(|source| McpConfigError::Io {
1052        path: project_root.to_path_buf(),
1053        source,
1054    })?;
1055    Ok(canonical.to_string_lossy().into_owned())
1056}
1057
1058/// Loads all configured servers from user config and optional project `.mcp.json`,
1059/// tagging each with its source and trust status.
1060/// User servers are always trusted; project servers default to untrusted unless present
1061/// with a matching fingerprint in `trust_path`.
1062pub fn load_configured_servers(
1063    user_path: &Path,
1064    project_root: Option<&Path>,
1065    trust_path: &Path,
1066) -> Result<Vec<ConfiguredServer>, McpConfigError> {
1067    let user_file = load_config_file(user_path)?;
1068    let mut servers = Vec::new();
1069    let mut seen_names = std::collections::BTreeSet::new();
1070
1071    for (name, config) in user_file.mcp_servers {
1072        let transport_kind = config.resolve_transport_kind(&name)?;
1073        seen_names.insert(name.clone());
1074        servers.push(ConfiguredServer {
1075            name,
1076            source: ServerSource::User,
1077            source_path: user_path.to_path_buf(),
1078            enabled: config.enabled,
1079            approval: config.approval,
1080            trusted: true,
1081            transport_kind,
1082            config,
1083        });
1084    }
1085
1086    if let Some(root) = project_root {
1087        let proj_path = project_config_path(root);
1088        let proj_file = load_config_file(&proj_path)?;
1089        if !proj_file.mcp_servers.is_empty() {
1090            let trust_store = ProjectTrustStore::load(trust_path)?;
1091            for (name, config) in proj_file.mcp_servers {
1092                if seen_names.contains(&name) {
1093                    continue;
1094                }
1095                let transport_kind = config.resolve_transport_kind(&name)?;
1096                let trusted = trust_store.is_trusted(root, &name, &config)?;
1097                servers.push(ConfiguredServer {
1098                    name,
1099                    source: ServerSource::Project,
1100                    source_path: proj_path.clone(),
1101                    enabled: config.enabled,
1102                    approval: config.approval,
1103                    trusted,
1104                    transport_kind,
1105                    config,
1106                });
1107            }
1108        }
1109    }
1110
1111    servers.sort_by(|a, b| a.name.cmp(&b.name));
1112    Ok(servers)
1113}
1114
1115/// Adds or replaces a server entry in `user_path`.
1116pub fn add_user_server(
1117    user_path: &Path,
1118    name: &str,
1119    config: ServerConfig,
1120    replace: bool,
1121) -> Result<(), McpConfigError> {
1122    validate_server_name(name)?;
1123    config.resolve_transport_kind(name)?;
1124    let mut file = load_config_file(user_path)?;
1125    if !replace && file.mcp_servers.contains_key(name) {
1126        return Err(McpConfigError::DuplicateServer(name.to_string()));
1127    }
1128    file.mcp_servers.insert(name.to_string(), config);
1129    save_config_file(user_path, &file)
1130}
1131
1132/// Removes a server entry from `user_path`. Returns `ServerNotFound` if absent.
1133pub fn remove_user_server(user_path: &Path, name: &str) -> Result<(), McpConfigError> {
1134    let mut file = load_config_file(user_path)?;
1135    if file.mcp_servers.remove(name).is_none() {
1136        return Err(McpConfigError::ServerNotFound(name.to_string()));
1137    }
1138    save_config_file(user_path, &file)
1139}
1140
1141/// Validates a server name for `blyte mcp add`.
1142pub fn validate_server_name(name: &str) -> Result<(), McpConfigError> {
1143    if name.trim().is_empty() {
1144        return Err(McpConfigError::InvalidServer {
1145            name: name.to_string(),
1146            reason: "server name cannot be empty".to_string(),
1147        });
1148    }
1149    if name.chars().any(|c| c.is_whitespace()) {
1150        return Err(McpConfigError::InvalidServer {
1151            name: name.to_string(),
1152            reason: "server name cannot contain whitespace".to_string(),
1153        });
1154    }
1155    if name.contains("__") {
1156        return Err(McpConfigError::InvalidServer {
1157            name: name.to_string(),
1158            reason: "server name cannot contain '__'".to_string(),
1159        });
1160    }
1161    Ok(())
1162}