Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: resolve MCP stdio transport disconnect and add auto-reconnect (#7791)

dev-miro2634d2123ba03d
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 077111cc0..06e51fb6c 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -21,6 +21,25 @@ async fn tool_call_timeout(state: &State<'_, AppState>) -> Duration {
state.mcp_settings.lock().await.tool_call_timeout_duration()
}
+fn is_transport_error(error: &str) -> bool {
+ let lower = error.to_lowercase();
+ lower.contains("transport closed")
+ || lower.contains("broken pipe")
+ || lower.contains("connection reset")
+ || lower.contains("channel closed")
+ || lower.contains("transport error")
+}
+
+async fn cleanup_cancellation_token(
+ state: &State<'_, AppState>,
+ cancellation_token: &Option<String>,
+) {
+ if let Some(token) = cancellation_token {
+ let mut cancellations = state.tool_call_cancellations.lock().await;
+ cancellations.remove(token);
+ }
+}
+
#[tauri::command]
pub async fn activate_mcp_server<R: Runtime>(
app: tauri::AppHandle<R>,
@@ -146,6 +165,28 @@ pub async fn get_connected_servers(
Ok(servers_map.keys().cloned().collect())
}
+/// Remove an MCP server entry and cancel its running service (used when list-tools fails).
+async fn remove_mcp_server_entry(
+ mcp_servers: &SharedMcpServers,
+ server_name: &str,
+) -> bool {
+ let mut servers = mcp_servers.lock().await;
+ if let Some(service) = servers.remove(server_name) {
+ log::warn!("Removing MCP server {server_name} from connected servers");
+ match service {
+ RunningServiceEnum::NoInit(s) => {
+ let _ = s.cancel().await;
+ }
+ RunningServiceEnum::WithInit(s) => {
+ let _ = s.cancel().await;
+ }
+ }
+ true
+ } else {
+ false
+ }
+}
+
/// Retrieves all available tools from all MCP servers with server information
///
/// # Arguments
@@ -162,36 +203,63 @@ pub async fn get_connected_servers(
/// 5. Combines all tools into a single vector
/// 6. Returns the combined list of all available tools with server information
#[tauri::command]
-pub async fn get_tools(state: State<'_, AppState>) -> Result<Vec<ToolWithServer>, String> {
+pub async fn get_tools<R: Runtime>(
+ app: AppHandle<R>,
+ state: State<'_, AppState>,
+) -> Result<Vec<ToolWithServer>, String> {
let timeout_duration = tool_call_timeout(&state).await;
- let servers = state.mcp_servers.lock().await;
let mut all_tools: Vec<ToolWithServer> = Vec::new();
+ let mut removed_any = false;
- for (server_name, service) in servers.iter() {
- // List tools with timeout
- let tools_future = service.list_all_tools();
- let tools = match timeout(timeout_duration, tools_future).await {
- Ok(Ok(tools)) => tools,
- Ok(Err(e)) => {
- log::warn!("MCP server {} failed to list tools: {}", server_name, e);
+ let server_names: Vec<String> = {
+ let servers = state.mcp_servers.lock().await;
+ servers.keys().cloned().collect()
+ };
+
+ for server_name in server_names {
+ let list_result = {
+ let servers = state.mcp_servers.lock().await;
+ if let Some(service) = servers.get(&server_name) {
+ timeout(timeout_duration, service.list_all_tools()).await
+ } else {
continue;
}
+ };
+
+ match list_result {
+ Ok(Ok(tools)) => {
+ for tool in tools {
+ all_tools.push(ToolWithServer {
+ name: tool.name.to_string(),
+ description: tool.description.as_ref().map(|d| d.to_string()),
+ input_schema: serde_json::Value::Object((*tool.input_schema).clone()),
+ server: server_name.clone(),
+ });
+ }
+ }
+ Ok(Err(e)) => {
+ let err_str = e.to_string();
+ log::warn!("MCP server {} failed to list tools: {}", server_name, err_str);
+ if is_transport_error(&err_str) {
+ state.mcp_reconnect_notify.notify_waiters();
+ }
+ if remove_mcp_server_entry(&state.mcp_servers, &server_name).await {
+ removed_any = true;
+ }
+ }
Err(_) => {
log::warn!(
- "Listing tools timed out after {} seconds",
+ "MCP server {}: listing tools timed out after {} seconds",
+ server_name,
timeout_duration.as_secs()
);
- continue; // Skip this server and continue with others
}
- };
+ }
+ }
- for tool in tools {
- all_tools.push(ToolWithServer {
- name: tool.name.to_string(),
- description: tool.description.as_ref().map(|d| d.to_string()),
- input_schema: serde_json::Value::Object((*tool.input_schema).clone()),
- server: server_name.clone(),
- });
+ if removed_any {
+ if let Err(e) = app.emit("mcp-update", json!({ "server": "tools-refresh" })) {
+ log::error!("Failed to emit mcp-update event: {e}");
}
}
@@ -245,23 +313,37 @@ pub async fn call_tool(
};
if servers_to_check.is_empty() {
+ cleanup_cancellation_token(&state, &cancellation_token).await;
if let Some(server) = server_name {
return Err(format!("Server '{server}' not found"));
}
+ return Err(format!("Tool {tool_name} not found — no MCP servers connected"));
}
+ let mut transport_error_servers: Vec<String> = Vec::new();
+
// Iterate through servers and find the one that contains the tool
for (srv_name, service) in servers_to_check.iter() {
let tools = match service.list_all_tools().await {
Ok(tools) => tools,
- Err(_) => continue, // Skip this server if we can't list tools
+ Err(e) => {
+ let err_str = e.to_string();
+ log::warn!(
+ "MCP server {} failed to list tools during call_tool: {}",
+ srv_name, err_str
+ );
+ if is_transport_error(&err_str) {
+ transport_error_servers.push(srv_name.to_string());
+ }
+ continue;
+ }
};
if !tools.iter().any(|t| t.name == tool_name) {
continue; // Tool not found in this server, try next
}
- println!("Found tool {tool_name} in server {srv_name}");
+ log::info!("Found tool {tool_name} in server {srv_name}");
// Call the tool with timeout and cancellation support
let tool_call = service.call_tool(CallToolRequestParam {
@@ -295,15 +377,33 @@ pub async fn call_tool(
}
};
- // Clean up cancellation token
- if let Some(token) = &cancellation_token {
- let mut cancellations = state.tool_call_cancellations.lock().await;
- cancellations.remove(token);
+ // Signal reconnect if the tool call itself hit a transport error
+ if let Err(ref e) = result {
+ if is_transport_error(e) {
+ log::warn!(
+ "MCP server {} transport error during tool call: {}",
+ srv_name, e
+ );
+ state.mcp_reconnect_notify.notify_waiters();
+ }
}
+ cleanup_cancellation_token(&state, &cancellation_token).await;
return result;
}
+ // No server had the tool — check if it's because of transport errors
+ if !transport_error_servers.is_empty() {
+ state.mcp_reconnect_notify.notify_waiters();
+ cleanup_cancellation_token(&state, &cancellation_token).await;
+ return Err(format!(
+ "MCP server(s) [{}] disconnected while looking for tool '{}'. Reconnecting — please retry.",
+ transport_error_servers.join(", "),
+ tool_name
+ ));
+ }
+
+ cleanup_cancellation_token(&state, &cancellation_token).await;
Err(format!("Tool {tool_name} not found"))
}
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index 938336386..7c9dbc31e 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -13,7 +13,7 @@ use tauri_plugin_http::reqwest;
use tokio::{
io::AsyncReadExt,
process::Command,
- sync::Mutex,
+ sync::{Mutex, Notify},
time::{sleep, timeout},
};
@@ -159,35 +159,40 @@ pub async fn run_mcp_commands<R: Runtime>(
Ok(())
}
-/// Monitor MCP server health without removing it from the HashMap
-pub async fn monitor_mcp_server_handle(
+/// Monitor MCP server health and auto-reconnect on failure with exponential backoff
+pub async fn monitor_mcp_server_handle<R: Runtime>(
+ app: AppHandle<R>,
servers_state: SharedMcpServers,
name: String,
+ config: Value,
shutdown_flag: Arc<Mutex<bool>>,
-) -> Option<rmcp::service::QuitReason> {
+ reconnect_notify: Arc<Notify>,
+) {
log::info!("Monitoring MCP server {name} health");
+ let mut consecutive_failures: u32 = 0;
- // Monitor server health with periodic checks
loop {
- // Small delay between health checks
- sleep(Duration::from_secs(5)).await;
+ // Wait for either the periodic health check or an immediate reconnect signal
+ tokio::select! {
+ _ = sleep(Duration::from_secs(2)) => {}
+ _ = reconnect_notify.notified() => {
+ log::info!("MCP server {name} monitor received reconnect signal");
+ }
+ }
{
let shutdown = shutdown_flag.lock().await;
if *shutdown {
- return Some(rmcp::service::QuitReason::Closed);
+ log::info!("MCP server {name} monitor shutting down (shutdown flag)");
+ return;
}
}
let health_check_result = {
let servers = servers_state.lock().await;
if let Some(service) = servers.get(&name) {
- // Try to list tools as a health check with a short timeout
match timeout(Duration::from_secs(2), service.list_all_tools()).await {
- Ok(Ok(_)) => {
- // Server responded successfully
- true
- }
+ Ok(Ok(_)) => true,
Ok(Err(e)) => {
log::warn!("MCP server {name} health check failed: {e}");
false
@@ -198,30 +203,118 @@ pub async fn monitor_mcp_server_handle(
}
}
} else {
- // Server was removed from HashMap (e.g., by deactivate_mcp_server)
- log::info!("MCP server {name} no longer in running services");
- return Some(rmcp::service::QuitReason::Closed);
+ // Entry was removed (e.g., by get_tools cleanup or deactivate).
+ // Only stop monitoring if the server was deliberately deactivated.
+ let still_active = {
+ let app_state = app.state::<AppState>();
+ let active_servers = app_state.mcp_active_servers.lock().await;
+ active_servers.contains_key(&name)
+ };
+ if still_active {
+ log::info!("MCP server {name} entry missing but still active, will reconnect");
+ false
+ } else {
+ log::info!("MCP server {name} removed and deactivated, stopping monitor");
+ return;
+ }
}
};
- if !health_check_result {
- // Server failed health check - remove it and return
- log::error!("MCP server {name} failed health check, removing from active servers");
+ if health_check_result {
+ // Reset failure count on success
+ consecutive_failures = 0;
+ continue;
+ }
+
+ // Server failed health check — remove the dead entry and try to reconnect
+ log::error!("MCP server {name} failed health check, attempting auto-reconnect");
+
+ // Clean up the dead server entry (if still present) and its tracked PID
+ {
let mut servers = servers_state.lock().await;
if let Some(service) = servers.remove(&name) {
- // Try to cancel the service gracefully
match service {
RunningServiceEnum::NoInit(service) => {
- log::info!("Stopping server {name}...");
let _ = service.cancel().await;
}
RunningServiceEnum::WithInit(service) => {
- log::info!("Stopping server {name} with initialization...");
let _ = service.cancel().await;
}
}
}
- return Some(rmcp::service::QuitReason::Closed);
+ }
+ {
+ let app_state = app.state::<AppState>();
+ let mut pids = app_state.mcp_server_pids.lock().await;
+ pids.remove(&name);
+ }
+
+ // Emit event so frontend shows accurate disconnected status
+ emit_mcp_update_event(&app, &name);
+
+ consecutive_failures += 1;
+
+ // Calculate backoff delay
+ let settings = {
+ let app_state = app.state::<AppState>();
+ let guard = app_state.mcp_settings.lock().await;
+ guard.clone()
+ };
+ let base_delay_ms = settings.base_restart_delay_ms;
+ let max_delay_ms = settings.max_restart_delay_ms;
+ let multiplier = settings.backoff_multiplier;
+ let delay_ms = (base_delay_ms as f64
+ * multiplier.powi((consecutive_failures - 1) as i32))
+ as u64;
+ let capped_delay_ms = delay_ms.min(max_delay_ms);
+
+ log::info!(
+ "MCP server {name} reconnect attempt {} in {}ms",
+ consecutive_failures,
+ capped_delay_ms
+ );
+ sleep(Duration::from_millis(capped_delay_ms)).await;
+
+ // Check shutdown flag before reconnect attempt
+ {
+ let shutdown = shutdown_flag.lock().await;
+ if *shutdown {
+ log::info!("MCP server {name} monitor shutting down before reconnect");
+ return;
+ }
+ }
+
+ // Check that server is still in active configs (user hasn't deactivated it)
+ let still_active = {
+ let app_state = app.state::<AppState>();
+ let active_servers = app_state.mcp_active_servers.lock().await;
+ active_servers.contains_key(&name)
+ };
+
+ if !still_active {
+ log::info!("MCP server {name} was deactivated, stopping monitor");
+ return;
+ }
+
+ // Attempt reconnect
+ match schedule_mcp_start_task(
+ app.clone(),
+ servers_state.clone(),
+ name.clone(),
+ config.clone(),
+ )
+ .await
+ {
+ Ok(_) => {
+ log::info!("MCP server {name} reconnected successfully");
+ consecutive_failures = 0;
+ // Emit event so frontend shows accurate connected status
+ emit_mcp_update_event(&app, &name);
+ }
+ Err(e) => {
+ log::error!("MCP server {name} reconnect attempt {consecutive_failures} failed: {e}");
+ // Loop continues — will retry with increased backoff
+ }
}
}
}
@@ -253,6 +346,33 @@ pub async fn start_mcp_server<R: Runtime>(
match first_start_result {
Ok(_) => {
log::info!("MCP server {name} started successfully");
+
+ // Spawn health monitoring with auto-reconnect
+ let monitor_app = app.clone();
+ let monitor_servers = servers_state.clone();
+ let monitor_name = name.clone();
+ let monitor_config = config.clone();
+ let shutdown_flag = app_state.mcp_shutdown_in_progress.clone();
+ let reconnect_notify = app_state.mcp_reconnect_notify.clone();
+
+ let monitor_handle = tauri::async_runtime::spawn(async move {
+ monitor_mcp_server_handle(
+ monitor_app,
+ monitor_servers,
+ monitor_name,
+ monitor_config,
+ shutdown_flag,
+ reconnect_notify,
+ )
+ .await;
+ });
+
+ // Store the monitoring task handle so it can be aborted on shutdown
+ {
+ let mut monitoring_tasks = app_state.mcp_monitoring_tasks.lock().await;
+ monitoring_tasks.insert(name.clone(), monitor_handle);
+ }
+
Ok(())
}
Err(e) => {
@@ -507,6 +627,26 @@ async fn schedule_mcp_start_task<R: Runtime>(
match service {
Ok(server) => {
+ // Keep the stderr pipe alive to prevent the child process from
+ // receiving SIGPIPE and to capture diagnostic output.
+ if let Some(mut stderr_stream) = stderr {
+ let stderr_name = name.clone();
+ tokio::spawn(async move {
+ let mut buf = [0u8; 1024];
+ while let Ok(n) = stderr_stream.read(&mut buf).await {
+ if n == 0 {
+ break;
+ }
+ if let Ok(text) = std::str::from_utf8(&buf[..n]) {
+ for line in text.lines() {
+ if !line.trim().is_empty() {
+ log::warn!("[mcp-stderr:{}] {}", stderr_name, line);
+ }
+ }
+ }
+ }
+ });
+ }
log::trace!("Connected to server: {:#?}", server.peer_info());
servers
.lock()
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index ee2a755d2..7df3b53bc 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -6,7 +6,7 @@ use rmcp::{
service::RunningService,
RoleClient, ServiceError,
};
-use tokio::sync::{oneshot, Mutex};
+use tokio::sync::{oneshot, Mutex, Notify};
/// Server handle type for managing the proxy server lifecycle
pub type ServerHandle =
@@ -34,7 +34,6 @@ pub enum RunningServiceEnum {
}
pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningServiceEnum>>>;
-#[derive(Default)]
pub struct AppState {
pub app_token: Option<String>,
pub mcp_servers: SharedMcpServers,
@@ -44,11 +43,33 @@ pub struct AppState {
pub tool_call_cancellations: Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>,
pub mcp_settings: Arc<Mutex<McpSettings>>,
pub mcp_shutdown_in_progress: Arc<Mutex<bool>>,
- pub mcp_monitoring_tasks: Arc<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>>,
+ pub mcp_monitoring_tasks: Arc<Mutex<HashMap<String, tauri::async_runtime::JoinHandle<()>>>>,
pub background_cleanup_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
pub mcp_server_pids: Arc<Mutex<HashMap<String, u32>>>,
/// Remote provider configurations (e.g., Anthropic, OpenAI, etc.)
pub provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
+ /// Wakes up MCP monitors to trigger an immediate health check + reconnect
+ pub mcp_reconnect_notify: Arc<Notify>,
+}
+
+impl Default for AppState {
+ fn default() -> Self {
+ Self {
+ app_token: None,
+ mcp_servers: Default::default(),
+ download_manager: Default::default(),
+ mcp_active_servers: Default::default(),
+ server_handle: Default::default(),
+ tool_call_cancellations: Default::default(),
+ mcp_settings: Default::default(),
+ mcp_shutdown_in_progress: Default::default(),
+ mcp_monitoring_tasks: Default::default(),
+ background_cleanup_handle: Default::default(),
+ mcp_server_pids: Default::default(),
+ provider_configs: Default::default(),
+ mcp_reconnect_notify: Arc::new(Notify::new()),
+ }
+ }
}
impl RunningServiceEnum {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 5e8733184..ad951cb69 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -243,6 +243,7 @@ pub fn run() {
background_cleanup_handle: Arc::new(Mutex::new(None)),
mcp_server_pids: Arc::new(Mutex::new(HashMap::new())),
provider_configs: Arc::new(Mutex::new(HashMap::new())),
+ mcp_reconnect_notify: Arc::new(tokio::sync::Notify::new()),
})
.setup(|app| {
app.handle().plugin(