From 1aeab9e3d5cd0c50e37c83d5dfd296abbd1ec936 Mon Sep 17 00:00:00 2001 From: Ben Romano Date: Tue, 1 Dec 2026 19:30:14 +0000 Subject: [PATCH] Overlap remote MCP config reads with capability discovery (#65101) ## Why MCP runtime refreshes waited for capability discovery and host MCP configuration to finish before requesting HTTP MCP servers from the selected remote environment. That serialized two reads that can be in flight together. ## What changed Start the remote environment config read alongside host MCP configuration, including executor capability discovery. Start the read's 10-second timeout after host configuration is ready so a serial executor can queue the read behind discovery without consuming its timeout. Merge the results with host server precedence and requirements still enforced. ## Testing Add V1 and V2 integration cases that hold both executor replies until both requests arrive, then verify host precedence and requirements. Add a paused-clock test that covers a queued read and confirms a stalled read times out 10 seconds after discovery completes. GitOrigin-RevId: d974f0f575559bfe6b756de11aa460399fdabf25 --- codex-rs/core/src/session/mcp.rs | 194 +++++++----------- codex-rs/core/src/session/mcp_runtime.rs | 112 +++++----- .../core/tests/suite/executor_discovery_v2.rs | 184 ++++++++++++++++- .../exec-server/src/environment_config.rs | 47 +++-- .../src/environment_config_tests.rs | 29 +++ 5 files changed, 380 insertions(+), 186 deletions(-) diff --git a/codex-rs/core/src/session/mcp.rs b/codex-rs/core/src/session/mcp.rs index 9c60d32c75..54f5716a47 100644 --- a/codex-rs/core/src/session/mcp.rs +++ b/codex-rs/core/src/session/mcp.rs @@ -1,8 +1,10 @@ use super::mcp_refresh::McpRefreshPermit; +use super::mcp_runtime::McpDesiredState; use super::*; use crate::McpRefreshReason; use crate::environment_selection::TurnEnvironmentSnapshot; use crate::environment_selection::combine_selected_capability_roots; +use crate::mcp::McpRuntimeProjection; use crate::mcp_tool_call::McpToolApprovalContext; use crate::mcp_tool_call::capture_environment_permissions; use anyhow::Context; @@ -179,7 +181,11 @@ impl Session { ) .await; let mcp_config = self - .project_selected_environment_mcp_servers(config, environments, mcp_projection) + .project_selected_environment_mcp_servers( + config, + environments, + std::future::ready(mcp_projection).boxed(), + ) .await .config; let runtime_context = self.mcp_runtime_context(environments, &host_fallback_cwd); @@ -284,61 +290,23 @@ impl Session { let auth = self.services.auth_manager.auth().await; // Keep current MCP authority even when reusing the step's executor inventory. let environments = self.services.turn_environments.snapshot().await; - let environment_selections = environments.all_selections(); let desired = self.latest_mcp_desired_state(auth, environments).await; let selected_capability_roots = self .resolve_selected_capability_roots_for_step(&desired.environments) .await; let ready_selected_capability_roots = Self::ready_selected_capability_roots(&selected_capability_roots); - let discovered_v2; - let executor_capability_discovery_v2 = match captured_executor_discovery_v2 { - Some(captured) => Some(captured), - None => { - (discovered_v2, _) = self - .executor_capability_discovery_for_step_v2( - &desired.config, - &desired.environments, - /*skill_turn*/ None, - ) - .await; - discovered_v2.as_deref() - } - }; - let (executor_capability_discovery, _) = self - .executor_capability_discovery_for_step( - &desired.config, + let projection_future = self + .host_mcp_projection( + &desired, &selected_capability_roots, - &desired.environments, - executor_capability_discovery_v2, - /*skill_turn*/ None, - ) - .await; - let mcp_projection = self - .services - .mcp_manager - .runtime_config_for_step( - &desired.config, - &self.services.mcp_thread_init, - &self.services.thread_extension_data, - McpThreadIdentity { - auth_changed: !self - .services - .mcp_runtime - .current_auth_matches(desired.auth.as_ref()), - session_source: &desired.session_source, - originator: &desired.originator, - disabled_plugin_ids: &desired.disabled_plugin_ids, - environments: McpEnvironmentScope::Selected(&environment_selections), - }, &ready_selected_capability_roots, - executor_capability_discovery.as_deref(), - executor_capability_discovery_v2, + captured_executor_discovery_v2, ) - .await; + .boxed(); self.publish_mcp_runtime( &desired, - mcp_projection, + projection_future, &ready_selected_capability_roots, Some(self.mcp_elicitation_reviewer()), ) @@ -347,6 +315,60 @@ impl Session { } } + async fn host_mcp_projection( + &self, + desired: &McpDesiredState, + selected_capability_roots: &[ResolvedSelectedCapabilityRoot], + ready_selected_capability_roots: &[SelectedCapabilityRoot], + captured_executor_discovery_v2: Option<&[ExecutorCapabilityDiscoveryV2Snapshot]>, + ) -> McpRuntimeProjection { + let environment_selections = desired.environments.all_selections(); + let discovered_v2; + let executor_capability_discovery_v2 = match captured_executor_discovery_v2 { + Some(captured) => Some(captured), + None => { + (discovered_v2, _) = self + .executor_capability_discovery_for_step_v2( + &desired.config, + &desired.environments, + /*skill_turn*/ None, + ) + .await; + discovered_v2.as_deref() + } + }; + let (executor_capability_discovery, _) = self + .executor_capability_discovery_for_step( + &desired.config, + selected_capability_roots, + &desired.environments, + executor_capability_discovery_v2, + /*skill_turn*/ None, + ) + .await; + self.services + .mcp_manager + .runtime_config_for_step( + &desired.config, + &self.services.mcp_thread_init, + &self.services.thread_extension_data, + McpThreadIdentity { + auth_changed: !self + .services + .mcp_runtime + .current_auth_matches(desired.auth.as_ref()), + session_source: &desired.session_source, + originator: &desired.originator, + disabled_plugin_ids: &desired.disabled_plugin_ids, + environments: McpEnvironmentScope::Selected(&environment_selections), + }, + ready_selected_capability_roots, + executor_capability_discovery.as_deref(), + executor_capability_discovery_v2, + ) + .await + } + /// Refreshes Apps tools on the published thread runtime and returns that client's snapshot. #[tracing::instrument(name = "mcp.runtime.apps_catalog_refresh", skip_all)] pub(crate) async fn refresh_codex_apps_tools( @@ -411,56 +433,25 @@ impl Session { .claim_forced(self.thread_id, McpRefreshReason::HardRefreshCodexAppsTools); let auth = self.services.auth_manager.auth().await; let environments = self.services.turn_environments.snapshot().await; - let environment_selections = environments.all_selections(); let desired = self.latest_mcp_desired_state(auth, environments).await; let selected_capability_roots = self .resolve_selected_capability_roots_for_step(&desired.environments) .await; let ready_selected_capability_roots = Self::ready_selected_capability_roots(&selected_capability_roots); - let (executor_capability_discovery_v2, _) = self - .executor_capability_discovery_for_step_v2( - &desired.config, - &desired.environments, - /*skill_turn*/ None, - ) - .await; - let (executor_capability_discovery, _) = self - .executor_capability_discovery_for_step( - &desired.config, - &selected_capability_roots, - &desired.environments, - executor_capability_discovery_v2.as_deref(), - /*skill_turn*/ None, - ) - .await; let mcp_projection = self - .services - .mcp_manager - .runtime_config_for_step( - &desired.config, - &self.services.mcp_thread_init, - &self.services.thread_extension_data, - McpThreadIdentity { - auth_changed: !self - .services - .mcp_runtime - .current_auth_matches(desired.auth.as_ref()), - session_source: &desired.session_source, - originator: &desired.originator, - disabled_plugin_ids: &desired.disabled_plugin_ids, - environments: McpEnvironmentScope::Selected(&environment_selections), - }, + .host_mcp_projection( + &desired, + &selected_capability_roots, &ready_selected_capability_roots, - executor_capability_discovery.as_deref(), - executor_capability_discovery_v2.as_deref(), + /*captured_executor_discovery_v2*/ None, ) .await; let mcp_projection = self .project_selected_environment_mcp_servers( &desired.config, &desired.environments, - mcp_projection, + std::future::ready(mcp_projection).boxed(), ) .await; let selected_plugins = mcp_projection.selected_plugins.clone(); @@ -944,49 +935,18 @@ impl Session { &captured_environments, ) .await; - let environment_selections = environments.all_selections(); let desired = self.latest_mcp_desired_state(auth, environments).await; - let (executor_capability_discovery_v2, _) = self - .executor_capability_discovery_for_step_v2( - &desired.config, - &desired.environments, - /*skill_turn*/ None, - ) - .await; - let (executor_capability_discovery, _) = self - .executor_capability_discovery_for_step( - &desired.config, - &selected_capability_roots, - &desired.environments, - executor_capability_discovery_v2.as_deref(), - /*skill_turn*/ None, - ) - .await; let mcp_projection = self - .services - .mcp_manager - .runtime_config_for_step( - &desired.config, - &self.services.mcp_thread_init, - &self.services.thread_extension_data, - McpThreadIdentity { - auth_changed: !self - .services - .mcp_runtime - .current_auth_matches(desired.auth.as_ref()), - session_source: &desired.session_source, - originator: &desired.originator, - disabled_plugin_ids: &desired.disabled_plugin_ids, - environments: McpEnvironmentScope::Selected(&environment_selections), - }, + .host_mcp_projection( + &desired, + &selected_capability_roots, &ready_selected_capability_roots, - executor_capability_discovery.as_deref(), - executor_capability_discovery_v2.as_deref(), + /*captured_executor_discovery_v2*/ None, ) .await; self.publish_mcp_runtime( &desired, - mcp_projection, + std::future::ready(mcp_projection).boxed(), &ready_selected_capability_roots, elicitation_reviewer, ) diff --git a/codex-rs/core/src/session/mcp_runtime.rs b/codex-rs/core/src/session/mcp_runtime.rs index a28fd1ed42..f1018a666e 100644 --- a/codex-rs/core/src/session/mcp_runtime.rs +++ b/codex-rs/core/src/session/mcp_runtime.rs @@ -123,7 +123,7 @@ impl Session { }; self.publish_mcp_runtime( &desired, - mcp_projection, + std::future::ready(mcp_projection).boxed(), /*ready_selected_capability_roots*/ &[], Some(self.mcp_elicitation_reviewer()), ) @@ -141,53 +141,73 @@ impl Session { &'a self, config: &'a Config, environments: &'a TurnEnvironmentSnapshot, - mut projection: McpRuntimeProjection, + projection_future: BoxFuture<'a, McpRuntimeProjection>, ) -> BoxFuture<'a, McpRuntimeProjection> { + if self.isolation == codex_extension_api::SessionIsolation::Isolated + || self + .services + .mcp_thread_init + .get::() + .is_some() + || !environments + .turn_environments() + .any(|selected| selected.environment().is_remote()) + { + return projection_future; + } + Box::pin(async move { - if self.isolation == codex_extension_api::SessionIsolation::Isolated - || self - .services - .mcp_thread_init - .get::() - .is_some() - { - return projection; - } - - let mut catalog = None; - for selected in environments.turn_environments() { - let environment = selected.environment(); - if !environment.is_remote() { - continue; - } - - let environment_id = &selected.selection.environment_id; - let discovery = environment - .discover_http_mcp_servers(selected.cwd().clone()) - .await; - let outcome = if discovery.is_ok() { - "success" - } else { - "error" - }; - // Count completed discovery attempts, including refreshes, before host policy - // or MCP startup determines whether the server's tools become available. - self.services.session_telemetry.counter( - "codex.mcp.executor_discovery", - /*inc*/ 1, - &[("outcome", outcome)], - ); - let servers = match discovery { - Ok(servers) => servers, - Err(error) => { - tracing::warn!( - environment_id, - %error, - "failed to discover executor-local MCP servers" - ); + // A serial executor can queue config behind root discovery. Each read keeps its + // full timeout after host projection, which also establishes catalog precedence. + let projection_done = tokio::sync::Notify::new(); + let timeout_start_future = projection_done.notified().shared(); + let host_projection_future = + projection_future.inspect(|_| projection_done.notify_one()); + let executor_servers_future = async { + let mut discovered = Vec::new(); + for selected in environments.turn_environments() { + let environment = selected.environment(); + if !environment.is_remote() { continue; } - }; + let environment_id = &selected.selection.environment_id; + let discovery = environment + .discover_http_mcp_servers( + selected.cwd().clone(), + timeout_start_future.clone(), + ) + .await; + let outcome = if discovery.is_ok() { + "success" + } else { + "error" + }; + // Count completed discovery attempts, including refreshes, before host policy + // or MCP startup determines whether the server's tools become available. + self.services.session_telemetry.counter( + "codex.mcp.executor_discovery", + /*inc*/ 1, + &[("outcome", outcome)], + ); + let servers = match discovery { + Ok(servers) => servers, + Err(error) => { + tracing::warn!( + environment_id, + %error, + "failed to discover executor-local MCP servers" + ); + continue; + } + }; + discovered.push((environment_id, servers)); + } + discovered + }; + let (mut projection, discovered) = + tokio::join!(host_projection_future, executor_servers_future); + let mut catalog = None; + for (environment_id, servers) in discovered { for (name, mut server) in servers { let outcome = if server.enabled { "found" @@ -261,7 +281,7 @@ impl Session { pub(super) async fn publish_mcp_runtime( &self, desired: &McpDesiredState, - mcp_projection: McpRuntimeProjection, + projection_future: BoxFuture<'_, McpRuntimeProjection>, ready_selected_capability_roots: &[SelectedCapabilityRoot], elicitation_reviewer: Option, ) { @@ -269,7 +289,7 @@ impl Session { .project_selected_environment_mcp_servers( &desired.config, &desired.environments, - mcp_projection, + projection_future, ) .await; let selected_plugins = mcp_projection.selected_plugins.clone(); diff --git a/codex-rs/core/tests/suite/executor_discovery_v2.rs b/codex-rs/core/tests/suite/executor_discovery_v2.rs index 031e385078..cb5a520e29 100644 --- a/codex-rs/core/tests/suite/executor_discovery_v2.rs +++ b/codex-rs/core/tests/suite/executor_discovery_v2.rs @@ -2,6 +2,7 @@ use anyhow::Context; use anyhow::Result; +use codex_core::StartThreadOptions; use codex_core::TurnInputRequest; use codex_core::config::Config; use codex_core::windows_sandbox::WindowsSandboxLevelExt; @@ -17,6 +18,7 @@ use codex_exec_server::DiscoverV2CapabilitiesResponse; use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot; use codex_exec_server::HttpRequestBodyDeltaNotification; use codex_exec_server::HttpRequestParams; +use codex_extension_api::ExtensionDataInit; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::McpServerContribution; @@ -32,6 +34,8 @@ use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_mcp::McpResourceClient; use codex_mcp_extension::PluginProviders; use codex_mcp_extension::install_plugin_providers; +use codex_protocol::capabilities::CapabilityRootLocation; +use codex_protocol::capabilities::SelectedCapabilityRoot; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -54,6 +58,7 @@ use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; use core_test_support::responses; use core_test_support::skip_if_no_network; +use core_test_support::test_codex::TestEnv; use core_test_support::test_codex::environment_config_for_selection; use core_test_support::test_codex::test_codex; use futures::SinkExt; @@ -177,6 +182,16 @@ impl codex_extension_api::ToolContributor for DiscoveryRecorder { } } +const EXECUTOR_MCP_CONFIG: &str = r#" +[mcp_servers.executor_only] +url = "http://127.0.0.1:1/executor" +enabled = false + +[mcp_servers.host] +url = "http://127.0.0.1:1/override" +enabled = false +"#; + pub(super) struct Executor { pub(super) url: String, pub(super) inventory: Arc>>, @@ -211,13 +226,20 @@ impl Executor { } pub(super) async fn start(supports_v2: bool, failure: DiscoveryFailure) -> Result { - Self::start_with_version(supports_v2, failure, "0.164.0").await + Self::start_with_version( + supports_v2, + failure, + "0.164.0", + /*hold_read_pair*/ None, + ) + .await } async fn start_with_version( supports_v2: bool, failure: DiscoveryFailure, version: &'static str, + hold_read_pair: Option>, ) -> Result { let listener = TcpListener::bind("127.0.0.1:0").await?; let url = format!("ws://{}", listener.local_addr()?); @@ -238,8 +260,10 @@ impl Executor { let inventory = Arc::clone(&served_inventory); let discovery_attempts = Arc::clone(&discovery_attempts); let http = Arc::clone(&http); + let hold_read_pair = hold_read_pair.clone(); connections.spawn(async move { let mut socket = accept_async(stream).await?; + let mut pending_reply = None; while let Some(Ok(message)) = socket.next().await { let request: Value = match message { Message::Text(text) => serde_json::from_str(&text)?, @@ -270,12 +294,19 @@ impl Executor { Some("initialize") => Some(json!({"sessionId":"acquisition-only", "environmentInfo": { "shell":{"name":"bash","path":"/bin/bash"}, "executorVersion":version, - "capabilities":{"sandboxedFileStreaming":true,"capabilityDiscoverySandbox":true,"capabilityDiscoveryV2":supports_v2} + "capabilities":{"sandboxedFileStreaming":true,"capabilityDiscoverySandbox":true,"capabilityDiscoveryV2":supports_v2,"environmentConfigRead":hold_read_pair.is_some()} }})), Some("environment/info") => Some(json!({ "shell":{"name":"bash","path":"/bin/bash"}, "executorVersion":version, - "capabilities":{"sandboxedFileStreaming":true,"capabilityDiscoverySandbox":true,"capabilityDiscoveryV2":supports_v2} + "capabilities":{"sandboxedFileStreaming":true,"capabilityDiscoverySandbox":true,"capabilityDiscoveryV2":supports_v2,"environmentConfigRead":hold_read_pair.is_some()} + })), + Some("environmentConfig/read") if hold_read_pair.is_some() => Some(json!({ + "codexHomeDir":"file:///codex-home", + "config":{"cloudInsertionIndex":0,"layers":[{"source":"fixture","baseDir":"file:///", + "toml":EXECUTOR_MCP_CONFIG}]}, + "requirements":{"cloudInsertionIndex":0,"layers":[{"source":"fixture","baseDir":"file:///", + "toml":"[mcp_servers.unrelated.identity]\nurl='http://127.0.0.1:1/unrelated'"}]} })), Some("capabilityRoots/discoverV1") => Some(json!({ "roots": request["params"]["roots"].as_array().context("V1 roots")? @@ -337,7 +368,20 @@ impl Executor { Some(result) => json!({"id":request["id"],"result":result}), None => json!({"id":request["id"],"error":{"code":-32004,"message":"fixture discovery failure"}}), }; - if socket.send(Message::Text(response.to_string().into())).await.is_err() { break; } + let reply = Message::Text(response.to_string().into()); + // Hold the first reply until the other RPC reaches this connection. + if let Some(armed) = &hold_read_pair + && armed.load(Ordering::SeqCst) + && matches!(request["method"].as_str(), Some("capabilities/discoverV2" | "capabilityRoots/discoverV1" | "environmentConfig/read")) + { + let Some(first) = pending_reply.take() else { + pending_reply = Some(reply); + continue; + }; + socket.send(first).await?; + armed.store(false, Ordering::SeqCst); + } + if socket.send(reply).await.is_err() { break; } } anyhow::Ok(()) }); @@ -354,6 +398,129 @@ impl Executor { } } +#[test_case::test_case("capabilityRoots/discoverV1"; "V1")] +#[test_case::test_case("capabilities/discoverV2"; "V2")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn executor_config_read_overlaps_discovery(discovery_method: &'static str) -> Result<()> { + skip_if_no_network!(Ok(())); + let hold_read_pair = Arc::new(AtomicBool::new(false)); + let executor = Executor::start_with_version( + /*supports_v2*/ true, + DiscoveryFailure::None, + "0.164.0", + Some(hold_read_pair.clone()), + ) + .await?; + let model = responses::start_mock_server().await; + // This test needs a controlled remote executor regardless of the test runner's platform. + let environment = TestEnv::local_with_exec_server_url(Some(executor.url.clone())).await?; + let fixture = test_codex() + .with_config(move |config| { + config + .mcp_servers + .set( + serde_json::from_value(json!({ + "host": {"url": "http://127.0.0.1:1/host", "enabled": false} + })) + .expect("host server config"), + ) + .expect("set host server"); + config + .features + .enable(Feature::ExecutorCapabilityDiscovery) + .expect("enable V1"); + config + .features + .set_enabled( + Feature::ExecutorCapabilityDiscoveryV2, + discovery_method == "capabilities/discoverV2", + ) + .expect("set discovery version"); + }) + .build_with_environment(&model, environment) + .await?; + let selection = fixture.executor_environment().selection().clone(); + let mut extension_init = ExtensionDataInit::new(); + extension_init.insert(vec![SelectedCapabilityRoot { + id: "overlap-root".to_string(), + location: CapabilityRootLocation::Environment { + environment_id: selection.environment_id.clone(), + path: selection.cwd.clone(), + }, + }]); + let thread = fixture + .thread_manager + .start_thread(StartThreadOptions { + environments: Some(vec![selection.clone().into_request()]), + thread_extension_init: extension_init, + ..StartThreadOptions::new(fixture.config.clone()) + }) + .await? + .thread; + // Mark the runtime dirty; for V2 this also evicts the inventory prewarmed at startup. + thread.invalidate_executor_discovery(); + let response = responses::mount_sse_once( + &model, + responses::sse(vec![responses::ev_completed("overlap-turn")]), + ) + .await; + executor.requests.lock().await.clear(); + hold_read_pair.store(true, Ordering::SeqCst); + let (config, _) = tokio::time::timeout(Duration::from_secs(5), async { + thread + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: "Say hello".into(), + text_elements: Vec::new(), + }])) + .await?; + core_test_support::wait_for_event(&thread, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + thread + .mcp_server_status_snapshot( + "host", + /*environment_id*/ None, + codex_mcp::McpSnapshotDetail::ToolsAndAuthOnly, + /*expected_registration*/ None, + ) + .await + }) + .await + .context("both executor reads must be in flight before either completes")??; + response.single_request(); + { + let mut reads = Vec::new(); + let requests = executor.requests.lock().await; + for request in requests.iter() { + let Some(method) = request["method"].as_str() else { + continue; + }; + let path = match method { + "capabilityRoots/discoverV1" => &request["params"]["roots"][0]["path"], + "capabilities/discoverV2" | "environmentConfig/read" => &request["params"]["cwd"], + _ => continue, + }; + assert_eq!(path, &json!(selection.cwd)); + reads.push(method); + } + reads.sort(); + assert_eq!(reads, [discovery_method, "environmentConfig/read"]); + } + let servers = codex_mcp::configured_mcp_servers(&config); + assert!(matches!( + servers["executor_only"].disabled_reason, + Some(codex_config::McpServerDisabledReason::Requirements { .. }) + )); + let host_url = match &servers["host"].transport { + codex_config::McpServerTransportConfig::StreamableHttp { url, .. } => url, + _ => anyhow::bail!("host server must remain HTTP"), + }; + assert_eq!(host_url, "http://127.0.0.1:1/host"); + thread.shutdown_and_wait().await?; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn v2_disabled_skips_inventory_discovery() -> Result<()> { check_acquisition(/*enabled*/ false, "0.164.0").await @@ -1233,8 +1400,13 @@ async fn v2_old_executor_retains_v1_selected_roots() -> Result<()> { pub(super) async fn check_acquisition(enabled: bool, version: &'static str) -> Result<()> { skip_if_no_network!(Ok(())); - let executor = - Executor::start_with_version(/*supports_v2*/ true, DiscoveryFailure::None, version).await?; + let executor = Executor::start_with_version( + /*supports_v2*/ true, + DiscoveryFailure::None, + version, + /*hold_read_pair*/ None, + ) + .await?; let acquires_v2 = enabled && version == "0.164.0"; if acquires_v2 { *executor.inventory.lock().await = Some(json!({"plugins":[],"skills":[],"warnings":[]})); diff --git a/codex-rs/exec-server/src/environment_config.rs b/codex-rs/exec-server/src/environment_config.rs index e738a5d135..2386814971 100644 --- a/codex-rs/exec-server/src/environment_config.rs +++ b/codex-rs/exec-server/src/environment_config.rs @@ -95,29 +95,27 @@ fn include_startup_preference( } impl Environment { - /// Reads executor-owned HTTP MCP servers from the selected project's current config. + /// Reads executor-owned HTTP MCP servers, allowing the full timeout after `timeout_start`. pub async fn discover_http_mcp_servers( &self, cwd: PathUri, + timeout_start: impl Future, ) -> Result, ExecServerError> { - let (response, http_header_env_vars) = - tokio::time::timeout(std::time::Duration::from_secs(10), async { - let capabilities = self.info().await?.capabilities; - if !capabilities.environment_config_read { - return Ok((None, false)); - } - self.read_environment_config(EnvironmentConfigReadParams { - cwd, - config_paths: vec![vec!["mcp_servers".to_string()]], - requirements_paths: vec![vec!["mcp_servers".to_string()]], - }) - .await - .map(|response| (Some(response), capabilities.http_header_env_vars)) + let request = async { + let capabilities = self.info().await?.capabilities; + if !capabilities.environment_config_read { + return Ok((None, false)); + } + self.read_environment_config(EnvironmentConfigReadParams { + cwd, + config_paths: vec![vec!["mcp_servers".to_string()]], + requirements_paths: vec![vec!["mcp_servers".to_string()]], }) .await - .map_err(|_| { - ExecServerError::Protocol("executor MCP discovery timed out".to_string()) - })??; + .map(|response| (Some(response), capabilities.http_header_env_vars)) + }; + let (response, http_header_env_vars) = + mcp_discovery_with_timeout(request, timeout_start).await?; let Some(response) = response else { return Ok(Vec::new()); }; @@ -174,6 +172,21 @@ impl Environment { } } +async fn mcp_discovery_with_timeout( + request: impl Future>, + timeout_start: impl Future, +) -> Result { + let deadline = async { + timeout_start.await; + tokio::time::sleep(std::time::Duration::from_secs(10)).await; + }; + tokio::select! { + biased; + result = request => result, + () = deadline => Err(ExecServerError::Protocol("executor MCP discovery timed out".to_string())), + } +} + fn validate_paths(params: &EnvironmentConfigReadParams) -> Result<(), ReadEnvironmentConfigError> { if params.config_paths.is_empty() && params.requirements_paths.is_empty() { return Err(ReadEnvironmentConfigError::InvalidParams( diff --git a/codex-rs/exec-server/src/environment_config_tests.rs b/codex-rs/exec-server/src/environment_config_tests.rs index e7c5b05eeb..2fa4f921fc 100644 --- a/codex-rs/exec-server/src/environment_config_tests.rs +++ b/codex-rs/exec-server/src/environment_config_tests.rs @@ -1,5 +1,8 @@ use super::*; use pretty_assertions::assert_eq; +use std::time::Duration; +use tokio::time::Instant; +use tokio::time::sleep; /// Legacy file and MDM values must still win after a CLI preference is projected. #[test] @@ -50,3 +53,29 @@ fn startup_preference_stays_below_both_managed_layers() -> anyhow::Result<()> { } Ok(()) } + +#[tokio::test(start_paused = true)] +async fn config_queued_behind_discovery_keeps_its_original_timeout() { + // The executor handles discovery first, then finishes the pending config request. + let queued_config = async { + sleep(Duration::from_secs(14)).await; + Ok(()) + }; + let discovery = sleep(Duration::from_secs(12)); + mcp_discovery_with_timeout(queued_config, discovery) + .await + .expect("a 2-second config read after discovery should finish"); + + let start = Instant::now(); + let hung_config = std::future::pending::>(); + let discovery = sleep(Duration::from_secs(12)); + let error = mcp_discovery_with_timeout(hung_config, discovery) + .await + .expect_err("a stalled config read must time out"); + assert!( + error + .to_string() + .contains("executor MCP discovery timed out") + ); + assert_eq!(start.elapsed(), Duration::from_secs(22)); +}