Overlap MCP refresh with executor capability discovery (#65343)

## Why

When an MCP refresh waits for host setup to finish before reading the
remote executor's MCP configuration, a capability cache miss can make
the two remote reads run back to back.

## What changed

Run host MCP setup alongside remote MCP server discovery. Start the
remote read during host setup and keep its timeout gated on host
completion. Carry the ready capability roots from host setup into the
published runtime.

## Testing

Extend the V1 and V2 overlap tests to hold replies until both requests
are in flight, then verify that the turn can call a tool from the newly
discovered MCP server and receive its result.

GitOrigin-RevId: 729eb6a85e8a8ce6e2549251de9873a0b064d9a7
This commit is contained in:
Dmitriy Kovalenko
2026-12-02 22:01:23 +00:00
committed by copyberry
parent cffa2fddad
commit 04ea445ecd
7 changed files with 178 additions and 148 deletions
+6 -2
View File
@@ -53,6 +53,7 @@ pub struct McpServersDisabled;
#[derive(Clone)]
pub(crate) struct McpRuntimeProjection {
pub(crate) config: McpConfig,
pub(crate) ready_selected_capability_roots: Vec<SelectedCapabilityRoot>,
pub(crate) plugins_available: bool,
pub(crate) selected_plugins: SelectedPluginSnapshot,
}
@@ -229,7 +230,7 @@ impl McpManager {
thread_init: &ExtensionDataInit,
thread_store: &ExtensionData,
identity: McpThreadIdentity<'_>,
ready_selected_capability_roots: &[SelectedCapabilityRoot],
ready_selected_capability_roots: Vec<SelectedCapabilityRoot>,
executor_capability_discovery: Option<&ExecutorCapabilityDiscoverySnapshot>,
executor_capability_discovery_v2: Option<&[ExecutorCapabilityDiscoveryV2Snapshot]>,
) -> McpRuntimeProjection {
@@ -238,7 +239,7 @@ impl McpManager {
thread_init,
thread_store,
identity.originator,
ready_selected_capability_roots,
&ready_selected_capability_roots,
executor_capability_discovery,
executor_capability_discovery_v2,
)
@@ -255,6 +256,7 @@ impl McpManager {
identity.disabled_plugin_ids,
)
.await;
projection.ready_selected_capability_roots = ready_selected_capability_roots;
projection.config.executor_discovery_v2 = executor_capability_discovery_v2.map(Arc::from);
projection
}
@@ -341,6 +343,7 @@ impl McpManager {
mcp_config.apps_enabled = false;
return McpRuntimeProjection {
config: mcp_config,
ready_selected_capability_roots: Vec::new(),
plugins_available: false,
selected_plugins: Default::default(),
};
@@ -595,6 +598,7 @@ impl McpManager {
mcp_config.connector_snapshot = connector_snapshot;
McpRuntimeProjection {
config: mcp_config,
ready_selected_capability_roots: Vec::new(),
plugins_available,
selected_plugins: SelectedPluginSnapshot {
plugins: selected_plugins,
+32 -42
View File
@@ -176,7 +176,7 @@ impl Session {
disabled_plugin_ids: &disabled_plugin_ids,
environments: McpEnvironmentScope::Selected(&environment_selections),
},
&ready_selected_capability_roots,
ready_selected_capability_roots,
executor_capability_discovery.as_deref(),
executor_capability_discovery_v2.as_deref(),
)
@@ -292,23 +292,10 @@ impl Session {
// Keep current MCP authority even when reusing the step's executor inventory.
let environments = self.services.turn_environments.snapshot().await;
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 projection_future = self
.host_mcp_projection(
&desired,
&selected_capability_roots,
&ready_selected_capability_roots,
captured_executor_discovery_v2,
)
.boxed();
self.publish_mcp_runtime(
&desired,
projection_future,
&ready_selected_capability_roots,
self.host_mcp_projection(&desired, captured_executor_discovery_v2)
.boxed(),
Some(self.mcp_elicitation_reviewer()),
)
.await;
@@ -317,10 +304,29 @@ impl Session {
}
async fn host_mcp_projection(
&self,
desired: &McpDesiredState,
captured_executor_discovery_v2: Option<&[ExecutorCapabilityDiscoveryV2Snapshot]>,
) -> McpRuntimeProjection {
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);
self.host_mcp_projection_with_roots(
desired,
&selected_capability_roots,
ready_selected_capability_roots,
captured_executor_discovery_v2,
)
.await
}
async fn host_mcp_projection_with_roots(
&self,
desired: &McpDesiredState,
selected_capability_roots: &[ResolvedSelectedCapabilityRoot],
ready_selected_capability_roots: &[SelectedCapabilityRoot],
ready_selected_capability_roots: Vec<SelectedCapabilityRoot>,
captured_executor_discovery_v2: Option<&[ExecutorCapabilityDiscoveryV2Snapshot]>,
) -> McpRuntimeProjection {
let environment_selections = desired.environments.all_selections();
@@ -435,31 +441,18 @@ impl Session {
let auth = self.services.auth_manager.auth().await;
let environments = self.services.turn_environments.snapshot().await;
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 mcp_projection = self
.host_mcp_projection(
&desired,
&selected_capability_roots,
&ready_selected_capability_roots,
/*captured_executor_discovery_v2*/ None,
)
.await;
let mcp_projection = self
.project_selected_environment_mcp_servers(
&desired.config,
&desired.environments,
std::future::ready(mcp_projection).boxed(),
self.host_mcp_projection(&desired, /*captured_executor_discovery_v2*/ None)
.boxed(),
)
.await;
let selected_plugins = mcp_projection.selected_plugins.clone();
let input = self.build_mcp_runtime_input(
&desired,
mcp_projection,
&ready_selected_capability_roots,
Some(self.mcp_elicitation_reviewer()),
);
anyhow::ensure!(
@@ -948,18 +941,15 @@ impl Session {
)
.await;
let desired = self.latest_mcp_desired_state(auth, environments).await;
let mcp_projection = self
.host_mcp_projection(
&desired,
&selected_capability_roots,
&ready_selected_capability_roots,
/*captured_executor_discovery_v2*/ None,
)
.await;
self.publish_mcp_runtime(
&desired,
std::future::ready(mcp_projection).boxed(),
&ready_selected_capability_roots,
self.host_mcp_projection_with_roots(
&desired,
&selected_capability_roots,
ready_selected_capability_roots,
/*captured_executor_discovery_v2*/ None,
)
.boxed(),
elicitation_reviewer,
)
.await;
+64 -56
View File
@@ -18,7 +18,6 @@ use codex_mcp::McpStartupPolicy;
use codex_mcp::PreparedMcpCall;
use codex_mcp::ToolInfo;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_protocol::capabilities::SelectedCapabilityRoot;
pub(super) struct McpDesiredState {
pub(super) config: Arc<Config>,
@@ -31,6 +30,11 @@ pub(super) struct McpDesiredState {
pub(super) disabled_plugin_ids: Vec<String>,
}
struct ExecutorMcpServers<'a> {
environment_id: &'a str,
servers: Vec<(String, McpServerConfig)>,
}
impl Session {
pub(super) fn mcp_inputs_differ(
&self,
@@ -124,7 +128,6 @@ impl Session {
self.publish_mcp_runtime(
&desired,
std::future::ready(mcp_projection).boxed(),
/*ready_selected_capability_roots*/ &[],
Some(self.mcp_elicitation_reviewer()),
)
.instrument(info_span!(
@@ -163,51 +166,16 @@ impl Session {
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 projection, discovered) = tokio::join!(
host_projection_future,
self.discover_selected_environment_mcp_servers(environments, timeout_start_future)
);
let mut catalog = None;
for (environment_id, servers) in discovered {
for ExecutorMcpServers {
environment_id,
servers,
} in discovered
{
for (name, mut server) in servers {
let outcome = if server.enabled {
"found"
@@ -242,7 +210,7 @@ impl Session {
);
continue;
}
server.environment_id = environment_id.clone();
server.environment_id = environment_id.to_owned();
if let Some(requirements) = config
.config_layer_stack
.requirements()
@@ -277,12 +245,57 @@ impl Session {
})
}
async fn discover_selected_environment_mcp_servers<'a>(
&self,
environments: &'a TurnEnvironmentSnapshot,
timeout_start: impl Future<Output = ()> + Clone,
) -> Vec<ExecutorMcpServers<'a>> {
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.as_str();
let discovery = environment
.discover_http_mcp_servers(selected.cwd().clone(), timeout_start.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(ExecutorMcpServers {
environment_id,
servers,
});
}
discovered
}
#[tracing::instrument(name = "mcp.runtime.refresh", skip_all)]
pub(super) async fn publish_mcp_runtime(
&self,
desired: &McpDesiredState,
projection_future: BoxFuture<'_, McpRuntimeProjection>,
ready_selected_capability_roots: &[SelectedCapabilityRoot],
elicitation_reviewer: Option<ElicitationReviewerHandle>,
) {
let mcp_projection = self
@@ -293,12 +306,7 @@ impl Session {
)
.await;
let selected_plugins = mcp_projection.selected_plugins.clone();
let input = self.build_mcp_runtime_input(
desired,
mcp_projection,
ready_selected_capability_roots,
elicitation_reviewer,
);
let input = self.build_mcp_runtime_input(desired, mcp_projection, elicitation_reviewer);
AuthStorageOriginator::from_client_name(&desired.originator)
.scope(self.services.mcp_runtime.replace(input))
.await;
@@ -367,13 +375,13 @@ impl Session {
&self,
desired: &McpDesiredState,
mcp_projection: McpRuntimeProjection,
ready_selected_capability_roots: &[SelectedCapabilityRoot],
elicitation_reviewer: Option<ElicitationReviewerHandle>,
) -> McpRuntimeInput {
let auth = desired.auth.clone();
let McpRuntimeProjection {
mut config,
plugins_available,
ready_selected_capability_roots,
selected_plugins: _,
} = mcp_projection;
config.host_cwd = desired.config.cwd.clone();
@@ -411,7 +419,7 @@ impl Session {
},
config: mcp_config,
plugins_available,
ready_selected_capability_roots: ready_selected_capability_roots.to_vec(),
ready_selected_capability_roots,
mcp_servers,
submit_id: desired.submit_id.clone(),
tx_event: Some(self.get_tx_event()),
+2 -2
View File
@@ -1338,7 +1338,7 @@ impl Session {
disabled_plugin_ids: &mcp_disabled_plugin_ids,
environments: McpEnvironmentScope::Selected(environment_selections),
},
/*ready_selected_capability_roots*/ &[],
/*ready_selected_capability_roots*/ Vec::new(),
/*executor_capability_discovery*/ None,
/*executor_capability_discovery_v2*/ None,
)
@@ -2230,7 +2230,7 @@ impl Session {
&resolved_environment_selections,
),
},
/*ready_selected_capability_roots*/ &[],
/*ready_selected_capability_roots*/ Vec::new(),
/*executor_capability_discovery*/ None,
/*executor_capability_discovery_v2*/ None,
)
+1 -1
View File
@@ -6408,10 +6408,10 @@ async fn mcp_runtime_keeps_local_backend_without_a_selected_local_environment()
&desired,
crate::mcp::McpRuntimeProjection {
config: (*mcp_config_for_test(&desired.config)).clone(),
ready_selected_capability_roots: Vec::new(),
plugins_available: false,
selected_plugins: Default::default(),
},
&[],
/*elicitation_reviewer*/ None,
);
assert_eq!(
+2 -2
View File
@@ -2360,7 +2360,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
&second_session.services.turn_environments.selections(),
),
},
/*ready_selected_capability_roots*/ &[],
/*ready_selected_capability_roots*/ Vec::new(),
/*executor_capability_discovery*/ None,
/*executor_capability_discovery_v2*/ None,
)
@@ -2514,7 +2514,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
&first_session.services.turn_environments.selections(),
),
},
/*ready_selected_capability_roots*/ &[],
/*ready_selected_capability_roots*/ Vec::new(),
/*executor_capability_discovery*/ None,
/*executor_capability_discovery_v2*/ None,
)
@@ -54,6 +54,7 @@ use codex_skills_extension::catalog::SkillSourceKind;
use codex_skills_extension::install_with_providers;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::apps_enabled_builder;
use core_test_support::apps_test_server::recorded_apps_tool_call_by_name;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::responses;
@@ -230,7 +231,7 @@ impl Executor {
supports_v2,
failure,
"0.164.0",
/*hold_read_pair*/ None,
/*refresh_server_url*/ None,
)
.await
}
@@ -239,7 +240,7 @@ impl Executor {
supports_v2: bool,
failure: DiscoveryFailure,
version: &'static str,
hold_read_pair: Option<Arc<AtomicBool>>,
refresh_server_url: Option<Arc<OnceLock<String>>>,
) -> Result<Self> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("ws://{}", listener.local_addr()?);
@@ -260,10 +261,11 @@ 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();
let refresh_server_url = refresh_server_url.clone();
connections.spawn(async move {
let mut socket = accept_async(stream).await?;
let mut pending_reply = None;
let mut pair_released = false;
while let Some(Ok(message)) = socket.next().await {
let request: Value = match message {
Message::Text(text) => serde_json::from_str(&text)?,
@@ -294,20 +296,28 @@ 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,"environmentConfigRead":hold_read_pair.is_some()}
"capabilities":{"sandboxedFileStreaming":true,"capabilityDiscoverySandbox":true,"capabilityDiscoveryV2":supports_v2,"environmentConfigRead":refresh_server_url.is_some()}
}})),
Some("environment/info") => Some(json!({
"shell":{"name":"bash","path":"/bin/bash"},
"executorVersion":version,
"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'"}]}
"capabilities":{"sandboxedFileStreaming":true,"capabilityDiscoverySandbox":true,"capabilityDiscoveryV2":supports_v2,"environmentConfigRead":refresh_server_url.is_some()}
})),
Some("environmentConfig/read") if let Some(url) = &refresh_server_url => {
let mut config = EXECUTOR_MCP_CONFIG.to_owned();
let mut requirements = "[mcp_servers]".to_owned();
if let Some(url) = url.get() {
config.push_str(&format!("\n[mcp_servers.notes]\nurl='{url}'\nrequired=true"));
requirements.push_str(&format!("\n[mcp_servers.notes.identity]\nurl='{url}'"));
}
Some(json!({
"codexHomeDir":"file:///codex-home",
"config":{"cloudInsertionIndex":0,"layers":[{"source":"fixture","baseDir":"file:///",
"toml":config}]},
"requirements":{"cloudInsertionIndex":0,"layers":[{"source":"fixture","baseDir":"file:///",
"toml":requirements}]}
}))
}
Some("capabilityRoots/discoverV1") => Some(json!({
"roots": request["params"]["roots"].as_array().context("V1 roots")?
.iter().map(|root| json!({
@@ -370,8 +380,8 @@ impl Executor {
};
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)
if !pair_released
&& refresh_server_url.as_ref().is_some_and(|url| url.get().is_some())
&& matches!(request["method"].as_str(), Some("capabilities/discoverV2" | "capabilityRoots/discoverV1" | "environmentConfig/read"))
{
let Some(first) = pending_reply.take() else {
@@ -379,7 +389,7 @@ impl Executor {
continue;
};
socket.send(first).await?;
armed.store(false, Ordering::SeqCst);
pair_released = true;
}
if socket.send(reply).await.is_err() { break; }
}
@@ -403,18 +413,27 @@ impl Executor {
#[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 refresh_server_url = Arc::new(OnceLock::new());
let executor = Executor::start_with_version(
/*supports_v2*/ true,
DiscoveryFailure::None,
"0.164.0",
Some(hold_read_pair.clone()),
Some(Arc::clone(&refresh_server_url)),
)
.await?;
let model = responses::start_mock_server().await;
let apps = AppsTestServer::mount_with_tools(
&model,
Arc::new(std::sync::Mutex::new(vec![json!({
"name": "echo", "description": "Read a note.", "annotations": {"readOnlyHint": true},
"inputSchema": {"type": "object", "properties": {}}
})])),
)
.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_model_info_override("gpt-5.5", |model| model.supports_search_tool = false)
.with_config(move |config| {
config
.mcp_servers
@@ -459,36 +478,45 @@ async fn executor_config_read_overlaps_discovery(discovery_method: &'static str)
.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(
let response = responses::mount_sse_sequence(
&model,
responses::sse(vec![responses::ev_completed("overlap-turn")]),
vec![
responses::sse(vec![
responses::ev_function_call_with_namespace("read", "mcp__notes", "echo", "{}"),
responses::ev_completed("first"),
]),
responses::sse(vec![responses::ev_completed("second")]),
],
)
.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(_))
})
// The new tool is available only from the config read paired with this cache miss.
refresh_server_url
.set(format!("{}/api/codex/ps/mcp", apps.chatgpt_base_url))
.expect("arm the executor after setup");
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 requests = response.requests();
assert_eq!(requests.len(), 2);
for request in &requests {
assert!(request.tool_by_name("mcp__notes", "echo").is_some());
}
recorded_apps_tool_call_by_name(&model, "echo").await;
assert!(requests[1].function_call_output_text("read").is_some());
let (config, _) = thread
.mcp_server_status_snapshot(
"host",
/*environment_id*/ None,
codex_mcp::McpSnapshotDetail::ToolsAndAuthOnly,
/*expected_registration*/ None,
)
.await?;
{
let mut reads = Vec::new();
let requests = executor.requests.lock().await;
@@ -1404,7 +1432,7 @@ pub(super) async fn check_acquisition(enabled: bool, version: &'static str) -> R
/*supports_v2*/ true,
DiscoveryFailure::None,
version,
/*hold_read_pair*/ None,
/*refresh_server_url*/ None,
)
.await?;
let acquires_v2 = enabled && version == "0.164.0";