Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/workflows/patched-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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" \
Expand Down
3 changes: 2 additions & 1 deletion crates/goose-agent/src/extension.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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]
Expand Down
2 changes: 2 additions & 0 deletions crates/goose/src/agents/extension_manager/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: ConnectContext startup_timeout.
use anyhow::Result;
use chrono::{DateTime, Utc};
use futures::Stream;
Expand Down Expand Up @@ -763,6 +764,7 @@ impl ExtensionManager {
let tools_version = Arc::new(AtomicU64::new(0));
let ctx = |timeout: Option<u64>, 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,
Expand Down
32 changes: 18 additions & 14 deletions crates/goose/src/agents/extension_manager/stdio.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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, std::io::Error>(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;
69 changes: 69 additions & 0 deletions crates/goose/src/agents/extension_manager/stdio_startup_tests.rs
Original file line number Diff line number Diff line change
@@ -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;
}
2 changes: 2 additions & 0 deletions crates/goose/src/agents/extension_manager/streamable_http.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand Down
20 changes: 15 additions & 5 deletions crates/goose/src/agents/mcp_client.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand Down Expand Up @@ -519,6 +521,7 @@ impl std::fmt::Debug for GooseMcpClientCapabilities {
#[derive(Clone)]
pub(crate) struct ConnectContext {
pub timeout: Duration,
pub startup_timeout: Option<Duration>,
pub client_name: String,
pub capabilities: GooseMcpClientCapabilities,
pub working_dir: PathBuf,
Expand Down Expand Up @@ -547,6 +550,7 @@ impl McpClient {
{
let ConnectContext {
timeout,
startup_timeout,
client_name,
capabilities,
working_dir,
Expand Down Expand Up @@ -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![
Expand All @@ -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())
Expand Down
Loading
Loading