Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(mcp): handle OAuth callback errors and wipe stale Linear credentials (#5191)
Eric Hayesb77dda618c93
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.tsindex 1c12625d26..ad52c0cc0f 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts@@ -1650,13 +1650,19 @@ export const deleteMcpServer = async (};/**- * @summary OAuth callback endpoint — receives code and state from the authorization server.+ * @summary OAuth callback endpoint — receives code and state, or an error, from the+authorization server.*/export type mcpAuthCallbackResponse200 = {data: void;status: 200;};+export type mcpAuthCallbackResponse400 = {+ data: ErrorResponse;+ status: 400;+};+export type mcpAuthCallbackResponse500 = {data: ErrorResponse;status: 500;@@ -1665,7 +1671,10 @@ export type mcpAuthCallbackResponse500 = {export type mcpAuthCallbackResponseSuccess = mcpAuthCallbackResponse200 & {headers: Headers;};-export type mcpAuthCallbackResponseError = mcpAuthCallbackResponse500 & {+export type mcpAuthCallbackResponseError = (+ | mcpAuthCallbackResponse400+ | mcpAuthCallbackResponse500+) & {headers: Headers;};@@ -1673,7 +1682,7 @@ export type mcpAuthCallbackResponse =| mcpAuthCallbackResponseSuccess| mcpAuthCallbackResponseError;-export const getMcpAuthCallbackUrl = (params: McpAuthCallbackParams) => {+export const getMcpAuthCallbackUrl = (params?: McpAuthCallbackParams) => {const normalizedParams = new URLSearchParams();Object.entries(params || {}).forEach(([key, value]) => {@@ -1690,7 +1699,7 @@ export const getMcpAuthCallbackUrl = (params: McpAuthCallbackParams) => {};export const mcpAuthCallback = async (- params: McpAuthCallbackParams,+ params?: McpAuthCallbackParams,options?: RequestInit): Promise<mcpAuthCallbackResponse> => {const res = await fetch(getMcpAuthCallbackUrl(params), {diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.tsindex d90a15a6be..a6a5890a4c 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.ts@@ -7,11 +7,19 @@export type McpAuthCallbackParams = {/**- * Authorization code from the OAuth provider.+ * Authorization code from the OAuth provider. Present on success.*/- code: string;+ code?: string;/*** CSRF state parameter.*/- state: string;+ state?: string;+ /**+ * OAuth error code from the provider, e.g. `access_denied`. Present on failure.+ */+ error?: string;+ /**+ * Human-readable error description from the provider.+ */+ error_description?: string;};diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.jsonindex ab420e15ff..7e46f4850e 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -1347,14 +1347,14 @@"/mcp/servers/auth/callback": {"get": {"tags": ["mcp"],- "summary": "OAuth callback endpoint — receives code and state from the authorization server.",+ "summary": "OAuth callback endpoint — receives code and state, or an error, from the\nauthorization server.","operationId": "mcp_auth_callback","parameters": [{"name": "code","in": "query",- "description": "Authorization code from the OAuth provider.",- "required": true,+ "description": "Authorization code from the OAuth provider. Present on success.",+ "required": false,"schema": {"type": "string"}@@ -1363,7 +1363,25 @@"name": "state","in": "query","description": "CSRF state parameter.",- "required": true,+ "required": false,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "error",+ "in": "query",+ "description": "OAuth error code from the provider, e.g. `access_denied`. Present on failure.",+ "required": false,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "error_description",+ "in": "query",+ "description": "Human-readable error description from the provider.",+ "required": false,"schema": {"type": "string"}@@ -1373,6 +1391,16 @@"200": {"description": "OAuth flow completed successfully"},+ "400": {+ "description": "Provider rejected authorization, or the callback was malformed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {diff --git a/crates/macro_db_client/migrations/20260724185232_wipe_linear_mcp_credentials.down.sql b/crates/macro_db_client/migrations/20260724185232_wipe_linear_mcp_credentials.down.sqlnew file mode 100644index 0000000000..95e07a0484--- /dev/null+++ b/crates/macro_db_client/migrations/20260724185232_wipe_linear_mcp_credentials.down.sql@@ -0,0 +1,2 @@+-- Irreversible: the deleted rows (and their encrypted credentials) cannot+-- be restored. Reverting this migration is a no-op.diff --git a/crates/macro_db_client/migrations/20260724185232_wipe_linear_mcp_credentials.sql b/crates/macro_db_client/migrations/20260724185232_wipe_linear_mcp_credentials.sqlnew file mode 100644index 0000000000..82bfa67b0e--- /dev/null+++ b/crates/macro_db_client/migrations/20260724185232_wipe_linear_mcp_credentials.sql@@ -0,0 +1,9 @@+-- Every Linear MCP connection stored before the OAuth persistence fix+-- (#5107) and the DCR scope fix (#5153) is unrecoverable: refresh tokens+-- rotate on use, and the pre-fix client store never wrote the rotated+-- token back to the database, so the stored refresh token was orphaned+-- the moment it was first exercised. There is no code path that detects+-- or repairs this — the only fix is a full disconnect/reconnect. Wipe+-- every row so the next connection attempt starts clean instead of+-- failing silently against a dead credential.+DELETE FROM mcp_servers WHERE url = 'https://mcp.linear.app/mcp';diff --git a/crates/mcp_client/src/domain/service/toolset.rs b/crates/mcp_client/src/domain/service/toolset.rsindex 0f8faf7fef..ea1a3123c9 100644--- a/crates/mcp_client/src/domain/service/toolset.rs+++ b/crates/mcp_client/src/domain/service/toolset.rs@@ -1,4 +1,4 @@-use crate::domain::models::{CallToolResultExt, Error, McpServer, McpServerRecord};+use crate::domain::models::{CallToolResultExt, Error, MacroUserIdStr, McpServer, McpServerRecord};use crate::domain::ports::{McpConnector, McpServerStore};use ai_toolset::{AsyncToolCollection, RequestContext, RequestSchema, SearchableTool, ToolCallError, ToolInfo,@@ -55,6 +55,9 @@ pub struct McpToolSet {tools: BTreeMap<MangledName, RegisteredTool>,/// Kept alive so the background transport tasks aren't cancelled._connections: Vec<McpServer>,+ /// The owning user, for correlating tool-call failures in logs. All+ /// records passed to [`McpToolSet::new`] belong to one user in practice.+ user_id: Option<MacroUserIdStr<'static>>,}impl McpToolSet {@@ -65,28 +68,43 @@ impl McpToolSet {/// Servers that fail to connect or list tools are silently skipped.#[tracing::instrument(skip_all)]pub async fn new<S: McpServerStore>(records: &[McpServerRecord], server_store: Arc<S>) -> Self {- let futs = records- .iter()- .filter(|r| r.enabled)- .map(|record| {- let server_store = server_store.clone();- async move {- let client = record.connect(server_store).await.inspect_err(|e| {- tracing::warn!(server = %record.server_name, error = ?e, "failed to connect");- }).ok()?;+ let user_id = records.first().map(|r| r.user_id.clone());++ let futs = records.iter().filter(|r| r.enabled).map(|record| {+ let server_store = server_store.clone();+ async move {+ let client = record+ .connect(server_store)+ .await+ .inspect_err(|e| {+ tracing::warn!(+ user_id = %record.user_id,+ server = %record.server_name,+ url = %record.url,+ error = ?e,+ "failed to connect"+ );+ })+ .ok()?;let server_tools = match client.list_all_tools().await {Ok(t) => t,Err(e) => {- tracing::warn!(server = %record.server_name, error = ?e, "failed to list tools");+ tracing::warn!(+ user_id = %record.user_id,+ server = %record.server_name,+ url = %record.url,+ error = ?e,+ "failed to list tools"+ );let _ = client.cancel().await;return None;}};Some((record.server_name.clone(), client, server_tools))- }- });+ }+ });let results = futures::future::join_all(futs).await;@@ -115,6 +133,7 @@ impl McpToolSet {Self {tools,_connections: connections,+ user_id,}}@@ -156,7 +175,7 @@ impl McpToolSet {names}- #[tracing::instrument(skip(self, arguments), err)]+ #[tracing::instrument(skip(self, arguments), err, fields(user_id = ?self.user_id))]async fn call_tool(&self,name: &str,diff --git a/crates/mcp_client/src/inbound/axum_router.rs b/crates/mcp_client/src/inbound/axum_router.rsindex 8561a0bcf3..95cfeaebfd 100644--- a/crates/mcp_client/src/inbound/axum_router.rs+++ b/crates/mcp_client/src/inbound/axum_router.rs@@ -17,6 +17,9 @@ use serde::{Deserialize, Serialize};use std::sync::Arc;use utoipa::{IntoParams, ToSchema};+#[cfg(test)]+mod test;+/// Hook invoked after an OAuth flow completes and the credentials are saved./// Hosts use this to react to a connection the moment it exists (e.g. start/// import gather jobs); implementations must be quick or spawn.@@ -165,13 +168,22 @@ pub struct StartAuthResponse {}/// Query parameters received on the OAuth callback redirect.+///+/// Providers redirect here on both success (`code` + `state`) and failure+/// (`error` [+ `error_description`], per RFC 6749 §4.1.2.1). All fields are+/// optional so a rejected authorization can still be parsed and logged+/// instead of failing Axum's query extraction before the handler runs.#[derive(Debug, Deserialize, IntoParams)]#[into_params(parameter_in = Query)]pub struct AuthCallbackParams {- /// Authorization code from the OAuth provider.- code: String,+ /// Authorization code from the OAuth provider. Present on success.+ code: Option<String>,/// CSRF state parameter.- state: String,+ state: Option<String>,+ /// OAuth error code from the provider, e.g. `access_denied`. Present on failure.+ error: Option<String>,+ /// Human-readable error description from the provider.+ error_description: Option<String>,}/// An MCP server record as returned by the API.@@ -206,6 +218,12 @@ pub enum McpHandlerErr {/// The requested server was not found.#[error("server not found")]NotFound,+ /// The OAuth provider rejected the authorization request.+ #[error("authorization rejected by provider: {0}")]+ OAuthRejected(String),+ /// The callback was missing both a code and an error parameter.+ #[error("malformed OAuth callback: missing code and error parameters")]+ MalformedCallback,/// An internal error occurred.#[error("{0}")]Internal(#[from] anyhow::Error),@@ -215,6 +233,9 @@ impl IntoResponse for McpHandlerErr {fn into_response(self) -> axum::response::Response {let status = match &self {McpHandlerErr::NotFound => StatusCode::NOT_FOUND,+ McpHandlerErr::OAuthRejected(_) | McpHandlerErr::MalformedCallback => {+ StatusCode::BAD_REQUEST+ }McpHandlerErr::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,};(@@ -428,6 +449,27 @@ whereOk(Json(StartAuthResponse { authorization_url }))}+/// Classify a callback as a successful `(code, state)` pair or a handler+/// error, logging provider rejections and malformed callbacks along the way.+fn parse_callback_params(params: AuthCallbackParams) -> Result<(String, String), McpHandlerErr> {+ if let Some(error) = params.error {+ let reason = match params.error_description {+ Some(description) => format!("{error}: {description}"),+ None => error,+ };+ tracing::warn!(reason, "MCP OAuth provider rejected authorization");+ return Err(McpHandlerErr::OAuthRejected(reason));+ }++ match (params.code, params.state) {+ (Some(code), Some(state)) => Ok((code, state)),+ _ => {+ tracing::warn!("MCP OAuth callback missing both code and error parameters");+ Err(McpHandlerErr::MalformedCallback)+ }+ }+}+#[utoipa::path(get,path = "/mcp/servers/auth/callback",@@ -436,11 +478,13 @@ whereparams(AuthCallbackParams),responses((status = 200, description = "OAuth flow completed successfully"),+ (status = 400, body = ErrorResponse, description = "Provider rejected authorization, or the callback was malformed"),(status = 500, body = ErrorResponse),))]-/// OAuth callback endpoint — receives code and state from the authorization server.-#[tracing::instrument(skip_all, err)]+/// OAuth callback endpoint — receives code and state, or an error, from the+/// authorization server.+#[tracing::instrument(skip_all, err, fields(state = ?params.state))]pub async fn auth_callback<S, O, Auth>(State(state): State<McpRouterState<S, O, Auth>>,Query(params): Query<AuthCallbackParams>,@@ -450,9 +494,11 @@ whereO: OAuthClient,Auth: MacroAuthorizationService,{+ let (code, csrf_state) = parse_callback_params(params)?;+let record = state.oauth- .exchange_authorization_code(¶ms.code, ¶ms.state)+ .exchange_authorization_code(&code, &csrf_state).await?;// Let the host react to the brand-new connection (e.g. kick off importdiff --git a/crates/mcp_client/src/inbound/axum_router/test.rs b/crates/mcp_client/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..542e6b0b6e--- /dev/null+++ b/crates/mcp_client/src/inbound/axum_router/test.rs@@ -0,0 +1,68 @@+use super::*;++fn params(+ code: Option<&str>,+ state: Option<&str>,+ error: Option<&str>,+ error_description: Option<&str>,+) -> AuthCallbackParams {+ AuthCallbackParams {+ code: code.map(String::from),+ state: state.map(String::from),+ error: error.map(String::from),+ error_description: error_description.map(String::from),+ }+}++#[test]+fn successful_callback_yields_code_and_state() {+ let result = parse_callback_params(params(Some("a-code"), Some("a-state"), None, None));+ assert!(matches!(result, Ok((code, state)) if code == "a-code" && state == "a-state"));+}++#[test]+fn provider_rejection_is_reported_with_description() {+ let result = parse_callback_params(params(+ None,+ Some("a-state"),+ Some("access_denied"),+ Some("user declined"),+ ));+ let Err(McpHandlerErr::OAuthRejected(message)) = result else {+ panic!("expected OAuthRejected, got {result:?}");+ };+ assert_eq!(message, "access_denied: user declined");+}++#[test]+fn provider_rejection_without_description_uses_bare_error() {+ let result = parse_callback_params(params(None, Some("a-state"), Some("access_denied"), None));+ let Err(McpHandlerErr::OAuthRejected(message)) = result else {+ panic!("expected OAuthRejected, got {result:?}");+ };+ assert_eq!(message, "access_denied");+}++#[test]+fn error_takes_precedence_over_a_stray_code() {+ // Providers shouldn't send both, but if they do, the rejection is authoritative.+ let result = parse_callback_params(params(+ Some("a-code"),+ Some("a-state"),+ Some("access_denied"),+ None,+ ));+ assert!(matches!(result, Err(McpHandlerErr::OAuthRejected(_))));+}++#[test]+fn missing_code_and_error_is_malformed() {+ let result = parse_callback_params(params(None, Some("a-state"), None, None));+ assert!(matches!(result, Err(McpHandlerErr::MalformedCallback)));+}++#[test]+fn missing_state_without_error_is_malformed() {+ let result = parse_callback_params(params(Some("a-code"), None, None, None));+ assert!(matches!(result, Err(McpHandlerErr::MalformedCallback)));+}