Speed up MCP OAuth credential reads (#37860)

## Why

Refreshing MCP connection identities should not stall the async executor while another process holds the OAuth credential-store lock.

## What changed

- Probe file and secrets credential stores without waiting during runtime refreshes, retaining the last known credentials when the store is contended.
- Reuse unchanged authentication failures while credentials are temporarily unavailable instead of restarting the connection.
- Run blocking credential loads on a blocking worker during MCP client construction.
- Allow OAuth fallback when a configured authorization header is missing, empty, or invalid.

GitOrigin-RevId: 38dad5606da9a1ceb30fe945000ec9151a5058fa
This commit is contained in:
jif authored and copyberry committed 2026-08-10 17:58:15 +00:00
1 parent d06dc73290
commit afcc95b431
7 files changed
+329 -44

No files matched your search

+80 -9
View File
@@ -64,6 +64,7 @@ use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::McpStartupCompleteEvent;
use codex_protocol::protocol::McpStartupFailure;
use codex_protocol::protocol::McpStartupFailureReason;
use codex_protocol::protocol::McpStartupStatus;
use codex_protocol::protocol::McpStartupUpdateEvent;
use codex_rmcp_client::determine_streamable_http_auth_status_from_credentials;
@@ -98,6 +99,16 @@ impl McpServerConnection {
if client.client.is_closed().await {
return None;
}
if current == desired {
if matches!(desired.oauth_credentials(), Ok(None))
&& tokio::time::timeout(Duration::ZERO, client.client.managed_oauth_credentials())
.await
.is_ok_and(|credentials| matches!(credentials, Some(Some(_))))
{
return None;
}
return Some(client);
}
let Ok(desired_credentials) = desired.oauth_credentials() else {
return Some(client);
};
@@ -167,6 +178,7 @@ impl McpServerView {
/// A published view over a set of running MCP server connections.
pub(crate) struct McpConnectionSet {
servers: HashMap<String, McpServerView>,
protocol_mode: crate::McpProtocolMode,
required_servers: Vec<String>,
optional_startup_deadline: OnceLock<tokio::time::Instant>,
tool_catalog_revision: Arc<RwLock<u64>>,
@@ -336,6 +348,9 @@ impl McpConnectionSet {
.then(|| (codex_home.clone(), codex_apps_tools_cache_key.clone())),
client_elicitation_capability.clone(),
client_mcp_extensions.clone(),
previous
.and_then(|previous| previous.servers.get(&server_name))
.and_then(|view| view.connection.identity.as_ref()),
);
let expected_protocol_mode = match &configured_config.transport {
McpServerTransportConfig::StreamableHttp { .. } => Some(protocol_mode),
@@ -361,14 +376,31 @@ impl McpConnectionSet {
reusable_previous.and_then(|previous| previous.servers.get(&server_name))
{
let connection = Arc::clone(&previous_view.connection);
if connection
.reusable_client(&connection_identity)
.await
.is_some_and(|client| {
previous_view.catalog_item_limit == catalog_item_limit
&& expected_protocol_mode
.is_some_and(|expected| client.client.protocol_mode() == expected)
})
let unchanged_auth_failure = if connection.identity.as_ref()
== Some(&connection_identity)
&& connection_identity.oauth_store_was_contended
&& reusable_previous
.is_some_and(|previous| previous.protocol_mode == protocol_mode)
&& connection.client.startup_complete.load(Ordering::Acquire)
{
connection
.client()
.await
.err()
.filter(StartupOutcomeError::is_authentication_required)
} else {
None
};
if unchanged_auth_failure.is_some()
|| connection
.reusable_client(&connection_identity)
.await
.is_some_and(|client| {
previous_view.catalog_item_limit == catalog_item_limit
&& expected_protocol_mode.is_some_and(|expected| {
client.client.protocol_mode() == expected
})
})
{
servers.insert(
server_name.clone(),
@@ -380,7 +412,44 @@ impl McpConnectionSet {
catalog_item_limit,
},
);
reused_ready.push(server_name);
if let Some(error) = unchanged_auth_failure {
let status = McpStartupStatus::Failed {
error: mcp_init_error_display(
&server_name,
Some(&configured_config),
&error,
),
reason: connection_identity
.oauth_credentials()
.ok()
.flatten()
.map(|_| McpStartupFailureReason::ReauthenticationRequired),
};
let tx_event = tx_event.clone();
let submit_id = startup_submit_id.clone();
let publication_gate = publication_gate.clone();
join_set.spawn(async move {
if !publication_gate.wait().await {
return (server_name, Err(StartupOutcomeError::Cancelled));
}
if let Some(tx_event) = tx_event.as_ref() {
for status in [McpStartupStatus::Starting, status] {
let _ = emit_update(
submit_id.as_str(),
tx_event,
McpStartupUpdateEvent {
server: server_name.clone(),
status,
},
)
.await;
}
}
(server_name, Err(error))
});
} else {
reused_ready.push(server_name);
}
continue;
}
}
@@ -567,6 +636,7 @@ impl McpConnectionSet {
}
let manager = Self {
servers,
protocol_mode,
required_servers,
optional_startup_deadline: OnceLock::new(),
tool_catalog_revision: Arc::new(RwLock::new(0)),
@@ -625,6 +695,7 @@ impl McpConnectionSet {
pub fn empty(prefix_mcp_tool_names: bool) -> Self {
Self {
servers: HashMap::new(),
protocol_mode: crate::McpProtocolMode::Legacy,
required_servers: Vec::new(),
optional_startup_deadline: OnceLock::new(),
tool_catalog_revision: Arc::new(RwLock::new(0)),