diff --git a/.github/workflows/patched-test.yml b/.github/workflows/patched-test.yml index 9a9f3cda6b25..fa1df635e77e 100644 --- a/.github/workflows/patched-test.yml +++ b/.github/workflows/patched-test.yml @@ -101,7 +101,14 @@ jobs: "acp::server::session_settings::tests::max_turns_from_meta_absent_or_null_is_default" \ "acp::server::session_settings::tests::max_turns_from_meta_accepts_positive_integer" \ "acp::server::session_settings::tests::max_turns_from_meta_rejects_invalid_values" \ - "acp::server::session_settings::tests::cache_ttl_is_normalized_and_validated" + "acp::server::session_settings::tests::cache_ttl_is_normalized_and_validated" \ + "agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_format" \ + "agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_resolve" \ + "agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_auto_lifecycle" \ + "agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_discover_lifecycle" \ + "agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_initialize_lifecycle" \ + "agents::extension_manager::stdio::startup_tests::test_mcp_client_startup_timeout_stdio_kills_process_group" \ + "agents::extension_manager::stdio::startup_tests::test_mcp_client_startup_timeout_stdio_abandoned_start_kills_process_group" run_exact_tests --release -p goose --features "$F" --test acp_server_test -- \ "test_prompt_reports_context_error_when_compaction_limit_is_exhausted" \ diff --git a/crates/goose-agent/src/extension.rs b/crates/goose-agent/src/extension.rs index 54e1e1181cd7..89ddb9fb186b 100644 --- a/crates/goose-agent/src/extension.rs +++ b/crates/goose-agent/src/extension.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: ProcessExit Display includes the source error (e.g. the startup timeout). use std::collections::HashMap; use once_cell::sync::Lazy; @@ -29,7 +30,7 @@ pub fn name_to_key(name: &str) -> String { } #[derive(Error, Debug)] -#[error("process quit before initialization: stderr = {stderr}")] +#[error("process quit before initialization: {source}; stderr = {stderr}")] pub struct ProcessExit { stderr: String, #[source] diff --git a/crates/goose/src/agents/extension_manager/mod.rs b/crates/goose/src/agents/extension_manager/mod.rs index 70efa18d16f9..88c8c7ab4987 100644 --- a/crates/goose/src/agents/extension_manager/mod.rs +++ b/crates/goose/src/agents/extension_manager/mod.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: ConnectContext startup_timeout. use anyhow::Result; use chrono::{DateTime, Utc}; use futures::Stream; @@ -763,6 +764,7 @@ impl ExtensionManager { let tools_version = Arc::new(AtomicU64::new(0)); let ctx = |timeout: Option, working_dir: PathBuf| ConnectContext { timeout: Duration::from_secs(resolve_timeout(timeout)), + startup_timeout: None, client_name: client.name.clone(), capabilities: client.capabilities.clone(), working_dir, diff --git a/crates/goose/src/agents/extension_manager/stdio.rs b/crates/goose/src/agents/extension_manager/stdio.rs index 73daaec702ba..25105d13964e 100644 --- a/crates/goose/src/agents/extension_manager/stdio.rs +++ b/crates/goose/src/agents/extension_manager/stdio.rs @@ -1,13 +1,14 @@ +// Modified by Jonathan Mohrbacher, 2026: a failed start kills the child's process group and stops waiting for stderr (see mcp_startup_timeout.rs). use std::collections::HashMap; use rmcp::transport::ConfigureCommandExt; -use tokio::io::AsyncReadExt; use tokio::process::Command; use super::super::container::Container; use super::super::extension::{ExtensionError, ExtensionResult, ProcessExit}; use super::super::extension_malware_check; use super::super::mcp_client::{ConnectContext, McpClient}; +use super::super::mcp_startup_timeout::{FailedStartKill, StartupStderr}; use crate::config::search_path::SearchPaths; use crate::subprocess::spawn_long_lived_mcp_subprocess; @@ -80,22 +81,25 @@ pub(super) async fn spawn(mut command: Command, ctx: ConnectContext) -> Extensio ); } - let (transport, mut stderr) = spawn_long_lived_mcp_subprocess(command).await?; - let mut stderr = stderr.take().ok_or_else(|| { + let (transport, stderr) = spawn_long_lived_mcp_subprocess(command).await?; + let failed_start_kill = FailedStartKill::new(transport.id()); + let stderr = stderr.ok_or_else(|| { ExtensionError::SetupError("failed to attach child process stderr".to_owned()) })?; - - let stderr_task = tokio::spawn(async move { - let mut all_stderr = Vec::new(); - stderr.read_to_end(&mut all_stderr).await?; - Ok::(String::from_utf8_lossy(&all_stderr).into()) - }); + let stderr = StartupStderr::capture(stderr); match McpClient::connect(transport, ctx).await { - Ok(client) => Ok(client), - Err(error) => Err(match stderr_task.await? { - Ok(stderr_content) => ProcessExit::new(stderr_content, error).into(), - Err(e) => e.into(), - }), + Ok(client) => { + failed_start_kill.disarm(); + Ok(client) + } + Err(error) => { + drop(failed_start_kill); + Err(ProcessExit::new(stderr.collect().await, error).into()) + } } } + +#[cfg(test)] +#[path = "stdio_startup_tests.rs"] +mod startup_tests; diff --git a/crates/goose/src/agents/extension_manager/stdio_startup_tests.rs b/crates/goose/src/agents/extension_manager/stdio_startup_tests.rs new file mode 100644 index 000000000000..eafb4c40db44 --- /dev/null +++ b/crates/goose/src/agents/extension_manager/stdio_startup_tests.rs @@ -0,0 +1,69 @@ +// Copyright 2026 Jonathan Mohrbacher. Licensed under the Apache License, Version 2.0. +// Fork-only tests: a failed stdio extension start kills the whole process group, so a +// grandchild that inherited stderr cannot keep spawn() waiting forever. + +#[cfg(unix)] +#[tokio::test] +async fn test_mcp_client_startup_timeout_stdio_kills_process_group() { + use crate::agents::mcp_startup_timeout::tests::{ + assert_dies, assert_startup_timeout_message, hung_server_ctx, read_pid, + }; + use std::time::Duration; + + let temp_dir = tempfile::tempdir().unwrap(); + let grandchild_pid_path = temp_dir.path().join("grandchild.pid"); + let mut command = tokio::process::Command::new("sh"); + command.args([ + "-c", + &format!( + "sleep 600 & echo $! > \"{}\"; echo starting >&2; exec sleep 600", + grandchild_pid_path.display() + ), + ]); + + let result = tokio::time::timeout( + Duration::from_secs(5), + super::spawn(command, hung_server_ctx(temp_dir.path(), None)), + ) + .await + .expect("stdio spawn hung past the startup timeout"); + + let message = match result { + Ok(_) => panic!("spawn of a server that never initializes succeeded"), + Err(error) => error.to_string(), + }; + assert_startup_timeout_message(&message); + assert!( + message.contains("starting"), + "error should carry the captured stderr, got: {message}" + ); + assert_dies(read_pid(&grandchild_pid_path).await).await; +} + +#[cfg(unix)] +#[tokio::test] +async fn test_mcp_client_startup_timeout_stdio_abandoned_start_kills_process_group() { + use crate::agents::mcp_startup_timeout::tests::{assert_dies, hung_server_ctx, read_pid}; + use std::time::Duration; + + let temp_dir = tempfile::tempdir().unwrap(); + let grandchild_pid_path = temp_dir.path().join("grandchild.pid"); + let mut command = tokio::process::Command::new("sh"); + command.args([ + "-c", + &format!( + "sleep 600 & echo $! > \"{}\"; exec sleep 600", + grandchild_pid_path.display() + ), + ]); + let mut ctx = hung_server_ctx(temp_dir.path(), None); + ctx.startup_timeout = Some(Duration::from_secs(60)); + + let abandoned = + tokio::time::timeout(Duration::from_millis(500), super::spawn(command, ctx)).await; + assert!( + abandoned.is_err(), + "start should still be pending when abandoned" + ); + assert_dies(read_pid(&grandchild_pid_path).await).await; +} diff --git a/crates/goose/src/agents/extension_manager/streamable_http.rs b/crates/goose/src/agents/extension_manager/streamable_http.rs index 3e287fdb96cb..cc17622f6996 100644 --- a/crates/goose/src/agents/extension_manager/streamable_http.rs +++ b/crates/goose/src/agents/extension_manager/streamable_http.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: test_ctx sets startup_timeout. use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; @@ -689,6 +690,7 @@ mod tests { fn test_ctx(working_dir: &std::path::Path) -> ConnectContext { ConnectContext { timeout: Duration::from_secs(5), + startup_timeout: None, client_name: "goose-test".to_string(), capabilities: GooseMcpClientCapabilities { mcpui: false, diff --git a/crates/goose/src/agents/mcp_client.rs b/crates/goose/src/agents/mcp_client.rs index 216a6b3df803..4d9e92bd5256 100644 --- a/crates/goose/src/agents/mcp_client.rs +++ b/crates/goose/src/agents/mcp_client.rs @@ -1,4 +1,6 @@ +// Modified by Jonathan Mohrbacher, 2026: MCP server startup is bounded by GOOSE_EXTENSION_STARTUP_TIMEOUT (see mcp_startup_timeout.rs). use crate::action_required_manager::{ActionRequiredManager, ElicitationOutcome}; +use crate::agents::mcp_startup_timeout::bound_startup; use crate::session_context::{SESSION_ID_HEADER, TOOL_CALL_REQUEST_ID_HEADER, WORKING_DIR_HEADER}; #[expect(deprecated)] @@ -519,6 +521,7 @@ impl std::fmt::Debug for GooseMcpClientCapabilities { #[derive(Clone)] pub(crate) struct ConnectContext { pub timeout: Duration, + pub startup_timeout: Option, pub client_name: String, pub capabilities: GooseMcpClientCapabilities, pub working_dir: PathBuf, @@ -547,6 +550,7 @@ impl McpClient { { let ConnectContext { timeout, + startup_timeout, client_name, capabilities, working_dir, @@ -574,10 +578,15 @@ impl McpClient { } else { ClientLifecycleMode::Initialize }; - client.serve_with_lifecycle(transport, lifecycle).await? + bound_startup( + startup_timeout, + client.serve_with_lifecycle(transport, lifecycle), + ) + .await? } else { - client - .serve_with_lifecycle( + bound_startup( + startup_timeout, + client.serve_with_lifecycle( transport, ClientLifecycleMode::Auto { preferred_versions: vec![ @@ -586,8 +595,9 @@ impl McpClient { ], legacy_version: Some(ProtocolVersion::V_2025_11_25), }, - ) - .await? + ), + ) + .await? }; let server_info = client.peer_info().map(|info| { let mut initialize_result = InitializeResult::new(info.capabilities.clone()) diff --git a/crates/goose/src/agents/mcp_startup_timeout.rs b/crates/goose/src/agents/mcp_startup_timeout.rs new file mode 100644 index 000000000000..f169a5c592c7 --- /dev/null +++ b/crates/goose/src/agents/mcp_startup_timeout.rs @@ -0,0 +1,311 @@ +// Copyright 2026 Jonathan Mohrbacher. Licensed under the Apache License, Version 2.0. +// Fork-only module: bound MCP server startup (GOOSE_EXTENSION_STARTUP_TIMEOUT, default 25s, +// 0 treated as default) so a hung server cannot hang session/new, session/load, +// extensions/add or an extension lease. + +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use rmcp::service::ClientInitializeError; +use tokio::io::{AsyncRead, AsyncReadExt}; +use tokio::sync::Mutex; + +use crate::config::Config; + +pub const DEFAULT_EXTENSION_STARTUP_TIMEOUT: u64 = 25; + +pub(crate) fn resolve_startup_timeout_from_config( + override_timeout: Option, + config_timeout: Option, +) -> Duration { + override_timeout + .filter(|d| !d.is_zero()) + .or_else(|| { + config_timeout + .filter(|seconds| *seconds > 0) + .map(Duration::from_secs) + }) + .unwrap_or_else(|| Duration::from_secs(DEFAULT_EXTENSION_STARTUP_TIMEOUT)) +} + +pub(crate) fn resolve_startup_timeout(override_timeout: Option) -> Duration { + resolve_startup_timeout_from_config( + override_timeout, + Config::global().get_goose_extension_startup_timeout().ok(), + ) +} + +fn format_startup_timeout(d: Duration) -> String { + if d.subsec_millis() == 0 { + format!("{}s", d.as_secs()) + } else if d.as_secs() == 0 { + format!("{}ms", d.as_millis()) + } else { + format!("{:.1}s", d.as_secs_f64()) + } +} + +pub(crate) async fn bound_startup( + override_timeout: Option, + startup: F, +) -> Result> +where + F: Future>, +{ + let limit = resolve_startup_timeout(override_timeout); + match tokio::time::timeout(limit, startup).await { + Ok(result) => result.map_err(Box::new), + Err(_) => Err(Box::new(ClientInitializeError::ConnectionClosed(format!( + "MCP server did not finish initializing within {} (GOOSE_EXTENSION_STARTUP_TIMEOUT)", + format_startup_timeout(limit) + )))), + } +} + +/// Reads a starting server's stderr in the background. On a failed start the +/// error carries what was read so far: a grandchild that inherited the pipe can +/// keep it open past the child's death, so waiting for EOF could hang. +pub(crate) struct StartupStderr { + buf: Arc>>, + task: tokio::task::JoinHandle<()>, +} + +impl StartupStderr { + pub(crate) fn capture(mut stderr: R) -> Self + where + R: AsyncRead + Unpin + Send + 'static, + { + let buf = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&buf); + let task = tokio::spawn(async move { + let mut chunk = [0u8; 1024]; + while let Ok(n) = stderr.read(&mut chunk).await { + if n == 0 { + break; + } + sink.lock().await.extend_from_slice(&chunk[..n]); + } + }); + Self { buf, task } + } + + pub(crate) async fn collect(mut self) -> String { + if tokio::time::timeout(STDERR_DRAIN_GRACE, &mut self.task) + .await + .is_err() + { + self.task.abort(); + } + String::from_utf8_lossy(&self.buf.lock().await).into_owned() + } +} + +const STDERR_DRAIN_GRACE: Duration = Duration::from_secs(2); + +/// Kills the child's process group when dropped, unless the start succeeded. The child is +/// its own process-group leader (`configure_subprocess` sets `process_group(0)`), so this +/// also reaches grandchildren such as `npx`'s node, which rmcp's drop of the leader misses. +/// Being a drop guard, it also runs when the caller abandons a start midway. +pub(crate) struct FailedStartKill { + child_pid: Option, +} + +impl FailedStartKill { + pub(crate) fn new(child_pid: Option) -> Self { + Self { child_pid } + } + + pub(crate) fn disarm(mut self) { + self.child_pid = None; + } +} + +impl Drop for FailedStartKill { + fn drop(&mut self) { + #[cfg(unix)] + if let Some(pid) = self + .child_pid + .and_then(|pid| libc::pid_t::try_from(pid).ok()) + { + unsafe { + libc::killpg(pid, libc::SIGKILL); + } + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + #[cfg(unix)] + use crate::action_required_manager::ActionRequiredManager; + #[cfg(unix)] + use crate::agents::mcp_client::{ConnectContext, GooseMcpClientCapabilities, McpClient}; + #[cfg(unix)] + use rmcp::model::ProtocolVersion; + #[cfg(unix)] + use std::sync::atomic::AtomicU64; + + #[cfg(unix)] + pub(crate) fn hung_server_ctx( + working_dir: &std::path::Path, + protocol_version: Option, + ) -> ConnectContext { + ConnectContext { + timeout: Duration::from_secs(30), + startup_timeout: Some(Duration::from_millis(500)), + client_name: "test".to_string(), + capabilities: GooseMcpClientCapabilities { + protocol_version, + ..Default::default() + }, + working_dir: working_dir.to_path_buf(), + docker_container: None, + action_required: Arc::new(ActionRequiredManager::new()), + tools_version: Arc::new(AtomicU64::new(0)), + } + } + + #[cfg(unix)] + pub(crate) fn process_is_alive(pid: i32) -> bool { + if unsafe { libc::kill(pid, 0) } != 0 { + return false; + } + #[cfg(target_os = "linux")] + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + if let Some((_, after_name)) = stat.rsplit_once(") ") { + if let Some(state) = after_name.chars().next() { + return state != 'Z' && state != 'X'; + } + } + } + true + } + + #[cfg(unix)] + pub(crate) async fn read_pid(path: &std::path::Path) -> i32 { + for _ in 0..100 { + if let Ok(content) = std::fs::read_to_string(path) { + if let Ok(pid) = content.trim().parse::() { + return pid; + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("no pid written to {}", path.display()); + } + + #[cfg(unix)] + pub(crate) async fn assert_dies(pid: i32) { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while std::time::Instant::now() < deadline { + if !process_is_alive(pid) { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("process {pid} still alive 5s after startup timeout"); + } + + #[cfg(unix)] + pub(crate) fn assert_startup_timeout_message(msg: &str) { + assert!( + msg.contains("MCP server did not finish initializing within 500ms") + && msg.contains("GOOSE_EXTENSION_STARTUP_TIMEOUT"), + "error should name the startup timeout, got: {msg}" + ); + } + + #[cfg(unix)] + async fn assert_connect_times_out_and_kills_child(protocol_version: Option) { + let temp_dir = tempfile::tempdir().unwrap(); + let pid_path = temp_dir.path().join("pid"); + let mut command = tokio::process::Command::new("sh"); + command.args([ + "-c", + &format!("echo $$ > \"{}\" && exec sleep 600", pid_path.display()), + ]); + let (transport, _stderr) = crate::subprocess::spawn_long_lived_mcp_subprocess(command) + .await + .unwrap(); + let pid = read_pid(&pid_path).await; + assert!(process_is_alive(pid)); + + let result = tokio::time::timeout( + Duration::from_secs(3), + McpClient::connect( + transport, + hung_server_ctx(temp_dir.path(), protocol_version), + ), + ) + .await + .expect("McpClient::connect hung past the 500ms startup timeout"); + + match result { + Ok(_) => panic!("connect to a server that never initializes succeeded"), + Err(error) => assert_startup_timeout_message(&error.to_string()), + } + assert_dies(pid).await; + } + + #[tokio::test] + #[cfg(unix)] + async fn test_mcp_client_startup_timeout_auto_lifecycle() { + assert_connect_times_out_and_kills_child(None).await; + } + + #[tokio::test] + #[cfg(unix)] + async fn test_mcp_client_startup_timeout_discover_lifecycle() { + assert_connect_times_out_and_kills_child(Some(ProtocolVersion::STANDARD_HEADERS)).await; + } + + #[tokio::test] + #[cfg(unix)] + async fn test_mcp_client_startup_timeout_initialize_lifecycle() { + assert_connect_times_out_and_kills_child(Some(ProtocolVersion::V_2025_11_25)).await; + } + + #[test] + fn test_mcp_client_startup_timeout_format() { + assert_eq!(format_startup_timeout(Duration::from_secs(25)), "25s"); + assert_eq!(format_startup_timeout(Duration::from_secs(1)), "1s"); + assert_eq!(format_startup_timeout(Duration::from_millis(500)), "500ms"); + assert_eq!(format_startup_timeout(Duration::from_millis(1500)), "1.5s"); + } + + #[test] + fn test_mcp_client_startup_timeout_resolve() { + let default_timeout = Duration::from_secs(DEFAULT_EXTENSION_STARTUP_TIMEOUT); + + assert_eq!( + resolve_startup_timeout_from_config(Some(Duration::from_secs(42)), Some(10)), + Duration::from_secs(42) + ); + assert_eq!( + resolve_startup_timeout_from_config(Some(Duration::ZERO), Some(10)), + Duration::from_secs(10) + ); + assert_eq!( + resolve_startup_timeout_from_config(Some(Duration::ZERO), Some(0)), + default_timeout + ); + assert_eq!( + resolve_startup_timeout_from_config(Some(Duration::ZERO), None), + default_timeout + ); + assert_eq!( + resolve_startup_timeout_from_config(None, Some(15)), + Duration::from_secs(15) + ); + assert_eq!( + resolve_startup_timeout_from_config(None, Some(0)), + default_timeout + ); + assert_eq!( + resolve_startup_timeout_from_config(None, None), + default_timeout + ); + } +} diff --git a/crates/goose/src/agents/mod.rs b/crates/goose/src/agents/mod.rs index 34896b5688fc..f2ba20ad3a98 100644 --- a/crates/goose/src/agents/mod.rs +++ b/crates/goose/src/agents/mod.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: register mcp_startup_timeout. mod active_run; pub mod container; pub mod context_report; @@ -10,6 +11,7 @@ pub mod final_output_tool; pub(crate) mod gen_ai_telemetry; mod large_response_handler; pub mod mcp_client; +pub(crate) mod mcp_startup_timeout; pub mod moim; pub mod platform_extensions; #[cfg(feature = "scheduler")] diff --git a/crates/goose/src/config/base.rs b/crates/goose/src/config/base.rs index 82b2c0226732..7110811f8c9d 100644 --- a/crates/goose/src/config/base.rs +++ b/crates/goose/src/config/base.rs @@ -1,3 +1,4 @@ +// Modified by Jonathan Mohrbacher, 2026: GOOSE_EXTENSION_STARTUP_TIMEOUT config param. use crate::config::paths::Paths; use crate::config::GooseMode; use crate::providers::private_file::{private_file_target_path, write_private_file}; @@ -1442,6 +1443,7 @@ impl Config { } config_value!(GOOSE_DEFAULT_EXTENSION_TIMEOUT, u64); +config_value!(GOOSE_EXTENSION_STARTUP_TIMEOUT, u64); fn find_workspace_or_exe_root() -> Option { let exe = std::env::current_exe().ok()?;