{"record":{"id":"cb458db4fe5c5e8c","repo":"Hmbown/CodeWhale","slug":"unexpected-mcp-oauth-state-while-preparing-stored","errorCode":null,"errorMessage":"unexpected MCP OAuth state while preparing stored credentials","messagePattern":"unexpected MCP OAuth state while preparing stored credentials","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/tui/src/mcp/oauth.rs","lineNumber":588,"sourceCode":"\n/// Build an `AuthorizationManager` preloaded with stored credentials, the\n/// shared construction step for initial load and for adopting a credential\n/// that another process rotated on disk.\nasync fn manager_from_stored_tokens(\n    url: &str,\n    tokens: &StoredMcpOAuthTokens,\n    http_client: &Arc<RecordingOAuthHttpClient>,\n) -> Result<AuthorizationManager> {\n    let client = Arc::clone(http_client) as Arc<dyn OAuthHttpClient>;\n    let mut state = OAuthState::new_with_oauth_http_client(url.to_string(), client).await?;\n    state\n        .set_credentials(&tokens.client_id, tokens.token_response.0.clone())\n        .await\n        .context(\"installing stored MCP OAuth credentials\")?;\n\n    match state {\n        OAuthState::Authorized(manager) | OAuthState::Unauthorized(manager) => Ok(manager),\n        _ => bail!(\"unexpected MCP OAuth state while preparing stored credentials\"),\n    }\n}\n\nimpl McpOAuthRuntime {\n    #[cfg(test)]\n    pub(super) async fn from_server_config(\n        server_name: &str,\n        server: &McpServerConfig,\n        default_headers: HeaderMap,\n    ) -> Result<Option<Self>> {\n        if server.reviewed_plugin.is_some() || server_has_manual_authorization(server) {\n            return Ok(None);\n        }\n        let Some(url) = server.url.as_deref() else {\n            return Ok(None);\n        };\n        let client = oauth_http_client(server, url, None)?;\n        Self::from_server_config_with_client(server_name, server, default_headers, client).await","sourceCodeStart":570,"sourceCodeEnd":606,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/73e0f67d83c59909b571efdfc88c4bc28c309cb1/crates/tui/src/mcp/oauth.rs#L570-L606","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Retry the operation from a fresh McpOAuthRuntime instance (restart the client or re-run the login flow)","Ensure no concurrent OAuth login/refresh/login-cancel operations run on the same server simultaneously","If it persists, file a bug: the state machine reached an unhandled variant after set_credentials, which is an internal invariant violation","If you recently added an OAuthState variant, extend the match at oauth.rs:588 to handle it"],"exampleFix":"match state {\n    OAuthState::Authorized(manager) | OAuthState::Unauthorized(manager) => Ok(manager),\n    other => bail!(\"unexpected MCP OAuth state while preparing stored credentials: {other:?}\"),\n}","handlingStrategy":"retry","validationCode":null,"typeGuard":"fn state_has_manager(state: &OAuthState) -> bool {\n    matches!(state, OAuthState::Authorized(_) | OAuthState::Unauthorized(_))\n}","tryCatchPattern":"match runtime.from_stored_tokens(&server).await {\n    Ok(manager) => manager,\n    Err(e) if e.to_string().contains(\"unexpected MCP OAuth state\") => {\n        // rebuild the runtime and retry once\n        let fresh = McpOAuthRuntime::new(cfg);\n        fresh.from_stored_tokens(&server).await?\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Do not run concurrent OAuth operations on the same MCP server","Serialize login/logout/refresh per server with a lock or queue","Recreate the OAuth runtime after a failed operation instead of reusing a possibly half-transitioned one"],"tags":["oauth","mcp","state-machine","internal"],"backgroundTag":"internal-invariant-violation","analyzedSha":"73e0f67d83c59909b571efdfc88c4bc28c309cb1","analyzedAt":"2026-09-22T01:30:00.501Z","contentChangedAt":"2026-09-22T01:30:00.501Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}