Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(mcp): kill browser MCP process group to stop port leak
Akarshan Biswasa95324deb974
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex 2ef9cdb03..5640e86e5 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -6,7 +6,7 @@ use tokio::time::timeout;use super::{constants::DEFAULT_MCP_CONFIG,- helpers::{kill_process_by_pid, restart_active_mcp_servers, start_mcp_server},+ helpers::{restart_active_mcp_servers, start_mcp_server, terminate_browser_mcp},};use crate::core::{app::commands::get_jan_data_folder_path,@@ -19,9 +19,6 @@ use crate::core::{};use std::{collections::HashSet, fs, time::Duration};-const BRIDGE_KILL_SETTLE_MS: u64 = 100; // settle after graceful cancel before port check-const PORT_FREE_SETTLE_MS: u64 = 500; // settle after force-kill before returning-async fn tool_call_timeout(state: &AppState) -> Duration {state.mcp_settings.lock().await.tool_call_timeout_duration()}@@ -198,29 +195,17 @@ pub async fn deactivate_mcp_server<R: Runtime>(}}- {+ let child_pid = {let mut pids = state.mcp_server_pids.lock().await;- pids.remove(&name);- }-+ pids.remove(&name)+ };+ // Reap the process group and confirm the port is released, then drop the lock.if name == "Jan Browser MCP" {if let Some(port) = bridge_port {- tokio::time::sleep(Duration::from_millis(BRIDGE_KILL_SETTLE_MS)).await;-- // Port 17389 is application-specific; the ~100 ms race window before another- // process could grab it is negligible in practice.- if !jan_utils::network::is_port_available(port) {- if let Some(info) = jan_utils::network::find_process_using_port(port) {- log::info!("Killing process on port {} after deactivation: PID={}", port, info.pid);- if let Err(e) = kill_process_by_pid(info.pid).await {- log::warn!("Failed to kill PID {}: {}", info.pid, e);- } else {- tokio::time::sleep(Duration::from_millis(PORT_FREE_SETTLE_MS)).await;- }- }- }-use crate::core::mcp::lockfile::delete_lock_file;++ terminate_browser_mcp(child_pid, port).await;+if let Err(e) = delete_lock_file(&app, port) {log::warn!("Failed to delete lock file for port {}: {}", port, e);}diff --git a/src-tauri/src/core/mcp/constants.rs b/src-tauri/src/core/mcp/constants.rsindex 658cc4aaa..f605d441b 100644--- a/src-tauri/src/core/mcp/constants.rs+++ b/src-tauri/src/core/mcp/constants.rs@@ -1,5 +1,9 @@// Default MCP runtime settingspub const DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS: u64 = 30;++// Browser MCP teardown: how long to wait for the port to free, and the poll cadence.+pub const MCP_PORT_FREE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2000);+pub const MCP_PORT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);pub const DEFAULT_MCP_BASE_RESTART_DELAY_MS: u64 = 1000; // Start with 1 secondpub const DEFAULT_MCP_MAX_RESTART_DELAY_MS: u64 = 30000; // Cap at 30 secondspub const DEFAULT_MCP_BACKOFF_MULTIPLIER: f64 = 2.0; // Double the delay each timediff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rsindex 61c826ea8..734bd8432 100644--- a/src-tauri/src/core/mcp/helpers.rs+++ b/src-tauri/src/core/mcp/helpers.rs@@ -24,8 +24,6 @@ use crate::core::{};use jan_utils::{can_override_npx, can_override_uvx};-const BRIDGE_KILL_SETTLE_MS: u64 = 100; // settle after graceful cancel before port check-#[derive(Debug, Clone, Copy)]pub enum ShutdownContext {AppExit, // User closing app - be fast@@ -608,6 +606,13 @@ async fn schedule_mcp_start_task<R: Runtime>({cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW: prevents shell window on Windows}+ // Make the child a process-group leader (pgid == pid) so teardown can+ // signal the whole tree; MCP bridges fork grandchildren that hold the+ // port and outlive a single-PID kill.+ #[cfg(unix)]+ {+ cmd.process_group(0);+ }cmd.kill_on_drop(true);config_params.args@@ -984,9 +989,13 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(log::info!("Killing orphaned MCP process: PID {}", process_info.pid);kill_process_by_pid(process_info.pid).await?;- tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;-- if jan_utils::network::is_port_available(port) {+ if jan_utils::network::wait_for_port_free(+ port,+ Duration::from_millis(2000),+ Duration::from_millis(50),+ )+ .await+ {log::info!("Cleaned up orphaned process on port {}", port);Ok(true)} else {@@ -995,31 +1004,42 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(}#[cfg(unix)]-pub async fn kill_process_by_pid(pid: u32) -> Result<(), String> {- use nix::sys::signal::{kill, Signal};- use nix::unistd::Pid;+async fn kill_process_by_pid(pid: u32) -> Result<(), String> {+ use nix::sys::signal::{kill, killpg, Signal};+ use nix::unistd::{getpgid, Pid};let nix_pid = Pid::from_raw(pid as i32);- kill(nix_pid, Signal::SIGTERM)+ // Signal the whole process group so forked grandchildren (which may hold the+ // port) die with the parent. We spawn MCP children as group leaders, so this+ // targets only our subtree. Fall back to the single PID if the group can't be+ // resolved (e.g. an orphan found by port scan) or resolves to init.+ let pgid = getpgid(Some(nix_pid)).ok().filter(|g| g.as_raw() > 1);+ let send = |sig: Signal| match pgid {+ Some(g) => killpg(g, sig),+ None => kill(nix_pid, sig),+ };++ send(Signal::SIGTERM).map_err(|e| format!("Failed to send SIGTERM to PID {}: {}", pid, e))?;for _ in 0..30 {tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;+ // Liveness of the leader PID is sufficient; the group dies with it.if kill(nix_pid, None).is_err() {return Ok(());}}- log::warn!("Process {} unresponsive, sending SIGKILL", pid);- kill(nix_pid, Signal::SIGKILL)+ log::warn!("Process group {} unresponsive, sending SIGKILL", pid);+ send(Signal::SIGKILL).map_err(|e| format!("Failed to send SIGKILL to PID {}: {}", pid, e))?;Ok(())}#[cfg(windows)]-pub async fn kill_process_by_pid(pid: u32) -> Result<(), String> {+async fn kill_process_by_pid(pid: u32) -> Result<(), String> {use std::process::Command;#[cfg(windows)]@@ -1043,6 +1063,43 @@ pub async fn kill_process_by_pid(pid: u32) -> Result<(), String> {Ok(())}+/// Tear down a Jan Browser MCP child and confirm its `port` is released.+/// Kills the recorded child's process group (Phase 1 makes children group+/// leaders, so this reaps forked grandchildren that hold the port), then polls;+/// if some straggler still binds the port it is found and group-killed too.+pub async fn terminate_browser_mcp(pid: Option<u32>, port: u16) {+ use crate::core::mcp::constants::{MCP_PORT_FREE_TIMEOUT, MCP_PORT_POLL_INTERVAL};++ if let Some(pid) = pid {+ if let Err(e) = kill_process_by_pid(pid).await {+ log::warn!("Failed to kill Browser MCP group (PID {}): {}", pid, e);+ }+ }++ if jan_utils::network::wait_for_port_free(port, MCP_PORT_FREE_TIMEOUT, MCP_PORT_POLL_INTERVAL)+ .await+ {+ return;+ }++ if let Some(info) = jan_utils::network::find_process_using_port(port) {+ log::info!(+ "Port {} still held after teardown; killing straggler PID {}",+ port,+ info.pid+ );+ if let Err(e) = kill_process_by_pid(info.pid).await {+ log::warn!("Failed to kill straggler PID {} on port {}: {}", info.pid, port, e);+ }+ let _ = jan_utils::network::wait_for_port_free(+ port,+ MCP_PORT_FREE_TIMEOUT,+ MCP_PORT_POLL_INTERVAL,+ )+ .await;+ }+}+pub async fn background_cleanup_mcp_servers<R: Runtime>(app: &AppHandle<R>,state: &State<'_, AppState>,@@ -1147,6 +1204,7 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(.into_iter().map(|(name, service, port)| {let app_clone = app.clone();+ let child_pid = pids_snapshot.get(&name).copied();tauri::async_runtime::spawn(async move {let cancel_future = async {@@ -1163,17 +1221,8 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(if name == "Jan Browser MCP" {if let Some(port) = port {- if success {- sleep(Duration::from_millis(BRIDGE_KILL_SETTLE_MS)).await;- }- if !jan_utils::network::is_port_available(port) {- if let Some(info) = jan_utils::network::find_process_using_port(port) {- if let Err(e) = kill_process_by_pid(info.pid).await {- log::warn!("Failed to kill port {} holder PID {}: {}", port, info.pid, e);- }- }- }use crate::core::mcp::lockfile::delete_lock_file;+ terminate_browser_mcp(child_pid, port).await;let _ = delete_lock_file(&app_clone, port);}}diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rsindex 52477d0da..7731f3264 100644--- a/src-tauri/src/core/mcp/tests.rs+++ b/src-tauri/src/core/mcp/tests.rs@@ -973,3 +973,39 @@ fn test_cleanup_own_locks_removes_only_current_pid_locks() {// Cleanuplet _ = std::fs::remove_file(&other_path);}++#[cfg(unix)]+#[tokio::test]+async fn terminate_browser_mcp_reaps_process_group() {+ use super::helpers::terminate_browser_mcp;+ use std::os::unix::process::CommandExt;+ use std::process::Command;++ // Group leader (pgid == pid) that keeps a backgrounded grandchild alive.+ // killpg must reap the whole group, not just the leader.+ let mut child = {+ let mut cmd = Command::new("sh");+ cmd.arg("-c").arg("sleep 30 & wait");+ cmd.process_group(0);+ cmd.spawn().expect("spawn group leader")+ };+ let pid = child.id();++ // A port nothing binds → terminate kills the group, finds the port already+ // free, and returns. (We're the leader's parent, so after the kill it sits as+ // a zombie until we wait() below.)+ let free_port = {+ let l = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();+ let p = l.local_addr().unwrap().port();+ drop(l);+ p+ };++ terminate_browser_mcp(Some(pid), free_port).await;++ let status = child.wait().expect("reap leader");+ assert!(+ !status.success(),+ "group leader should have been signalled, got {status:?}"+ );+}diff --git a/src-tauri/utils/Cargo.toml b/src-tauri/utils/Cargo.tomlindex 691f90a92..4d94639d6 100644--- a/src-tauri/utils/Cargo.toml+++ b/src-tauri/utils/Cargo.toml@@ -11,7 +11,7 @@ rand = "0.8"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"sha2 = "0.10"-tokio = { version = "1", features = ["process", "fs", "macros", "rt"] }+tokio = { version = "1", features = ["process", "fs", "macros", "rt", "time"] }tokio-util = "0.7.14"url = "2.5"diff --git a/src-tauri/utils/src/network.rs b/src-tauri/utils/src/network.rsindex e82407a79..738a5fd48 100644--- a/src-tauri/utils/src/network.rs+++ b/src-tauri/utils/src/network.rs@@ -17,6 +17,25 @@ pub fn is_port_available(port: u16) -> bool {std::net::TcpListener::bind(("127.0.0.1", port)).is_ok()}+/// Poll until `port` is free or `timeout` elapses; returns whether it freed.+/// Yields to the async runtime between checks instead of blocking a fixed delay.+pub async fn wait_for_port_free(+ port: u16,+ timeout: std::time::Duration,+ interval: std::time::Duration,+) -> bool {+ let start = std::time::Instant::now();+ loop {+ if is_port_available(port) {+ return true;+ }+ if start.elapsed() >= timeout {+ return false;+ }+ tokio::time::sleep(interval).await;+ }+}+/// Generate a random port that's not in the used_ports set and is availablepub fn generate_random_port(used_ports: &HashSet<u16>) -> Result<u16, String> {const MAX_ATTEMPTS: u32 = 20000;@@ -430,3 +449,32 @@ pub fn is_orphaned_mcp_process(process_info: &ProcessUsingPort) -> bool {is_js_runtime && is_jan_mcp_server}++#[cfg(test)]+mod tests {+ use super::wait_for_port_free;+ use std::time::Duration;++ #[tokio::test]+ async fn wait_for_port_free_returns_true_when_free() {+ // Bind then drop to get a port that is currently free.+ let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();+ let port = listener.local_addr().unwrap().port();+ drop(listener);++ assert!(+ wait_for_port_free(port, Duration::from_millis(500), Duration::from_millis(20)).await+ );+ }++ #[tokio::test]+ async fn wait_for_port_free_times_out_when_held() {+ let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();+ let port = listener.local_addr().unwrap().port();+ // Listener stays bound for the whole call → never frees → times out.+ assert!(+ !wait_for_port_free(port, Duration::from_millis(150), Duration::from_millis(20)).await+ );+ drop(listener);+ }+}diff --git a/src-tauri/utils/src/path.rs b/src-tauri/utils/src/path.rsindex 6134ce373..2c9c3c994 100644--- a/src-tauri/utils/src/path.rs+++ b/src-tauri/utils/src/path.rs@@ -104,6 +104,7 @@ pub fn get_short_path<P: AsRef<std::path::Path>>(path: P) -> Option<String> {#[cfg(test)]mod tests {+ #[cfg(windows)]use super::*;#[cfg(windows)]