use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use blyte_agent::approval::{Approval, Approver};
use blyte_agent::redact::Redactor;
use blyte_agent::tools::{McpToolAccess, ToolOutcome};
use blyte_provider::ToolSpec;
use serde::Serialize;
use serde_json::{json, Value};
use super::client::McpClient;
use super::config::{
add_user_server, load_config_file, load_configured_servers, remove_user_server,
save_config_file, trust_store_path, user_config_path, ApprovalPolicy, ConfiguredServer,
EnvLookup, OAuthClientConfig, ProjectTrustStore, ServerConfig, ServerSource, ServerTransport,
TransportKind,
};
use super::oauth::{
logout_server as oauth_logout_server, prepare_oauth_flow_with_config,
refresh_access_token_with_config, resolve_bearer_token_with_config, McpAuthStore,
DEFAULT_CALLBACK_TIMEOUT, DEFAULT_OAUTH_HTTP_TIMEOUT,
};
use super::protocol::{McpError, Tool, ToolCallResult};
const BUILTIN_TOOL_NAMES: &[&str] = &[
"read", "write", "edit", "bash", "glob", "grep", "blyte", "surfaces", "tell", "publish",
"land", "dispatch",
];
const APPROVAL_ARGS_DISPLAY_MAX_CHARS: usize = 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", content = "message", rename_all = "snake_case")]
pub enum ServerStatus {
Connected,
NeedsAuth,
Disabled,
UntrustedProject,
Error(String),
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct McpToolInfo {
pub server: String,
pub name: String,
pub exposed_name: String,
pub description: Option<String>,
pub input_schema: Value,
pub read_only_hint: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct McpOAuthSnapshot {
pub client_id: Option<String>,
pub has_client_secret: bool,
pub callback_port: Option<u16>,
pub scopes: Option<Vec<String>>,
}
#[derive(Debug, Clone, Default)]
pub struct OAuthConfigPatch {
pub client_id: Option<String>,
pub client_secret: Option<String>,
pub clear_client_secret: bool,
pub callback_port: Option<u16>,
pub scopes: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct McpServerSnapshot {
pub name: String,
pub transport: String,
pub target: String,
pub source: ServerSource,
pub enabled: bool,
pub trusted: bool,
pub approval: ApprovalPolicy,
pub status: ServerStatus,
pub tools: Vec<McpToolInfo>,
pub auth_in_progress: bool,
pub oauth: Option<McpOAuthSnapshot>,
}
struct ManagedServer {
configured: ConfiguredServer,
status: ServerStatus,
client: Option<Arc<Mutex<McpClient>>>,
tools: Vec<McpToolInfo>,
last_www_authenticate: Option<String>,
auth_in_progress: bool,
generation: u64,
}
impl ManagedServer {
fn from_configured(configured: ConfiguredServer) -> Self {
let status = initial_status(&configured);
Self {
configured,
status,
client: None,
tools: Vec::new(),
last_www_authenticate: None,
auth_in_progress: false,
generation: 0,
}
}
fn is_live_connected(&self) -> bool {
self.configured.enabled
&& self.configured.trusted
&& matches!(self.status, ServerStatus::Connected)
&& self.client.is_some()
}
fn clear_connection(&mut self, status: ServerStatus) -> Option<Arc<Mutex<McpClient>>> {
let old = self.client.take();
self.tools.clear();
self.status = status;
old
}
fn snapshot(&self) -> McpServerSnapshot {
let oauth = self
.configured
.config
.oauth
.as_ref()
.map(|o| McpOAuthSnapshot {
client_id: o.client_id.clone(),
has_client_secret: o
.client_secret
.as_deref()
.is_some_and(|s| !s.trim().is_empty()),
callback_port: o.callback_port,
scopes: o.scopes.clone(),
});
McpServerSnapshot {
name: self.configured.name.clone(),
transport: self.configured.transport_kind.as_str().to_string(),
target: self.configured.config.target_display(),
source: self.configured.source,
enabled: self.configured.enabled,
trusted: self.configured.trusted,
approval: self.configured.approval,
status: self.status.clone(),
tools: if self.is_live_connected() {
self.tools.clone()
} else {
Vec::new()
},
auth_in_progress: self.auth_in_progress,
oauth,
}
}
}
fn initial_status(configured: &ConfiguredServer) -> ServerStatus {
if !configured.enabled {
ServerStatus::Disabled
} else if !configured.trusted {
ServerStatus::UntrustedProject
} else {
ServerStatus::Error("disconnected".to_string())
}
}
struct ManagerState {
servers: BTreeMap<String, ManagedServer>,
}
pub struct McpManager {
user_config_path: PathBuf,
project_root: Option<PathBuf>,
trust_store_path: PathBuf,
auth_store_path: PathBuf,
env_lookup: Option<EnvLookup>,
http_timeout: Duration,
callback_timeout: Duration,
state: Mutex<ManagerState>,
}
impl McpManager {
pub fn new(
user_config_path: PathBuf,
project_root: Option<PathBuf>,
trust_store_path: PathBuf,
auth_store_path: PathBuf,
) -> Result<Self, String> {
let configured = load_configured_servers(
&user_config_path,
project_root.as_deref(),
&trust_store_path,
)
.map_err(|e| e.to_string())?;
let mut servers = BTreeMap::new();
for srv in configured {
servers.insert(srv.name.clone(), ManagedServer::from_configured(srv));
}
Ok(Self {
user_config_path,
project_root,
trust_store_path,
auth_store_path,
env_lookup: None,
http_timeout: DEFAULT_OAUTH_HTTP_TIMEOUT,
callback_timeout: DEFAULT_CALLBACK_TIMEOUT,
state: Mutex::new(ManagerState { servers }),
})
}
pub fn from_default_paths(project_root: Option<&Path>) -> Result<Self, String> {
let user_path = user_config_path().map_err(|e| e.to_string())?;
let trust_path = trust_store_path().map_err(|e| e.to_string())?;
let auth_path = McpAuthStore::default_path().map_err(|e| e.to_string())?;
Self::new(
user_path,
project_root.map(Path::to_path_buf),
trust_path,
auth_path,
)
}
pub fn empty_in(base_dir: &Path) -> Self {
Self {
user_config_path: base_dir.join("mcp.json"),
project_root: None,
trust_store_path: base_dir.join("mcp-trust.json"),
auth_store_path: base_dir.join("mcp-auth.json"),
env_lookup: None,
http_timeout: DEFAULT_OAUTH_HTTP_TIMEOUT,
callback_timeout: DEFAULT_CALLBACK_TIMEOUT,
state: Mutex::new(ManagerState {
servers: BTreeMap::new(),
}),
}
}
pub fn with_env_lookup(mut self, lookup: EnvLookup) -> Self {
self.env_lookup = Some(lookup);
self
}
pub fn with_timeouts(mut self, http_timeout: Duration, callback_timeout: Duration) -> Self {
self.http_timeout = http_timeout;
self.callback_timeout = callback_timeout;
self
}
pub fn auth_store_path(&self) -> &Path {
&self.auth_store_path
}
pub fn user_config_path(&self) -> &Path {
&self.user_config_path
}
pub fn trust_store_path(&self) -> &Path {
&self.trust_store_path
}
fn configured_secret_pairs(&self) -> Vec<(String, String)> {
let mut extra_pairs = Vec::new();
if let Ok(guard) = self.state.lock() {
let lookup = self.resolve_env_lookup().ok();
for (name, srv) in &guard.servers {
for (k, v) in &srv.configured.config.headers {
if !v.is_empty() {
extra_pairs.push((format!("MCP_HEADER_{name}_{k}"), v.clone()));
}
if let Some(ref env_lookup) = lookup {
if let Ok(expanded) = crate::mcp::config::expand_env_vars(v, env_lookup) {
if !expanded.is_empty() {
extra_pairs.push((format!("MCP_HEADER_EXP_{name}_{k}"), expanded));
}
}
}
}
for (k, v) in &srv.configured.config.env {
if !v.is_empty() {
extra_pairs.push((format!("MCP_ENV_{name}_{k}"), v.clone()));
}
if let Some(ref env_lookup) = lookup {
if let Ok(expanded) = crate::mcp::config::expand_env_vars(v, env_lookup) {
if !expanded.is_empty() {
extra_pairs.push((format!("MCP_ENV_EXP_{name}_{k}"), expanded));
}
}
}
}
if let Some(secret) = srv
.configured
.config
.oauth
.as_ref()
.and_then(|o| o.client_secret.as_deref())
{
if !secret.is_empty() && !secret.contains("${") {
extra_pairs.push((format!("MCP_OAUTH_SECRET_{name}"), secret.to_string()));
}
if let Some(ref env_lookup) = lookup {
if let Ok(expanded) =
crate::mcp::config::expand_env_vars(secret, env_lookup)
{
if !expanded.is_empty() {
extra_pairs
.push((format!("MCP_OAUTH_SECRET_EXP_{name}"), expanded));
}
}
}
}
}
}
extra_pairs
}
pub fn redact_text(&self, text: &str, root: &Path) -> String {
let mut redacted = match apply_all_redactors(text, root, &self.auth_store_path) {
Ok(redacted) => redacted,
Err(e) => return format!("[redacted: {e}]"),
};
let extra_pairs = self.configured_secret_pairs();
if !extra_pairs.is_empty() {
redacted = Redactor::from_pairs(extra_pairs).apply(&redacted);
}
redacted
}
pub fn connect_all_in_background(self: &Arc<Self>) {
let names: Vec<String> = {
let guard = self.lock_state().unwrap_or_else(|e| panic!("{e}"));
guard
.servers
.values()
.filter(|s| s.configured.enabled && s.configured.trusted)
.map(|s| s.configured.name.clone())
.collect()
};
for name in names {
let manager = Arc::clone(self);
std::thread::spawn(move || {
let _ = manager.connect_server(&name);
});
}
}
pub fn connect_all(&self) {
let names: Vec<String> = {
let guard = self.lock_state().unwrap_or_else(|e| panic!("{e}"));
guard
.servers
.values()
.filter(|s| s.configured.enabled && s.configured.trusted)
.map(|s| s.configured.name.clone())
.collect()
};
for name in names {
let _ = self.connect_server(&name);
}
}
pub fn list_servers(&self) -> Vec<McpServerSnapshot> {
let guard = self.lock_state().unwrap_or_else(|e| panic!("{e}"));
guard
.servers
.values()
.map(ManagedServer::snapshot)
.collect()
}
pub fn get_server(&self, name: &str) -> Option<McpServerSnapshot> {
let guard = self.lock_state().unwrap_or_else(|e| panic!("{e}"));
guard.servers.get(name).map(ManagedServer::snapshot)
}
pub fn list_tools(&self) -> Vec<McpToolInfo> {
let guard = self.lock_state().unwrap_or_else(|e| panic!("{e}"));
let mut out = Vec::new();
for srv in guard.servers.values() {
if srv.is_live_connected() {
out.extend(srv.tools.iter().cloned());
}
}
out
}
pub fn connect_server(&self, name: &str) -> Result<McpServerSnapshot, String> {
let (configured, generation) = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
if !srv.configured.enabled {
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = false;
srv.client = None;
srv.tools.clear();
srv.status = ServerStatus::Disabled;
return Ok(srv.snapshot());
}
if !srv.configured.trusted {
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = false;
srv.client = None;
srv.tools.clear();
srv.status = ServerStatus::UntrustedProject;
return Ok(srv.snapshot());
}
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = false;
(srv.configured.clone(), srv.generation)
};
let outcome = self.establish_connection(&configured);
let mut guard = self.lock_state()?;
let existing = existing_exposed_names(&guard.servers, name);
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
if srv.generation != generation {
return Ok(srv.snapshot());
}
match outcome {
Ok((client, defs)) => {
srv.client = Some(Arc::new(Mutex::new(client)));
srv.status = ServerStatus::Connected;
srv.last_www_authenticate = None;
let assigned = assign_exposed_names(&srv.configured.name, &defs, &existing);
srv.tools = assigned;
}
Err(ConnectFailure::NeedsAuth(www_auth)) => {
srv.client = None;
srv.tools.clear();
srv.status = ServerStatus::NeedsAuth;
srv.last_www_authenticate = www_auth;
}
Err(ConnectFailure::Error(msg)) => {
srv.client = None;
srv.tools.clear();
srv.status = ServerStatus::Error(msg);
}
}
Ok(srv.snapshot())
}
pub fn reconnect_server(&self, name: &str) -> Result<McpServerSnapshot, String> {
let _ = self.disconnect_server(name)?;
self.connect_server(name)
}
pub fn disconnect_server(&self, name: &str) -> Result<McpServerSnapshot, String> {
let (old_client, snapshot) = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = false;
let old = srv.client.take();
srv.tools.clear();
srv.status = if !srv.configured.enabled {
ServerStatus::Disabled
} else if !srv.configured.trusted {
ServerStatus::UntrustedProject
} else {
ServerStatus::Error("disconnected".to_string())
};
(old, srv.snapshot())
};
drop(old_client);
Ok(snapshot)
}
pub fn set_enabled(&self, name: &str, enabled: bool) -> Result<McpServerSnapshot, String> {
let source = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
srv.configured.enabled = enabled;
srv.configured.config.enabled = enabled;
srv.configured.source
};
if source == ServerSource::User {
let mut file = load_config_file(&self.user_config_path).map_err(|e| e.to_string())?;
if let Some(entry) = file.mcp_servers.get_mut(name) {
entry.enabled = enabled;
save_config_file(&self.user_config_path, &file).map_err(|e| e.to_string())?;
}
}
if enabled {
self.connect_server(name)
} else {
self.disconnect_server(name)
}
}
pub fn set_approval_policy(
&self,
name: &str,
policy: ApprovalPolicy,
) -> Result<McpServerSnapshot, String> {
let (source, snapshot) = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
srv.configured.approval = policy;
srv.configured.config.approval = policy;
(srv.configured.source, srv.snapshot())
};
if source == ServerSource::User {
let mut file = load_config_file(&self.user_config_path).map_err(|e| e.to_string())?;
if let Some(entry) = file.mcp_servers.get_mut(name) {
entry.approval = policy;
save_config_file(&self.user_config_path, &file).map_err(|e| e.to_string())?;
}
}
Ok(snapshot)
}
pub fn trust_project_server(&self, name: &str) -> Result<McpServerSnapshot, String> {
let project_root = self
.project_root
.as_deref()
.ok_or_else(|| "no project root configured for this surface".to_string())?;
let config = {
let guard = self.lock_state()?;
let Some(srv) = guard.servers.get(name) else {
return Err(format!("MCP server '{name}' not found"));
};
if srv.configured.source != ServerSource::Project {
return Ok(srv.snapshot());
}
srv.configured.config.clone()
};
let mut trust_store =
ProjectTrustStore::load(&self.trust_store_path).map_err(|e| e.to_string())?;
trust_store
.trust(project_root, name, &config)
.map_err(|e| e.to_string())?;
trust_store
.save(&self.trust_store_path)
.map_err(|e| e.to_string())?;
let should_connect = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
srv.configured.trusted = true;
srv.configured.enabled
};
if should_connect {
self.connect_server(name)
} else {
self.get_server(name)
.ok_or_else(|| format!("MCP server '{name}' not found"))
}
}
pub fn add_server(
&self,
name: &str,
config: ServerConfig,
replace: bool,
) -> Result<McpServerSnapshot, String> {
add_user_server(&self.user_config_path, name, config, replace)
.map_err(|e| e.to_string())?;
self.reload_config()?;
let guard = self.lock_state()?;
guard
.servers
.get(name)
.map(ManagedServer::snapshot)
.ok_or_else(|| format!("MCP server '{name}' not found after reload"))
}
pub fn remove_server(&self, name: &str) -> Result<(), String> {
remove_user_server(&self.user_config_path, name).map_err(|e| e.to_string())?;
let _ = oauth_logout_server(&self.auth_store_path, name);
let old_client = {
let mut guard = self.lock_state()?;
guard.servers.remove(name).and_then(|s| s.client)
};
drop(old_client);
Ok(())
}
pub fn logout_server(&self, name: &str) -> Result<McpServerSnapshot, String> {
let is_http = {
let guard = self.lock_state()?;
let Some(srv) = guard.servers.get(name) else {
return Err(format!("MCP server '{name}' not found"));
};
srv.configured.transport_kind == TransportKind::Http
};
if !is_http {
return Err(format!(
"MCP server '{name}' uses stdio transport and does not use OAuth authentication"
));
}
oauth_logout_server(&self.auth_store_path, name).map_err(|e| e.to_string())?;
let (old_client, snapshot) = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = false;
let old = srv.client.take();
srv.tools.clear();
srv.status = if !srv.configured.enabled {
ServerStatus::Disabled
} else if !srv.configured.trusted {
ServerStatus::UntrustedProject
} else {
ServerStatus::NeedsAuth
};
(old, srv.snapshot())
};
drop(old_client);
Ok(snapshot)
}
pub fn reload_config(&self) -> Result<Vec<McpServerSnapshot>, String> {
let configured = load_configured_servers(
&self.user_config_path,
self.project_root.as_deref(),
&self.trust_store_path,
)
.map_err(|e| e.to_string())?;
let mut old_clients = Vec::new();
let mut to_connect = Vec::new();
{
let mut guard = self.lock_state()?;
let mut next = BTreeMap::new();
for srv in configured {
let name = srv.name.clone();
let mut next_generation = 0u64;
if let Some(mut existing) = guard.servers.remove(&name) {
if existing.configured == srv {
next.insert(name, existing);
continue;
}
next_generation = existing.generation.wrapping_add(1);
if let Some(c) = existing.client.take() {
old_clients.push(c);
}
}
let should_connect = srv.enabled && srv.trusted;
let mut managed = ManagedServer::from_configured(srv);
managed.generation = next_generation;
next.insert(name.clone(), managed);
if should_connect {
to_connect.push(name);
}
}
for (_, mut removed) in std::mem::take(&mut guard.servers) {
if let Some(c) = removed.client.take() {
old_clients.push(c);
}
}
guard.servers = next;
}
drop(old_clients);
for name in to_connect {
let _ = self.connect_server(&name);
}
let guard = self.lock_state()?;
Ok(guard
.servers
.values()
.map(ManagedServer::snapshot)
.collect())
}
pub fn update_server_oauth(
&self,
name: &str,
patch: OAuthConfigPatch,
) -> Result<McpServerSnapshot, String> {
let (old_client, should_connect, should_logout) = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
if srv.configured.transport_kind != TransportKind::Http {
return Err(format!(
"MCP server '{name}' uses stdio transport and does not support OAuth"
));
}
if srv.configured.source != ServerSource::User {
return Err(format!(
"MCP server '{name}' is defined in project .mcp.json; edit that file to update OAuth settings"
));
}
let existing_oauth = srv.configured.config.oauth.clone();
let existing_client_id = existing_oauth.as_ref().and_then(|o| o.client_id.clone());
let existing_secret = existing_oauth
.as_ref()
.and_then(|o| o.client_secret.clone());
let next_client_id = patch
.client_id
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let next_secret = if patch.clear_client_secret {
None
} else if let Some(secret) = patch
.client_secret
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
{
Some(secret)
} else {
existing_secret
};
let next_scopes = patch.scopes.and_then(|list| {
let cleaned: Vec<String> = list
.into_iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if cleaned.is_empty() {
None
} else {
Some(cleaned)
}
});
let candidate = OAuthClientConfig {
client_id: next_client_id.clone(),
client_secret: next_secret,
callback_port: patch.callback_port,
scopes: next_scopes,
};
let next_oauth = if candidate.is_empty() {
None
} else {
candidate.validate(name).map_err(|e| e.to_string())?;
Some(candidate)
};
let mut file = load_config_file(&self.user_config_path).map_err(|e| e.to_string())?;
let entry = file
.mcp_servers
.get_mut(name)
.ok_or_else(|| format!("MCP server '{name}' not found in user config"))?;
entry.oauth = next_oauth.clone();
save_config_file(&self.user_config_path, &file).map_err(|e| e.to_string())?;
let should_logout = existing_client_id != next_client_id || patch.clear_client_secret;
srv.configured.config.oauth = next_oauth;
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = false;
let next_status = initial_status(&srv.configured);
let old = srv.clear_connection(next_status);
let should_connect = srv.configured.enabled && srv.configured.trusted;
(old, should_connect, should_logout)
};
drop(old_client);
if should_logout {
oauth_logout_server(&self.auth_store_path, name).map_err(|e| e.to_string())?;
}
if should_connect {
self.connect_server(name)
} else {
self.get_server(name)
.ok_or_else(|| format!("MCP server '{name}' not found"))
}
}
pub fn start_oauth(self: &Arc<Self>, name: &str) -> Result<String, String> {
let (server_url, www_auth, resolved_oauth, auth_generation) = {
let mut guard = self.lock_state()?;
let Some(srv) = guard.servers.get_mut(name) else {
return Err(format!("MCP server '{name}' not found"));
};
if srv.configured.transport_kind != TransportKind::Http {
return Err(format!(
"MCP server '{name}' uses stdio transport and does not support OAuth"
));
}
if !srv.configured.trusted {
return Err(format!(
"MCP server '{name}' is an untrusted project server; trust it before authenticating"
));
}
if srv.auth_in_progress {
return Err(format!(
"OAuth authentication is already in progress for MCP server '{name}'"
));
}
let lookup = self.resolve_env_lookup()?;
let url = match srv
.configured
.resolve_transport(&lookup)
.map_err(|e| e.to_string())?
{
ServerTransport::Http { url, .. } => url,
ServerTransport::Stdio { .. } => {
return Err(format!(
"MCP server '{name}' uses stdio transport and does not support OAuth"
));
}
};
let resolved_oauth = srv
.configured
.resolve_oauth(&lookup)
.map_err(|e| e.to_string())?;
srv.generation = srv.generation.wrapping_add(1);
srv.auth_in_progress = true;
(
url,
srv.last_www_authenticate.clone(),
resolved_oauth,
srv.generation,
)
};
let pending = match prepare_oauth_flow_with_config(
&self.auth_store_path,
name,
&server_url,
www_auth.as_deref(),
resolved_oauth.as_ref(),
self.http_timeout,
) {
Ok(p) => p,
Err(e) => {
if let Ok(mut guard) = self.lock_state() {
if let Some(srv) = guard.servers.get_mut(name) {
if srv.generation == auth_generation {
srv.auth_in_progress = false;
}
}
}
return Err(e.to_string());
}
};
let authorize_url = pending.authorize_url().to_string();
let manager = Arc::clone(self);
let server_name = name.to_string();
let callback_timeout = self.callback_timeout;
std::thread::spawn(move || {
let result = pending.complete(callback_timeout);
let (still_current, dropped_client) = {
let Ok(mut guard) = manager.lock_state() else {
return;
};
match guard.servers.get_mut(&server_name) {
Some(srv) if srv.generation == auth_generation => {
srv.auth_in_progress = false;
let old = if let Err(ref err) = result {
if srv.configured.enabled && srv.configured.trusted {
srv.clear_connection(ServerStatus::Error(err.to_string()))
} else {
None
}
} else {
None
};
(true, old)
}
_ => (false, None),
}
};
drop(dropped_client);
if still_current && result.is_ok() {
let _ = manager.connect_server(&server_name);
}
});
Ok(authorize_url)
}
pub fn tool_access(
self: &Arc<Self>,
approver: Option<Arc<dyn Approver>>,
) -> Arc<dyn McpToolAccess> {
Arc::new(SurfaceMcpTools {
manager: Arc::clone(self),
approver,
})
}
fn resolve_env_lookup(&self) -> Result<EnvLookup, String> {
match &self.env_lookup {
Some(lookup) => Ok(lookup.clone()),
None => EnvLookup::from_system().map_err(|e| e.to_string()),
}
}
fn establish_connection(
&self,
configured: &ConfiguredServer,
) -> Result<(McpClient, Vec<Tool>), ConnectFailure> {
let lookup = self.resolve_env_lookup().map_err(ConnectFailure::Error)?;
let resolved = configured
.resolve_transport(&lookup)
.map_err(|e| ConnectFailure::Error(e.to_string()))?;
let resolved_oauth = configured
.resolve_oauth(&lookup)
.map_err(|e| ConnectFailure::Error(e.to_string()))?;
let mut bearer = None;
let http_target = match &resolved {
ServerTransport::Http { url, headers } if !has_authorization_header(headers) => {
bearer = resolve_bearer_token_with_config(
&self.auth_store_path,
&configured.name,
url,
resolved_oauth.as_ref(),
self.http_timeout,
)
.ok()
.flatten();
Some(url.clone())
}
_ => None,
};
match connect_and_list(configured, &lookup, bearer, self.http_timeout) {
Ok(res) => Ok(res),
Err(McpError::NeedsAuth {
www_authenticate, ..
}) => {
if let Some(url) = http_target {
if let Ok(refreshed) = refresh_access_token_with_config(
&self.auth_store_path,
&configured.name,
&url,
www_authenticate.as_deref(),
resolved_oauth.as_ref(),
self.http_timeout,
) {
if let Some(new_token) = refreshed.access_token {
match connect_and_list(
configured,
&lookup,
Some(new_token),
self.http_timeout,
) {
Ok(res) => return Ok(res),
Err(McpError::NeedsAuth {
www_authenticate: retry_hdr,
..
}) => {
return Err(ConnectFailure::NeedsAuth(retry_hdr));
}
Err(e) => return Err(ConnectFailure::Error(e.to_string())),
}
}
}
}
Err(ConnectFailure::NeedsAuth(www_authenticate))
}
Err(e) => Err(ConnectFailure::Error(e.to_string())),
}
}
pub fn tool_specs(&self) -> Vec<ToolSpec> {
let guard = self.lock_state().unwrap_or_else(|e| panic!("{e}"));
let mut specs = Vec::new();
for srv in guard.servers.values() {
if !srv.is_live_connected() {
continue;
}
for tool in &srv.tools {
let mut desc = tool.description.clone().unwrap_or_default();
if desc.is_empty() {
desc = format!("MCP tool '{}' from server '{}'.", tool.name, tool.server);
} else {
desc = format!("[MCP: {}] {}", tool.server, desc);
}
specs.push(ToolSpec {
name: tool.exposed_name.clone(),
description: desc,
parameters: tool.input_schema.clone(),
});
}
}
specs
}
pub fn execute_exposed_tool(
&self,
exposed_name: &str,
args: &Value,
root: &Path,
approver: Option<&Arc<dyn Approver>>,
) -> Option<ToolOutcome> {
enum ExposedLookup {
Connected(
Box<ConfiguredServer>,
Arc<Mutex<McpClient>>,
McpToolInfo,
u64,
),
Unavailable(ToolOutcome),
Unknown,
}
let lookup = {
let guard = match self.lock_state() {
Ok(g) => g,
Err(e) => return Some(ToolOutcome::err(e)),
};
let mut hit = ExposedLookup::Unknown;
for srv in guard.servers.values() {
if !srv.is_live_connected() {
continue;
}
let Some(ref client) = srv.client else {
continue;
};
if let Some(tool) = srv.tools.iter().find(|t| t.exposed_name == exposed_name) {
hit = ExposedLookup::Connected(
Box::new(srv.configured.clone()),
Arc::clone(client),
tool.clone(),
srv.generation,
);
break;
}
}
if matches!(hit, ExposedLookup::Unknown) {
if let Some(server_seg) = exposed_name
.strip_prefix("mcp__")
.and_then(|rest| rest.split_once("__"))
.map(|(seg, _)| seg)
{
for srv in guard.servers.values() {
if sanitize_name_segment(&srv.configured.name) == server_seg
&& !srv.is_live_connected()
{
let msg = match &srv.status {
ServerStatus::NeedsAuth => format!(
"MCP server '{}' requires authentication; run `blyte mcp auth {}` or authenticate in Integrations",
srv.configured.name, srv.configured.name
),
ServerStatus::Disabled => {
format!("MCP server '{}' is disabled", srv.configured.name)
}
ServerStatus::UntrustedProject => format!(
"MCP server '{}' is an untrusted project server; trust it in Integrations or via `blyte mcp trust {}`",
srv.configured.name, srv.configured.name
),
ServerStatus::Error(err) => format!(
"MCP server '{}' is not connected: {err}",
srv.configured.name
),
ServerStatus::Connected => format!(
"MCP server '{}' is not connected",
srv.configured.name
),
};
hit = ExposedLookup::Unavailable(ToolOutcome::err(msg));
break;
}
}
}
}
hit
};
let (configured, client, tool, generation) = match lookup {
ExposedLookup::Connected(c, cl, t, g) => (c, cl, t, g),
ExposedLookup::Unavailable(outcome) => {
return Some(self.redact_outcome(outcome, root));
}
ExposedLookup::Unknown => return None,
};
let requires_approval = match configured.approval {
ApprovalPolicy::Auto => false,
ApprovalPolicy::ReadOnly => tool.read_only_hint != Some(true),
ApprovalPolicy::Ask => true,
};
if requires_approval {
if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
return Some(ToolOutcome::err(format!(
"cannot run MCP tool '{}/{}' that requires approval during a turn started by another surface ({started_by})",
tool.server, tool.name
)));
}
let Some(approver) = approver else {
return Some(ToolOutcome::err(format!(
"MCP tool '{}/{}' requires user approval, but no interactive approver is available",
tool.server, tool.name
)));
};
let extra_pairs = self.configured_secret_pairs();
let args_summary = match format_args_for_approval_with_extra(
args,
root,
&self.auth_store_path,
&extra_pairs,
) {
Ok(summary) => summary,
Err(e) => return Some(ToolOutcome::err(e)),
};
let command = format!("mcp {}/{} {}", tool.server, tool.name, args_summary);
let reason = format!(
"MCP tool '{}' on server '{}' requires approval (policy: {})",
tool.name, tool.server, configured.approval
);
if approver.ask(&command, &reason) != Approval::Approved {
return Some(ToolOutcome::err(format!(
"MCP tool '{}/{}' was denied by user",
tool.server, tool.name
)));
}
}
let call_result = {
let mut client_guard = match client.lock() {
Ok(g) => g,
Err(_) => {
return Some(ToolOutcome::err(format!(
"MCP client lock for server '{}' is poisoned",
configured.name
)));
}
};
client_guard.call_tool(&tool.name, args.clone())
};
let call_result = match call_result {
Ok(res) => Ok(res),
Err(McpError::NeedsAuth {
www_authenticate, ..
}) => self.retry_call_after_refresh(
&configured,
generation,
&tool.name,
args,
www_authenticate,
),
Err(e) => Err(e),
};
let raw_outcome = match call_result {
Ok(res) => format_tool_call_result(&res),
Err(McpError::NeedsAuth { .. }) => ToolOutcome::err(format!(
"MCP server '{}' requires authentication; run `blyte mcp auth {}` or authenticate in Integrations",
tool.server, tool.server
)),
Err(e) => ToolOutcome::err(format!("MCP tool '{}/{}' failed: {e}", tool.server, tool.name)),
};
Some(self.redact_outcome(raw_outcome, root))
}
fn redact_outcome(&self, mut outcome: ToolOutcome, root: &Path) -> ToolOutcome {
let extra_pairs = self.configured_secret_pairs();
match apply_all_redactors_with_extra(
&outcome.content,
root,
&self.auth_store_path,
&extra_pairs,
) {
Ok(redacted) => {
outcome.content = redacted;
outcome
}
Err(e) => ToolOutcome::err(e),
}
}
fn retry_call_after_refresh(
&self,
configured: &ConfiguredServer,
generation: u64,
tool_name: &str,
args: &Value,
www_authenticate: Option<String>,
) -> Result<ToolCallResult, McpError> {
if configured.transport_kind == TransportKind::Http {
if let Ok(lookup) = self.resolve_env_lookup() {
if let Ok(ServerTransport::Http { url, headers }) =
configured.resolve_transport(&lookup)
{
let resolved_oauth = configured.resolve_oauth(&lookup).ok().flatten();
if !has_authorization_header(&headers) {
if let Ok(refreshed) = refresh_access_token_with_config(
&self.auth_store_path,
&configured.name,
&url,
www_authenticate.as_deref(),
resolved_oauth.as_ref(),
self.http_timeout,
) {
if let Some(new_token) = refreshed.access_token {
if let Ok((mut new_client, _)) = McpClient::connect_server(
configured,
&lookup,
Some(new_token),
self.http_timeout,
) {
let retry = new_client.call_tool(tool_name, args.clone());
match retry {
Err(McpError::NeedsAuth {
www_authenticate: retry_www_auth,
status,
}) => {
let mut guard =
self.lock_state().map_err(McpError::Protocol)?;
if let Some(srv) =
guard.servers.get_mut(&configured.name)
{
if srv.generation == generation
&& srv.configured.enabled
&& srv.configured.trusted
{
srv.client = None;
srv.tools.clear();
srv.status = ServerStatus::NeedsAuth;
srv.last_www_authenticate =
retry_www_auth.clone();
}
}
return Err(McpError::NeedsAuth {
www_authenticate: retry_www_auth,
status,
});
}
other => {
let new_arc = Arc::new(Mutex::new(new_client));
let mut guard =
self.lock_state().map_err(McpError::Protocol)?;
if let Some(srv) =
guard.servers.get_mut(&configured.name)
{
if srv.generation == generation
&& srv.configured.enabled
&& srv.configured.trusted
{
srv.client = Some(new_arc);
srv.status = ServerStatus::Connected;
srv.last_www_authenticate = None;
}
}
return other;
}
}
}
}
}
}
}
}
}
let mut guard = self.lock_state().map_err(McpError::Protocol)?;
if let Some(srv) = guard.servers.get_mut(&configured.name) {
if srv.generation == generation && srv.configured.enabled && srv.configured.trusted {
srv.client = None;
srv.tools.clear();
srv.status = ServerStatus::NeedsAuth;
srv.last_www_authenticate = www_authenticate.clone();
}
}
Err(McpError::NeedsAuth {
www_authenticate,
status: 401,
})
}
fn lock_state(&self) -> Result<std::sync::MutexGuard<'_, ManagerState>, String> {
self.state
.lock()
.map_err(|_| "MCP manager state lock is poisoned".to_string())
}
}
struct SurfaceMcpTools {
manager: Arc<McpManager>,
approver: Option<Arc<dyn Approver>>,
}
impl McpToolAccess for SurfaceMcpTools {
fn tool_specs(&self) -> Vec<ToolSpec> {
self.manager.tool_specs()
}
fn execute(&self, name: &str, args: &Value, root: &Path) -> Option<ToolOutcome> {
self.manager
.execute_exposed_tool(name, args, root, self.approver.as_ref())
}
}
enum ConnectFailure {
NeedsAuth(Option<String>),
Error(String),
}
fn connect_and_list(
configured: &ConfiguredServer,
lookup: &EnvLookup,
bearer_token: Option<String>,
timeout: Duration,
) -> Result<(McpClient, Vec<Tool>), McpError> {
let (mut client, _) = McpClient::connect_server(configured, lookup, bearer_token, timeout)?;
let tools = client.list_tools()?;
Ok((client, tools))
}
fn has_authorization_header(headers: &BTreeMap<String, String>) -> bool {
headers
.keys()
.any(|k| k.eq_ignore_ascii_case("authorization"))
}
fn existing_exposed_names(
servers: &BTreeMap<String, ManagedServer>,
exclude_server: &str,
) -> HashSet<String> {
let mut set: HashSet<String> = BUILTIN_TOOL_NAMES
.iter()
.map(|s| (*s).to_string())
.collect();
for (name, srv) in servers {
if name == exclude_server {
continue;
}
for t in &srv.tools {
set.insert(t.exposed_name.clone());
}
}
set
}
pub fn sanitize_name_segment(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut prev_underscore = false;
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch);
prev_underscore = false;
} else if !prev_underscore {
out.push('_');
prev_underscore = true;
}
}
let trimmed = out.trim_matches('_');
if trimmed.is_empty() {
"tool".to_string()
} else {
trimmed.to_string()
}
}
pub fn format_exposed_tool_name(
server_name: &str,
tool_name: &str,
used: &mut HashSet<String>,
) -> String {
let base = format!(
"mcp__{}__{}",
sanitize_name_segment(server_name),
sanitize_name_segment(tool_name)
);
if used.insert(base.clone()) {
return base;
}
let mut suffix = 2u32;
loop {
let candidate = format!("{base}_{suffix}");
if used.insert(candidate.clone()) {
return candidate;
}
suffix += 1;
}
}
fn assign_exposed_names(
server_name: &str,
defs: &[Tool],
other_used: &HashSet<String>,
) -> Vec<McpToolInfo> {
let mut used = other_used.clone();
let mut out = Vec::with_capacity(defs.len());
for def in defs {
let exposed_name = format_exposed_tool_name(server_name, &def.name, &mut used);
let input_schema = if def.input_schema.is_object() {
def.input_schema.clone()
} else {
json!({ "type": "object", "properties": {} })
};
out.push(McpToolInfo {
server: server_name.to_string(),
name: def.name.clone(),
exposed_name,
description: def.description.clone(),
input_schema,
read_only_hint: def.annotations.as_ref().and_then(|a| a.read_only_hint),
});
}
out
}
fn format_tool_call_result(result: &ToolCallResult) -> ToolOutcome {
let rendered = result.text_content();
let text = if rendered.is_empty() {
if result.is_error {
"MCP tool returned an error with no output".to_string()
} else {
"(no output)".to_string()
}
} else {
rendered
};
if result.is_error {
ToolOutcome::err(text)
} else {
ToolOutcome::ok(text)
}
}
fn apply_all_redactors(text: &str, root: &Path, auth_store_path: &Path) -> Result<String, String> {
apply_all_redactors_with_extra(text, root, auth_store_path, &[])
}
fn apply_all_redactors_with_extra(
text: &str,
root: &Path,
auth_store_path: &Path,
extra_pairs: &[(String, String)],
) -> Result<String, String> {
let mut redacted = Redactor::for_root(root)
.map_err(|e| format!("failed to initialize secret redactor: {e}"))?
.apply(text);
if let Ok(store) = McpAuthStore::load(auth_store_path) {
let pairs = store.secret_pairs();
if !pairs.is_empty() {
redacted = Redactor::from_pairs(pairs).apply(&redacted);
}
}
if !extra_pairs.is_empty() {
redacted = Redactor::from_pairs(extra_pairs.to_vec()).apply(&redacted);
}
Ok(redacted)
}
#[cfg(test)]
fn redact_outcome(mut outcome: ToolOutcome, root: &Path, auth_store_path: &Path) -> ToolOutcome {
match apply_all_redactors_with_extra(&outcome.content, root, auth_store_path, &[]) {
Ok(redacted) => {
outcome.content = redacted;
outcome
}
Err(e) => ToolOutcome::err(e),
}
}
#[cfg(test)]
fn format_args_for_approval<T: Serialize + ?Sized>(
args: &T,
root: &Path,
auth_store_path: &Path,
) -> Result<String, String> {
format_args_for_approval_with_extra(args, root, auth_store_path, &[])
}
fn format_args_for_approval_with_extra<T: Serialize + ?Sized>(
args: &T,
root: &Path,
auth_store_path: &Path,
extra_pairs: &[(String, String)],
) -> Result<String, String> {
let compact = serde_json::to_string(args)
.map_err(|e| format!("failed to serialize MCP tool arguments for approval: {e}"))?;
let redacted = apply_all_redactors_with_extra(&compact, root, auth_store_path, extra_pairs)?;
if redacted.chars().count() <= APPROVAL_ARGS_DISPLAY_MAX_CHARS {
Ok(redacted)
} else {
let truncated: String = redacted
.chars()
.take(APPROVAL_ARGS_DISPLAY_MAX_CHARS)
.collect();
Ok(format!("{truncated}..."))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic::{catch_unwind, AssertUnwindSafe};
struct FailingSerialize;
impl Serialize for FailingSerialize {
fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom("cannot serialize args"))
}
}
#[test]
fn format_args_for_approval_returns_error_on_serialization_failure() {
let td = tempfile::tempdir().unwrap();
let err = format_args_for_approval(
&FailingSerialize,
td.path(),
&td.path().join("mcp-auth.json"),
)
.unwrap_err();
assert!(
err.contains("failed to serialize MCP tool arguments"),
"expected serialization error, got: {err}"
);
}
#[test]
fn poisoned_manager_state_lock_fails_with_error() {
let td = tempfile::tempdir().unwrap();
let manager = McpManager::new(
td.path().join("mcp.json"),
None,
td.path().join("mcp-trust.json"),
td.path().join("mcp-auth.json"),
)
.unwrap();
let _ = catch_unwind(AssertUnwindSafe(|| {
let _guard = manager.state.lock().unwrap();
panic!("poison state mutex");
}));
let err = manager.connect_server("any").unwrap_err();
assert!(
err.contains("MCP manager state lock is poisoned"),
"expected poisoned state lock error, got: {err}"
);
let outcome = manager
.execute_exposed_tool("mcp__any__tool", &json!({}), td.path(), None)
.expect("poisoned state lock should return an error outcome");
assert!(outcome.is_error);
assert!(
outcome
.content
.contains("MCP manager state lock is poisoned"),
"expected poisoned state lock outcome, got: {}",
outcome.content
);
}
#[test]
fn poisoned_client_lock_fails_with_error() {
let td = tempfile::tempdir().unwrap();
let cfg_path = td.path().join("mcp.json");
let server_cfg = ServerConfig::http(
"http://127.0.0.1:1/mcp",
BTreeMap::new(),
ApprovalPolicy::Auto,
);
add_user_server(&cfg_path, "demo", server_cfg, false).unwrap();
let manager = McpManager::new(
cfg_path,
None,
td.path().join("mcp-trust.json"),
td.path().join("mcp-auth.json"),
)
.unwrap();
let client = McpClient::new(crate::mcp::http::StreamableHttpTransport::new(
"http://127.0.0.1:1/mcp",
BTreeMap::new(),
None,
));
let client_arc = Arc::new(Mutex::new(client));
let _ = catch_unwind(AssertUnwindSafe(|| {
let _guard = client_arc.lock().unwrap();
panic!("poison client mutex");
}));
{
let mut guard = manager.state.lock().unwrap();
let srv = guard.servers.get_mut("demo").unwrap();
srv.client = Some(client_arc);
srv.status = ServerStatus::Connected;
srv.tools = vec![McpToolInfo {
server: "demo".to_string(),
name: "ping".to_string(),
exposed_name: "mcp__demo__ping".to_string(),
description: None,
input_schema: json!({ "type": "object", "properties": {} }),
read_only_hint: Some(true),
}];
}
let outcome = manager
.execute_exposed_tool("mcp__demo__ping", &json!({}), td.path(), None)
.expect("poisoned client lock should return an error outcome");
assert!(outcome.is_error);
assert!(
outcome
.content
.contains("MCP client lock for server 'demo' is poisoned"),
"expected poisoned client lock error, got: {}",
outcome.content
);
}
#[test]
fn apply_all_redactors_fails_closed_when_project_redactor_errors() {
let td = tempfile::tempdir().unwrap();
std::fs::create_dir(td.path().join(".env")).unwrap();
let auth_store = td.path().join("mcp-auth.json");
let secret = "super-sensitive-payload-12345";
let err = apply_all_redactors(secret, td.path(), &auth_store)
.expect_err("unreadable .env should fail closed");
assert!(
err.contains("secret redactor"),
"expected redactor error, got: {err}"
);
assert!(!err.contains(secret));
let outcome = redact_outcome(ToolOutcome::ok(secret), td.path(), &auth_store);
assert!(outcome.is_error);
assert!(!outcome.content.contains(secret));
let approval_err = format_args_for_approval(
&serde_json::json!({ "token": secret }),
td.path(),
&auth_store,
)
.expect_err("approval args formatting should fail closed");
assert!(!approval_err.contains(secret));
let manager = McpManager::new(
td.path().join("mcp.json"),
Some(td.path().to_path_buf()),
td.path().join("mcp-trust.json"),
auth_store,
)
.unwrap();
let redacted_text = manager.redact_text(secret, td.path());
assert!(!redacted_text.contains(secret));
assert!(redacted_text.contains("redacted"));
}
}