use std::collections::BTreeMap;
use std::fmt;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
#[value(rename_all = "lowercase")]
pub enum TransportKind {
Stdio,
#[serde(alias = "streamable-http", alias = "streamable_http")]
Http,
}
impl TransportKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::Stdio => "stdio",
Self::Http => "http",
}
}
}
impl fmt::Display for TransportKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalPolicy {
#[default]
#[value(name = "read_only")]
ReadOnly,
#[value(name = "auto")]
Auto,
#[value(name = "ask")]
Ask,
}
impl ApprovalPolicy {
pub fn as_str(&self) -> &'static str {
match self {
Self::ReadOnly => "read_only",
Self::Auto => "auto",
Self::Ask => "ask",
}
}
}
impl fmt::Display for ApprovalPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServerSource {
User,
Project,
}
impl ServerSource {
pub fn as_str(&self) -> &'static str {
match self {
Self::User => "user",
Self::Project => "project",
}
}
}
impl fmt::Display for ServerSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
fn default_enabled() -> bool {
true
}
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OAuthClientConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub callback_port: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scopes: Option<Vec<String>>,
}
impl fmt::Debug for OAuthClientConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OAuthClientConfig")
.field("client_id", &self.client_id)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| "<redacted>"),
)
.field("callback_port", &self.callback_port)
.field("scopes", &self.scopes)
.finish()
}
}
#[derive(Clone, Default, PartialEq, Eq)]
pub struct ResolvedOAuthClientConfig {
pub client_id: Option<String>,
pub client_secret: Option<String>,
pub callback_port: Option<u16>,
pub scopes: Option<Vec<String>>,
}
impl fmt::Debug for ResolvedOAuthClientConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResolvedOAuthClientConfig")
.field("client_id", &self.client_id)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| "<redacted>"),
)
.field("callback_port", &self.callback_port)
.field("scopes", &self.scopes)
.finish()
}
}
impl OAuthClientConfig {
pub fn is_empty(&self) -> bool {
self.client_id
.as_deref()
.is_none_or(|s| s.trim().is_empty())
&& self
.client_secret
.as_deref()
.is_none_or(|s| s.trim().is_empty())
&& self.callback_port.is_none()
&& self
.scopes
.as_ref()
.is_none_or(|scopes| scopes.iter().all(|s| s.trim().is_empty()))
}
pub fn normalized(self) -> Option<Self> {
let client_id = self
.client_id
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let client_secret = self
.client_secret
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let scopes = self
.scopes
.map(|items| {
let mut seen = std::collections::BTreeSet::new();
let mut cleaned = Vec::new();
for item in items {
let trimmed = item.trim();
if !trimmed.is_empty() && seen.insert(trimmed.to_string()) {
cleaned.push(trimmed.to_string());
}
}
cleaned
})
.filter(|items| !items.is_empty());
let out = Self {
client_id,
client_secret,
callback_port: self.callback_port,
scopes,
};
if out.is_empty() {
None
} else {
Some(out)
}
}
pub fn validate(&self, server_name: &str) -> Result<(), McpConfigError> {
if self.callback_port == Some(0) {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "oauth.callback_port must be between 1 and 65535".to_string(),
});
}
Ok(())
}
pub fn has_client_secret(&self) -> bool {
self.client_secret
.as_deref()
.is_some_and(|s| !s.trim().is_empty())
}
pub fn resolve(
&self,
server_name: &str,
env_lookup: &EnvLookup,
) -> Result<ResolvedOAuthClientConfig, McpConfigError> {
let client_id = match self.client_id.as_deref() {
Some(raw) if !raw.trim().is_empty() => {
let expanded = expand_env_vars(raw.trim(), env_lookup)
.map_err(|err| err.with_context(server_name, "oauth.client_id"))?;
let trimmed = expanded.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
_ => None,
};
let client_secret = match self.client_secret.as_deref() {
Some(raw) if !raw.trim().is_empty() => {
let expanded = expand_env_vars(raw.trim(), env_lookup)
.map_err(|err| err.with_context(server_name, "oauth.client_secret"))?;
let trimmed = expanded.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
_ => None,
};
let scopes = self
.scopes
.as_ref()
.map(|items| {
items
.iter()
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(String::from)
.collect::<Vec<_>>()
})
.filter(|items| !items.is_empty());
Ok(ResolvedOAuthClientConfig {
client_id,
client_secret,
callback_port: self.callback_port,
scopes,
})
}
pub fn resolve_from_system(
&self,
server_name: &str,
) -> Result<ResolvedOAuthClientConfig, McpConfigError> {
let lookup = EnvLookup::from_system()?;
self.resolve(server_name, &lookup)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerConfig {
#[serde(default, skip_serializing_if = "Option::is_none", alias = "type")]
pub transport: Option<TransportKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub headers: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oauth: Option<OAuthClientConfig>,
#[serde(default = "default_enabled")]
pub enabled: bool,
#[serde(default)]
pub approval: ApprovalPolicy,
}
impl ServerConfig {
pub fn stdio(
command: impl Into<String>,
args: Vec<String>,
env: BTreeMap<String, String>,
approval: ApprovalPolicy,
) -> Self {
Self {
transport: Some(TransportKind::Stdio),
command: Some(command.into()),
args,
env,
url: None,
headers: BTreeMap::new(),
oauth: None,
enabled: true,
approval,
}
}
pub fn http(
url: impl Into<String>,
headers: BTreeMap<String, String>,
approval: ApprovalPolicy,
) -> Self {
Self {
transport: Some(TransportKind::Http),
command: None,
args: Vec::new(),
env: BTreeMap::new(),
url: Some(url.into()),
headers,
oauth: None,
enabled: true,
approval,
}
}
pub fn with_oauth(mut self, oauth: Option<OAuthClientConfig>) -> Self {
self.oauth = oauth.and_then(OAuthClientConfig::normalized);
self
}
pub fn resolve_transport_kind(
&self,
server_name: &str,
) -> Result<TransportKind, McpConfigError> {
let has_command = self
.command
.as_deref()
.is_some_and(|c| !c.trim().is_empty());
let has_url = self.url.as_deref().is_some_and(|u| !u.trim().is_empty());
let kind = match self.transport {
Some(TransportKind::Stdio) => {
if !has_command {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "stdio server must specify a non-empty 'command'".to_string(),
});
}
if has_url {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "stdio server cannot also specify 'url'".to_string(),
});
}
TransportKind::Stdio
}
Some(TransportKind::Http) => {
if !has_url {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "http server must specify a non-empty 'url'".to_string(),
});
}
if has_command {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "http server cannot also specify 'command'".to_string(),
});
}
TransportKind::Http
}
None => match (has_command, has_url) {
(true, true) => {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "server specifies both 'command' and 'url'; remove one or set 'transport'".to_string(),
});
}
(true, false) => TransportKind::Stdio,
(false, true) => TransportKind::Http,
(false, false) => {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "server must specify either 'command' or 'url'".to_string(),
});
}
},
};
if kind == TransportKind::Http {
let url = self.url.as_deref().unwrap_or("");
if !url.starts_with("http://") && !url.starts_with("https://") {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: format!("http server url must start with http:// or https://: {url}"),
});
}
if let Some(oauth) = &self.oauth {
if oauth.callback_port == Some(0) {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "oauth.callback_port must be between 1 and 65535".to_string(),
});
}
}
} else if self.oauth.as_ref().is_some_and(|o| !o.is_empty()) {
return Err(McpConfigError::InvalidServer {
name: server_name.to_string(),
reason: "stdio server cannot specify 'oauth'".to_string(),
});
}
Ok(kind)
}
pub fn trust_fingerprint(&self) -> String {
let mut hasher = Sha256::new();
let update_str = |h: &mut Sha256, s: &str| {
h.update((s.len() as u64).to_be_bytes());
h.update(s.as_bytes());
};
let update_opt_str = |h: &mut Sha256, opt: Option<&str>| match opt {
Some(s) => {
h.update([1u8]);
update_str(h, s);
}
None => h.update([0u8]),
};
update_opt_str(&mut hasher, self.transport.map(|t| t.as_str()));
update_opt_str(&mut hasher, self.command.as_deref());
hasher.update((self.args.len() as u64).to_be_bytes());
for arg in &self.args {
update_str(&mut hasher, arg);
}
hasher.update((self.env.len() as u64).to_be_bytes());
for (k, v) in &self.env {
update_str(&mut hasher, k);
update_str(&mut hasher, v);
}
update_opt_str(&mut hasher, self.url.as_deref());
hasher.update((self.headers.len() as u64).to_be_bytes());
for (k, v) in &self.headers {
update_str(&mut hasher, k);
update_str(&mut hasher, v);
}
update_str(&mut hasher, self.approval.as_str());
if let Some(oauth) = &self.oauth {
if !oauth.is_empty() {
hasher.update([1u8]);
update_opt_str(&mut hasher, oauth.client_id.as_deref());
update_opt_str(&mut hasher, oauth.client_secret.as_deref());
match oauth.callback_port {
Some(port) => {
hasher.update([1u8]);
hasher.update(port.to_be_bytes());
}
None => hasher.update([0u8]),
}
match &oauth.scopes {
Some(scopes) => {
hasher.update([1u8]);
hasher.update((scopes.len() as u64).to_be_bytes());
for scope in scopes {
update_str(&mut hasher, scope);
}
}
None => hasher.update([0u8]),
}
}
}
let digest = hasher.finalize();
format!("{digest:x}")
}
pub fn target_display(&self) -> String {
if let Some(url) = &self.url {
return url.clone();
}
if let Some(cmd) = &self.command {
if self.args.is_empty() {
return cmd.clone();
}
return format!("{cmd} {}", self.args.join(" "));
}
String::new()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct McpConfigFile {
#[serde(rename = "mcpServers", default)]
pub mcp_servers: BTreeMap<String, ServerConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerTransport {
Stdio {
command: String,
args: Vec<String>,
env: BTreeMap<String, String>,
},
Http {
url: String,
headers: BTreeMap<String, String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguredServer {
pub name: String,
pub source: ServerSource,
pub source_path: PathBuf,
pub enabled: bool,
pub approval: ApprovalPolicy,
pub trusted: bool,
pub transport_kind: TransportKind,
pub config: ServerConfig,
}
impl ConfiguredServer {
pub fn resolve_transport(
&self,
env_lookup: &EnvLookup,
) -> Result<ServerTransport, McpConfigError> {
match self.transport_kind {
TransportKind::Stdio => {
let command =
self.config
.command
.clone()
.ok_or_else(|| McpConfigError::InvalidServer {
name: self.name.clone(),
reason: "stdio server missing 'command'".to_string(),
})?;
let mut expanded_env = BTreeMap::new();
for (k, v) in &self.config.env {
let expanded = expand_env_vars(v, env_lookup)
.map_err(|err| err.with_context(&self.name, &format!("env.{k}")))?;
expanded_env.insert(k.clone(), expanded);
}
Ok(ServerTransport::Stdio {
command,
args: self.config.args.clone(),
env: expanded_env,
})
}
TransportKind::Http => {
let url = self
.config
.url
.clone()
.ok_or_else(|| McpConfigError::InvalidServer {
name: self.name.clone(),
reason: "http server missing 'url'".to_string(),
})?;
let mut expanded_headers = BTreeMap::new();
for (k, v) in &self.config.headers {
let expanded = expand_env_vars(v, env_lookup)
.map_err(|err| err.with_context(&self.name, &format!("headers.{k}")))?;
expanded_headers.insert(k.clone(), expanded);
}
Ok(ServerTransport::Http {
url,
headers: expanded_headers,
})
}
}
}
pub fn resolve_transport_from_system(&self) -> Result<ServerTransport, McpConfigError> {
let lookup = EnvLookup::from_system()?;
self.resolve_transport(&lookup)
}
pub fn resolve_oauth(
&self,
env_lookup: &EnvLookup,
) -> Result<Option<ResolvedOAuthClientConfig>, McpConfigError> {
match &self.config.oauth {
Some(oauth) if !oauth.is_empty() => Ok(Some(oauth.resolve(&self.name, env_lookup)?)),
_ => Ok(None),
}
}
pub fn resolve_oauth_from_system(
&self,
) -> Result<Option<ResolvedOAuthClientConfig>, McpConfigError> {
let lookup = EnvLookup::from_system()?;
self.resolve_oauth(&lookup)
}
}
#[derive(Debug)]
pub enum McpConfigError {
ConfigDirUnavailable,
Io {
path: PathBuf,
source: std::io::Error,
},
Parse {
path: PathBuf,
message: String,
},
InvalidServer {
name: String,
reason: String,
},
MissingEnvVar {
server: Option<String>,
field: Option<String>,
var: String,
},
InvalidEnvSyntax {
server: Option<String>,
field: Option<String>,
detail: String,
},
EnvFile(String),
DuplicateServer(String),
ServerNotFound(String),
}
impl McpConfigError {
fn with_context(self, server: &str, field: &str) -> Self {
match self {
Self::MissingEnvVar { var, .. } => Self::MissingEnvVar {
server: Some(server.to_string()),
field: Some(field.to_string()),
var,
},
Self::InvalidEnvSyntax { detail, .. } => Self::InvalidEnvSyntax {
server: Some(server.to_string()),
field: Some(field.to_string()),
detail,
},
other => other,
}
}
}
impl fmt::Display for McpConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ConfigDirUnavailable => {
write!(f, "cannot determine blyte config directory (neither XDG_CONFIG_HOME nor HOME is set)")
}
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Parse { path, message } => {
write!(f, "failed to parse {}: {message}", path.display())
}
Self::InvalidServer { name, reason } => {
write!(f, "invalid MCP server '{name}': {reason}")
}
Self::MissingEnvVar { server, field, var } => match (server, field) {
(Some(s), Some(fld)) => write!(
f,
"MCP server '{s}' ({fld}) references missing environment variable '${{{var}}}'"
),
_ => write!(f, "missing environment variable '${{{var}}}'"),
},
Self::InvalidEnvSyntax {
server,
field,
detail,
} => match (server, field) {
(Some(s), Some(fld)) => {
write!(
f,
"MCP server '{s}' ({fld}) has invalid variable syntax: {detail}"
)
}
_ => write!(f, "invalid environment variable syntax: {detail}"),
},
Self::EnvFile(msg) => write!(f, "failed to load blyte env file: {msg}"),
Self::DuplicateServer(name) => {
write!(
f,
"MCP server '{name}' already exists (pass --replace to overwrite)"
)
}
Self::ServerNotFound(name) => write!(f, "MCP server '{name}' not found"),
}
}
}
impl std::error::Error for McpConfigError {}
#[derive(Debug, Clone, Default)]
pub struct EnvLookup {
process_env: Option<BTreeMap<String, String>>,
file_env: BTreeMap<String, String>,
}
impl EnvLookup {
pub fn from_system() -> Result<Self, McpConfigError> {
let mut file_env = BTreeMap::new();
if let Some(path) = crate::env_file::default_path() {
file_env = read_env_file_map(&path)?;
}
Ok(Self {
process_env: None,
file_env,
})
}
pub fn from_process_and_file(env_file_path: &Path) -> Result<Self, McpConfigError> {
let file_env = read_env_file_map(env_file_path)?;
Ok(Self {
process_env: None,
file_env,
})
}
pub fn from_maps(
process_env: BTreeMap<String, String>,
file_env: BTreeMap<String, String>,
) -> Self {
Self {
process_env: Some(process_env),
file_env,
}
}
pub fn get(&self, name: &str) -> Option<String> {
match &self.process_env {
Some(map) => {
if let Some(val) = map.get(name) {
return Some(val.clone());
}
}
None => {
if let Ok(val) = std::env::var(name) {
return Some(val);
}
}
}
self.file_env.get(name).cloned()
}
}
fn read_env_file_map(path: &Path) -> Result<BTreeMap<String, String>, McpConfigError> {
let meta = match std::fs::metadata(path) {
Ok(m) => m,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => {
return Err(McpConfigError::Io {
path: path.to_path_buf(),
source: e,
});
}
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o077 != 0 {
return Err(McpConfigError::EnvFile(format!(
"{} can be read by other users, so it was not loaded; run: chmod 600 {}",
path.display(),
path.display()
)));
}
}
#[cfg(not(unix))]
let _ = meta;
let text = std::fs::read_to_string(path).map_err(|source| McpConfigError::Io {
path: path.to_path_buf(),
source,
})?;
let mut map = BTreeMap::new();
for (k, v) in crate::env_file::parse(&text) {
map.insert(k, v);
}
Ok(map)
}
pub fn expand_env_vars(input: &str, lookup: &EnvLookup) -> Result<String, McpConfigError> {
let mut out = String::with_capacity(input.len());
let mut rest = input;
while let Some(idx) = rest.find("${") {
out.push_str(&rest[..idx]);
let after_open = &rest[idx + 2..];
let Some(end) = after_open.find('}') else {
return Err(McpConfigError::InvalidEnvSyntax {
server: None,
field: None,
detail: format!("unclosed '${{' in '{input}'"),
});
};
let var_name = &after_open[..end];
if !is_valid_env_name(var_name) {
return Err(McpConfigError::InvalidEnvSyntax {
server: None,
field: None,
detail: format!("invalid environment variable name '${{{var_name}}}'"),
});
}
let value = lookup
.get(var_name)
.ok_or_else(|| McpConfigError::MissingEnvVar {
server: None,
field: None,
var: var_name.to_string(),
})?;
out.push_str(&value);
rest = &after_open[end + 1..];
}
out.push_str(rest);
Ok(out)
}
fn is_valid_env_name(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
(first.is_ascii_alphabetic() || first == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
pub fn user_config_dir() -> Result<PathBuf, McpConfigError> {
if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
return Ok(PathBuf::from(x).join("blyte"));
}
std::env::var_os("HOME")
.filter(|h| !h.is_empty())
.map(|h| PathBuf::from(h).join(".config/blyte"))
.ok_or(McpConfigError::ConfigDirUnavailable)
}
pub fn user_config_path() -> Result<PathBuf, McpConfigError> {
Ok(user_config_dir()?.join("mcp.json"))
}
pub fn trust_store_path() -> Result<PathBuf, McpConfigError> {
Ok(user_config_dir()?.join("mcp-trust.json"))
}
pub fn project_config_path(project_root: &Path) -> PathBuf {
project_root.join(".mcp.json")
}
pub fn load_config_file(path: &Path) -> Result<McpConfigFile, McpConfigError> {
let text = match std::fs::read_to_string(path) {
Ok(s) => s,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(McpConfigFile::default()),
Err(source) => {
return Err(McpConfigError::Io {
path: path.to_path_buf(),
source,
});
}
};
let parsed: McpConfigFile = serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
})?;
for (name, cfg) in &parsed.mcp_servers {
if name.trim().is_empty() {
return Err(McpConfigError::InvalidServer {
name: name.clone(),
reason: "server name cannot be empty".to_string(),
});
}
cfg.resolve_transport_kind(name)?;
}
Ok(parsed)
}
pub fn save_config_file(path: &Path, config: &McpConfigFile) -> Result<(), McpConfigError> {
let mut rendered = serde_json::to_string_pretty(config).map_err(|e| McpConfigError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
})?;
rendered.push('\n');
write_restricted_file(path, rendered.as_bytes())
}
fn write_restricted_file(path: &Path, bytes: &[u8]) -> Result<(), McpConfigError> {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|source| McpConfigError::Io {
path: parent.to_path_buf(),
source,
})?;
}
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)
.map_err(|source| McpConfigError::Io {
path: path.to_path_buf(),
source,
})?;
file.write_all(bytes).map_err(|source| McpConfigError::Io {
path: path.to_path_buf(),
source,
})?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
|source| McpConfigError::Io {
path: path.to_path_buf(),
source,
},
)?;
}
#[cfg(not(unix))]
{
std::fs::write(path, bytes).map_err(|source| McpConfigError::Io {
path: path.to_path_buf(),
source,
})?;
}
Ok(())
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectTrustStore {
#[serde(default)]
pub projects: BTreeMap<String, BTreeMap<String, String>>,
}
impl ProjectTrustStore {
pub fn load(path: &Path) -> Result<Self, McpConfigError> {
let text = match std::fs::read_to_string(path) {
Ok(s) => s,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Self::default()),
Err(source) => {
return Err(McpConfigError::Io {
path: path.to_path_buf(),
source,
});
}
};
serde_json::from_str(&text).map_err(|e| McpConfigError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
})
}
pub fn save(&self, path: &Path) -> Result<(), McpConfigError> {
let mut rendered =
serde_json::to_string_pretty(self).map_err(|e| McpConfigError::Parse {
path: path.to_path_buf(),
message: e.to_string(),
})?;
rendered.push('\n');
write_restricted_file(path, rendered.as_bytes())
}
pub fn is_trusted(
&self,
project_root: &Path,
server_name: &str,
config: &ServerConfig,
) -> Result<bool, McpConfigError> {
let key = project_key(project_root)?;
let expected = config.trust_fingerprint();
Ok(self
.projects
.get(&key)
.and_then(|servers| servers.get(server_name))
.is_some_and(|stored| stored == &expected))
}
pub fn trust(
&mut self,
project_root: &Path,
server_name: &str,
config: &ServerConfig,
) -> Result<(), McpConfigError> {
let key = project_key(project_root)?;
self.projects
.entry(key)
.or_default()
.insert(server_name.to_string(), config.trust_fingerprint());
Ok(())
}
pub fn revoke(
&mut self,
project_root: &Path,
server_name: &str,
) -> Result<bool, McpConfigError> {
let key = project_key(project_root)?;
let Some(servers) = self.projects.get_mut(&key) else {
return Ok(false);
};
let removed = servers.remove(server_name).is_some();
if servers.is_empty() {
self.projects.remove(&key);
}
Ok(removed)
}
}
fn project_key(project_root: &Path) -> Result<String, McpConfigError> {
let canonical = std::fs::canonicalize(project_root).map_err(|source| McpConfigError::Io {
path: project_root.to_path_buf(),
source,
})?;
Ok(canonical.to_string_lossy().into_owned())
}
pub fn load_configured_servers(
user_path: &Path,
project_root: Option<&Path>,
trust_path: &Path,
) -> Result<Vec<ConfiguredServer>, McpConfigError> {
let user_file = load_config_file(user_path)?;
let mut servers = Vec::new();
let mut seen_names = std::collections::BTreeSet::new();
for (name, config) in user_file.mcp_servers {
let transport_kind = config.resolve_transport_kind(&name)?;
seen_names.insert(name.clone());
servers.push(ConfiguredServer {
name,
source: ServerSource::User,
source_path: user_path.to_path_buf(),
enabled: config.enabled,
approval: config.approval,
trusted: true,
transport_kind,
config,
});
}
if let Some(root) = project_root {
let proj_path = project_config_path(root);
let proj_file = load_config_file(&proj_path)?;
if !proj_file.mcp_servers.is_empty() {
let trust_store = ProjectTrustStore::load(trust_path)?;
for (name, config) in proj_file.mcp_servers {
if seen_names.contains(&name) {
continue;
}
let transport_kind = config.resolve_transport_kind(&name)?;
let trusted = trust_store.is_trusted(root, &name, &config)?;
servers.push(ConfiguredServer {
name,
source: ServerSource::Project,
source_path: proj_path.clone(),
enabled: config.enabled,
approval: config.approval,
trusted,
transport_kind,
config,
});
}
}
}
servers.sort_by(|a, b| a.name.cmp(&b.name));
Ok(servers)
}
pub fn add_user_server(
user_path: &Path,
name: &str,
config: ServerConfig,
replace: bool,
) -> Result<(), McpConfigError> {
validate_server_name(name)?;
config.resolve_transport_kind(name)?;
let mut file = load_config_file(user_path)?;
if !replace && file.mcp_servers.contains_key(name) {
return Err(McpConfigError::DuplicateServer(name.to_string()));
}
file.mcp_servers.insert(name.to_string(), config);
save_config_file(user_path, &file)
}
pub fn remove_user_server(user_path: &Path, name: &str) -> Result<(), McpConfigError> {
let mut file = load_config_file(user_path)?;
if file.mcp_servers.remove(name).is_none() {
return Err(McpConfigError::ServerNotFound(name.to_string()));
}
save_config_file(user_path, &file)
}
pub fn validate_server_name(name: &str) -> Result<(), McpConfigError> {
if name.trim().is_empty() {
return Err(McpConfigError::InvalidServer {
name: name.to_string(),
reason: "server name cannot be empty".to_string(),
});
}
if name.chars().any(|c| c.is_whitespace()) {
return Err(McpConfigError::InvalidServer {
name: name.to_string(),
reason: "server name cannot contain whitespace".to_string(),
});
}
if name.contains("__") {
return Err(McpConfigError::InvalidServer {
name: name.to_string(),
reason: "server name cannot contain '__'".to_string(),
});
}
Ok(())
}