[codex-mcp] Preserve fast MCP startup during turns

This commit is contained in:
malsamiri
2026-07-08 15:05:34 -07:00
parent 117deb3243
commit 13e05edf07
4 changed files with 92 additions and 23 deletions
+26 -9
View File
@@ -84,11 +84,16 @@ use tracing::warn;
const MCP_UI_META_KEY: &str = "ui";
const MCP_UI_VISIBILITY_META_KEY: &str = "visibility";
const MCP_UI_MODEL_VISIBILITY: &str = "model";
// Optional MCP startup happens concurrently with turn setup. Give healthy
// servers a short chance to finish so their tools are not dropped only because
// the background startup task has not been scheduled yet, while still keeping
// a slow optional server from holding the turn until its configured timeout.
const OPTIONAL_MCP_TURN_STARTUP_GRACE: Duration = Duration::from_secs(1);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PendingOptionalToolListing {
WaitForStartup,
SkipWithoutCache,
SkipAfterStartupGrace,
}
/// Returns whether a tool may be included in model-facing tool declarations.
@@ -494,9 +499,10 @@ impl McpConnectionManager {
.await
}
/// Returns tools available to a turn without waiting for uncached optional servers to start.
/// Returns tools available to a turn after giving uncached optional servers a short
/// startup grace period.
pub async fn list_all_tools_for_turn(&self) -> Vec<ToolInfo> {
self.list_all_tools_with_pending_optional(PendingOptionalToolListing::SkipWithoutCache)
self.list_all_tools_with_pending_optional(PendingOptionalToolListing::SkipAfterStartupGrace)
.await
}
@@ -519,16 +525,27 @@ impl McpConnectionManager {
startup_complete,
"listing MCP server tools while building tool list"
);
if pending_optional == PendingOptionalToolListing::SkipWithoutCache
if pending_optional == PendingOptionalToolListing::SkipAfterStartupGrace
&& !required
&& !startup_complete
&& !has_cached_tools
{
trace!(
server_name = %server_name,
"skipping pending optional MCP server without cached tools"
);
return None;
return match tokio::time::timeout(
OPTIONAL_MCP_TURN_STARTUP_GRACE,
managed_client.listed_tools(),
)
.await
{
Ok(server_tools) => server_tools,
Err(_) => {
trace!(
server_name = %server_name,
grace_ms = OPTIONAL_MCP_TURN_STARTUP_GRACE.as_millis(),
"skipping pending optional MCP server without cached tools"
);
None
}
};
}
if required && !startup_complete && has_cached_tools {
let _ = managed_client.client().await;
@@ -988,8 +988,8 @@ async fn list_all_tools_applies_legacy_mcp_prefix_by_default() {
);
}
#[tokio::test]
async fn list_all_tools_for_turn_skips_optional_client_pending_without_cached_tools() {
#[tokio::test(start_paused = true)]
async fn list_all_tools_for_turn_skips_optional_client_after_startup_grace_without_cached_tools() {
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
@@ -1001,10 +1001,10 @@ async fn list_all_tools_for_turn_skips_optional_client_pending_without_cached_to
/*prefix_mcp_tool_names*/ true,
);
manager.clients.insert(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
"pending_optional".to_string(),
AsyncManagedClient {
client: pending_client,
is_codex_apps_mcp_server: true,
is_codex_apps_mcp_server: false,
cached_server_info: None,
codex_apps_tools_cache_context: None,
tool_filter: ToolFilter::default(),
@@ -1015,12 +1015,51 @@ async fn list_all_tools_for_turn_skips_optional_client_pending_without_cached_to
},
);
let tools = tokio::time::timeout(Duration::from_secs(1), manager.list_all_tools_for_turn())
let tools = tokio::time::timeout(Duration::from_secs(2), manager.list_all_tools_for_turn())
.await
.expect("optional client tool listing should not block a turn on startup");
.expect("optional client tool listing should only wait for the startup grace period");
assert!(tools.is_empty());
}
#[tokio::test]
async fn list_all_tools_for_turn_uses_optional_client_that_finishes_during_startup_grace() {
let client = async {
tokio::time::sleep(Duration::from_millis(10)).await;
Ok(create_test_managed_client(vec![create_test_tool("fast_optional", "echo")]).await)
}
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
&permission_profile,
/*prefix_mcp_tool_names*/ true,
);
manager.clients.insert(
"fast_optional".to_string(),
AsyncManagedClient {
client,
is_codex_apps_mcp_server: false,
cached_server_info: None,
codex_apps_tools_cache_context: None,
tool_filter: ToolFilter::default(),
startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)),
startup_reconnect: None,
tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()),
cancel_token: CancellationToken::new(),
},
);
let tools = manager.list_all_tools_for_turn().await;
assert!(
tools.iter().any(|tool| {
tool.canonical_tool_name() == ToolName::namespaced("mcp__fast_optional", "echo")
}),
"fast optional client tools should be available to the turn"
);
}
#[tokio::test]
async fn list_all_tools_waits_for_optional_client_pending_without_cached_tools() {
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
+2 -8
View File
@@ -550,14 +550,8 @@ async fn build_skills_and_plugins(
// Plugin mentions need raw MCP/app inventory even when app tools
// are normally hidden so we can describe the plugin's currently
// usable capabilities for this turn.
match step_context
.mcp
.manager_arc()
.list_all_tools_for_turn()
.or_cancel(cancellation_token)
.await
{
Ok(mcp_tools) => mcp_tools,
match step_context.mcp_tools().or_cancel(cancellation_token).await {
Ok(mcp_tools) => mcp_tools.to_vec(),
Err(_) if turn_context.apps_enabled() => return None,
Err(_) => Vec::new(),
}
+19
View File
@@ -28,6 +28,7 @@ use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::MCP_SANDBOX_STATE_META_CAPABILITY;
use codex_mcp::SandboxState;
use codex_models_manager::manager::RefreshStrategy;
@@ -45,6 +46,7 @@ use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::McpInvocation;
use codex_protocol::protocol::McpStartupStatus;
use codex_protocol::protocol::McpToolCallBeginEvent;
use codex_protocol::protocol::Op;
use codex_protocol::user_input::UserInput;
@@ -738,6 +740,23 @@ async fn apps_enabled_turn_skips_pending_optional_mcp_without_cached_tools() ->
tokio::time::timeout(Duration::from_secs(5), pending_mcp_listener.accept())
.await
.context("optional MCP startup should reach the pending server")??;
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let event = fixture
.codex
.next_event()
.await
.context("event stream ended before Codex Apps became ready")?;
if let EventMsg::McpStartupUpdate(update) = event.msg
&& update.server == CODEX_APPS_MCP_SERVER_NAME
&& matches!(update.status, McpStartupStatus::Ready)
{
break Ok::<(), anyhow::Error>(());
}
}
})
.await
.context("Codex Apps should become ready before exercising pending optional MCP startup")??;
tokio::time::timeout(Duration::from_secs(5), fixture.submit_turn("hello"))
.await
.context("turn should not wait for pending optional MCP startup")??;