Avoid blocking thread startup on MCP OAuth discovery (#32825)

## Why

OAuth metadata discovery for an optional HTTP MCP server can stall, delaying
`thread/start` even though that server is not required.

## What changed

- Remove eager MCP authentication-status discovery from session and connection
  manager startup.
- When an MCP connection reports an authentication error, inspect configured and
  stored credentials locally to preserve login and reauthentication failure
  reasons without making another discovery request.
- Continue using server configuration directly for startup error messages and
  timeout hints.

## Testing

Add an app-server regression test with an optional HTTP MCP endpoint that accepts
a connection but never responds, and verify that `thread/start` completes without
waiting for its configured startup timeout.

GitOrigin-RevId: 56fe0188cc1ceaf746b0b65e8b7dd1fd2e13420d
This commit is contained in:
jif authored and copyberry committed 2026-07-13 15:47:03 +00:00
1 parent 4ebc61c0f8
commit 2e156cbe31
12 files changed
+219 -139

No files matched your search

+59 -29
View File
@@ -13,7 +13,6 @@ use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use crate::McpAuthStatusEntry;
use crate::codex_apps::prepare_openai_file_params_for_model;
use crate::elicitation::ElicitationRequestManager;
use crate::elicitation::ElicitationRequestRouter;
@@ -41,6 +40,7 @@ use async_channel::Sender;
use codex_api::SharedAuthProvider;
use codex_config::Constrained;
use codex_config::McpServerAuth;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
@@ -63,6 +63,7 @@ use codex_protocol::protocol::McpStartupUpdateEvent;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::McpAuthState;
use codex_rmcp_client::McpLoginRequirement;
use codex_rmcp_client::determine_streamable_http_auth_status_from_credentials;
use rmcp::model::ElicitationCapability;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
@@ -127,7 +128,6 @@ impl McpConnectionManager {
mcp_servers: &HashMap<String, EffectiveMcpServer>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
auth_entries: HashMap<String, McpAuthStatusEntry>,
approval_policy: &Constrained<AskForApproval>,
submit_id: String,
tx_event: Sender<Event>,
@@ -189,18 +189,20 @@ impl McpConnectionManager {
},
)
.await;
let configured_config = server.configured_config();
let configured_config = server.configured_config().cloned();
// For built-in Codex Apps, `CODEX_CONNECTORS_TOKEN` is a debug
// override: it supplies runtime auth but bypasses the shared tools
// cache.
let uses_env_bearer_token =
configured_config.is_some_and(|config| match &config.transport {
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
..
} => bearer_token_env_var.is_some(),
McpServerTransportConfig::Stdio { .. } => false,
});
configured_config
.as_ref()
.is_some_and(|config| match &config.transport {
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
..
} => bearer_token_env_var.is_some(),
McpServerTransportConfig::Stdio { .. } => false,
});
let shares_codex_apps_tools_cache =
should_share_codex_apps_tools_cache(&server_name, uses_env_bearer_token);
let codex_apps_tools_cache_context = shares_codex_apps_tools_cache.then(|| {
@@ -226,6 +228,7 @@ impl McpConnectionManager {
} else {
chatgpt_auth_provider_for_server(&server, chatgpt_auth_provider)
};
let has_runtime_auth = runtime_auth_provider.is_some();
let async_managed_client = AsyncManagedClient::new(
server_name.clone(),
startup_submit_id.clone(),
@@ -245,20 +248,55 @@ impl McpConnectionManager {
clients.insert(server_name.clone(), async_managed_client.clone());
let tx_event = tx_event.clone();
let submit_id = startup_submit_id.clone();
let auth_entry = auth_entries.get(&server_name).cloned();
join_set.spawn(async move {
let mut outcome = async_managed_client.client().await;
if cancel_token.is_cancelled() {
outcome = Err(StartupOutcomeError::Cancelled);
}
let auth_state = match &outcome {
Err(error) if error.is_authentication_required() && !has_runtime_auth => {
configured_config.as_ref().and_then(|config| {
let McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
} = &config.transport
else {
return None;
};
match determine_streamable_http_auth_status_from_credentials(
&server_name,
url,
bearer_token_env_var.as_deref(),
http_headers.clone(),
env_http_headers.clone(),
store_mode,
keyring_backend_kind,
) {
Ok(auth_state) => auth_state,
Err(error) => {
warn!(
"failed to read stored auth status for MCP server `{server_name}`: {error:?}"
);
None
}
}
})
}
Ok(_) | Err(_) => None,
};
if cancel_token.is_cancelled() {
outcome = Err(StartupOutcomeError::Cancelled);
}
let status = match &outcome {
Ok(_) => McpStartupStatus::Ready,
Err(StartupOutcomeError::Cancelled) => McpStartupStatus::Cancelled,
Err(error) => {
let reason = mcp_startup_failure_reason(auth_entry.as_ref(), error);
let reason = mcp_startup_failure_reason(auth_state, error);
let error_str = mcp_init_error_display(
server_name.as_str(),
auth_entry.as_ref(),
configured_config.as_ref(),
error,
);
McpStartupStatus::Failed {
@@ -960,14 +998,14 @@ async fn emit_update(
}
fn mcp_startup_failure_reason(
entry: Option<&McpAuthStatusEntry>,
auth_state: Option<McpAuthState>,
error: &StartupOutcomeError,
) -> Option<McpStartupFailureReason> {
if !error.is_authentication_required() {
return None;
}
match entry.map(|entry| entry.auth_state) {
match auth_state {
Some(McpAuthState::LoggedOut(McpLoginRequirement::Reauthentication)) => {
Some(McpStartupFailureReason::ReauthenticationRequired)
}
@@ -983,7 +1021,7 @@ fn mcp_startup_failure_reason(
fn mcp_init_error_display(
server_name: &str,
entry: Option<&McpAuthStatusEntry>,
config: Option<&McpServerConfig>,
err: &StartupOutcomeError,
) -> String {
if let Some(McpServerTransportConfig::StreamableHttp {
@@ -991,7 +1029,7 @@ fn mcp_init_error_display(
bearer_token_env_var,
http_headers,
..
}) = entry.and_then(|entry| entry.config.as_ref().map(|config| &config.transport))
}) = config.map(|config| &config.transport)
&& url == "https://api.githubcopilot.com/mcp/"
&& bearer_token_env_var.is_none()
&& http_headers.as_ref().map(HashMap::is_empty).unwrap_or(true)
@@ -1004,18 +1042,10 @@ fn mcp_init_error_display(
"The {server_name} MCP server is not logged in. Run `codex mcp login {server_name}`."
)
} else if is_mcp_client_startup_timeout_error(err) {
let startup_timeout_secs = match entry {
Some(entry) => match entry
.config
.as_ref()
.and_then(|config| config.startup_timeout_sec)
{
Some(timeout) => timeout,
None => DEFAULT_STARTUP_TIMEOUT,
},
None => DEFAULT_STARTUP_TIMEOUT,
}
.as_secs();
let startup_timeout_secs = config
.and_then(|config| config.startup_timeout_sec)
.unwrap_or(DEFAULT_STARTUP_TIMEOUT)
.as_secs();
format!(
"MCP client for `{server_name}` timed out after {startup_timeout_secs} seconds. Add or adjust `startup_timeout_sec` in your config.toml:\n[mcp_servers.{server_name}]\nstartup_timeout_sec = XX"
)