From 293972baaaed5d7c300971fe665ea7d71bf890f7 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:02:19 +0800 Subject: [PATCH] fix(mcp): wait only for the stopped server's own port on a restart (#3341) With the fixed MCP port taken by another program the server runs on a free port, yet every restart polled the taken port for two seconds, blocking the window. A restart now waits only for the port the stopped server held. --- src-tauri/src/commands/mcp.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/commands/mcp.rs b/src-tauri/src/commands/mcp.rs index d03fe10fc..d9a9699fb 100644 --- a/src-tauri/src/commands/mcp.rs +++ b/src-tauri/src/commands/mcp.rs @@ -65,8 +65,9 @@ pub fn apply(state: &AppState) { } // Another address, port or token: clients connect anew. if let Some(running) = server.take() { + let held = (running.address(), running.port()); running.stop(); - if let Some(port) = wanted.port { + if let Some(port) = port_to_wait_for(held, address, wanted.port) { wait_until_free(address, port); } } @@ -104,6 +105,13 @@ pub fn apply(state: &AppState) { } } +/// The port a restart listening on `address` and `wanted` waits for after stopping the server +/// that listened on `held`: only its own. A port another program holds (the run fell back to a +/// free one) stays taken, and waiting for it would block the window. +fn port_to_wait_for(held: (IpAddr, u16), address: IpAddr, wanted: Option) -> Option { + wanted.filter(|port| held == (address, *port)) +} + /// Waits briefly for a stopped server's port to close, so the restart gets it again. fn wait_until_free(address: IpAddr, port: u16) { for _ in 0..100 { @@ -243,3 +251,20 @@ pub fn mcp_respond( ) -> IdeResult<()> { state.host.mcp_requests.answer(window.label(), id, allow, error) } + +#[cfg(test)] +mod tests { + use super::*; + use std::net::Ipv4Addr; + + #[test] + fn a_restart_waits_only_for_the_port_the_stopped_server_held() { + let local = IpAddr::V4(Ipv4Addr::LOCALHOST); + let any = IpAddr::V4(Ipv4Addr::UNSPECIFIED); + assert_eq!(port_to_wait_for((local, 64342), local, Some(64342)), Some(64342)); + // The fixed port was taken by another program: the server ran on a free one. + assert_eq!(port_to_wait_for((local, 51234), local, Some(64342)), None); + assert_eq!(port_to_wait_for((local, 64342), any, Some(64342)), None); + assert_eq!(port_to_wait_for((local, 64342), local, None), None); + } +}