Hmbown/CodeWhale · error

unexpected MCP OAuth state while preparing stored…

Error message

unexpected MCP OAuth state while preparing stored credentials

What it means

This internal invariant error fires when the MCP OAuth runtime finishes installing stored credentials but the resulting OAuthState is neither Authorized nor Unauthorized — i.e. the state machine is in an unexpected variant after token installation. Callers from_stored_tokens, adopt_rotated_on_disk_tokens, and clear_stored_tokens all expect a manager to be produced; any other state means the runtime's async state transition did not settle as designed.

Solutions

  1. Retry the operation from a fresh McpOAuthRuntime instance (restart the client or re-run the login flow)
  2. Ensure no concurrent OAuth login/refresh/login-cancel operations run on the same server simultaneously
  3. If it persists, file a bug: the state machine reached an unhandled variant after set_credentials, which is an internal invariant violation
  4. If you recently added an OAuthState variant, extend the match at oauth.rs:588 to handle it

Example fix

match state {
    OAuthState::Authorized(manager) | OAuthState::Unauthorized(manager) => Ok(manager),
    other => bail!("unexpected MCP OAuth state while preparing stored credentials: {other:?}"),
}
Defensive patterns

Strategy: retry

Type guard

fn state_has_manager(state: &OAuthState) -> bool {
    matches!(state, OAuthState::Authorized(_) | OAuthState::Unauthorized(_))
}

Try / catch

match runtime.from_stored_tokens(&server).await {
    Ok(manager) => manager,
    Err(e) if e.to_string().contains("unexpected MCP OAuth state") => {
        // rebuild the runtime and retry once
        let fresh = McpOAuthRuntime::new(cfg);
        fresh.from_stored_tokens(&server).await?
    }
    Err(e) => return Err(e),
}

Prevention

When it happens

Trigger: Calling McpOAuthRuntime::from_stored_tokens (directly or via adopt_rotated_on_disk_tokens or clear_stored_tokens) when the internal state machine, after set_credentials, holds a state other than OAuthState::Authorized/Unauthorized — e.g. a Failed/Pending variant left over from a prior step.

Common situations: A prior OAuth operation failed or was cancelled leaving the runtime in a transient state; concurrent login/refresh operations racing on the same runtime; a code change adding a new OAuthState variant without updating this match.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of Hmbown/CodeWhale@73e0f67d83 (2026-09-22). Data as JSON: /api/errors/cb458db4fe5c5e8c. Report an issue: GitHub.

Appendix: source

Thrown at crates/tui/src/mcp/oauth.rs:588

/// Build an `AuthorizationManager` preloaded with stored credentials, the
/// shared construction step for initial load and for adopting a credential
/// that another process rotated on disk.
async fn manager_from_stored_tokens(
    url: &str,
    tokens: &StoredMcpOAuthTokens,
    http_client: &Arc<RecordingOAuthHttpClient>,
) -> Result<AuthorizationManager> {
    let client = Arc::clone(http_client) as Arc<dyn OAuthHttpClient>;
    let mut state = OAuthState::new_with_oauth_http_client(url.to_string(), client).await?;
    state
        .set_credentials(&tokens.client_id, tokens.token_response.0.clone())
        .await
        .context("installing stored MCP OAuth credentials")?;

    match state {
        OAuthState::Authorized(manager) | OAuthState::Unauthorized(manager) => Ok(manager),
        _ => bail!("unexpected MCP OAuth state while preparing stored credentials"),
    }
}

impl McpOAuthRuntime {
    #[cfg(test)]
    pub(super) async fn from_server_config(
        server_name: &str,
        server: &McpServerConfig,
        default_headers: HeaderMap,
    ) -> Result<Option<Self>> {
        if server.reviewed_plugin.is_some() || server_has_manual_authorization(server) {
            return Ok(None);
        }
        let Some(url) = server.url.as_deref() else {
            return Ok(None);
        };
        let client = oauth_http_client(server, url, None)?;
        Self::from_server_config_with_client(server_name, server, default_headers, client).await

View on GitHub (pinned to 73e0f67d83)