Serialize MCP OAuth credential refreshes (#32229)

## Why

Concurrent Codex processes can otherwise refresh the same rotating token, and a
cancelled or partially persisted refresh can leave durable and in-memory MCP
credentials out of sync.

## What changed

- Serialize each credential's read-refresh-write transaction across processes,
  reread the authoritative store after locking, and adopt credentials refreshed
  by another process.
- Keep refresh persistence running after caller cancellation, bound lock and
  provider waits independently, and preserve omitted refresh tokens and scopes.
- Fail MCP startup and operations when refresh or persistence fails instead of
  continuing with stale credentials, while requiring reauthorization for
  missing, unusable, or rejected refresh tokens.
- Exclude OAuth refresh time from the MCP initialization timeout.

## Testing

Add coverage for lock contention, concurrent refreshes, rejected and missing
credentials, storage failures, caller cancellation, and provider timeouts.

GitOrigin-RevId: 4d29b879bec646d2ceb922b526dc793b1a1f5423
This commit is contained in:
stevenlee-oai
2026-07-10 17:59:41 +00:00
committed by copyberry
parent c8dc8e5fd5
commit 6962a2ecae
9 changed files with 925 additions and 45 deletions
@@ -37,7 +37,7 @@ impl RmcpClient {
PendingTransport::StreamableHttp { .. }
| PendingTransport::StreamableHttpWithOAuth { .. } => true,
};
let retry_deadline = timeout.map(|duration| Instant::now() + duration);
let mut retry_deadline = timeout.map(|duration| Instant::now() + duration);
let mut pending_transport = Some(initial_transport);
for (attempt, retry_delay_ms) in STREAMABLE_HTTP_RETRY_DELAYS_MS
@@ -62,6 +62,18 @@ impl RmcpClient {
}
}
};
if let PendingTransport::StreamableHttpWithOAuth {
oauth_persistor, ..
} = &transport
{
// OAuth refresh has its own lock and provider request bounds. Exclude it from the
// MCP handshake budget, and finish persistence before attempting initialize.
let refresh_started_at = Instant::now();
oauth_persistor.refresh_if_needed().await?;
if let Some(deadline) = retry_deadline.as_mut() {
*deadline += refresh_started_at.elapsed();
}
}
let attempt_timeout = remaining_initialize_timeout(timeout, retry_deadline)?;
match Self::connect_pending_transport(