Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🗼 fix: Serialize MCP OAuth Token Refresh Across Replicas (#15993)

lia-by-librechat[bot]2452f499a86a
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js
index 94e8a0693c..bc3fe779b5 100644
--- a/api/server/routes/__tests__/mcp.spec.js
+++ b/api/server/routes/__tests__/mcp.spec.js
@@ -1354,6 +1354,7 @@ describe('MCP Routes', () => {
deleteFlow: jest.fn().mockResolvedValue(true),
};
const mockFlowState = {
+ oauthPersistenceWaitTimeout: 60000,
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
@@ -1428,6 +1429,8 @@ describe('MCP Routes', () => {
);
expect(MCPTokenStorage.storeTokens).toHaveBeenCalledWith(
expect.objectContaining({
+ flowManager: mockFlowManager,
+ persistenceWaitTimeoutMs: 60000,
userId: 'test-user-id',
serverName: 'test-server',
tokens: mockTokens,
diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.js
index 9b28db1f90..2b0da05553 100644
--- a/api/server/routes/mcp.js
+++ b/api/server/routes/mcp.js
@@ -533,6 +533,8 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
completeAuthorization: completePersistedFlow,
persistTokens: async (candidateTokens, onStoreCommitted) =>
(await MCPTokenStorage.storeTokens({
+ flowManager,
+ persistenceWaitTimeoutMs: flowState.oauthPersistenceWaitTimeout,
userId: flowState.userId,
serverName,
tokens: candidateTokens,
diff --git a/librechat.example.yaml b/librechat.example.yaml
index c36d841be5..c4289f737a 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -514,6 +514,20 @@ actions:
# url: http://localhost:3001/sse
# # proxy: "${MCP_PROXY_URL}" # optional outbound proxy (http/https/socks/socks5)
# timeout: 60000 # 1 minute timeout for this server, this is the default timeout for MCP servers.
+# coordinated-oauth:
+# type: streamable-http
+# url: https://mcp.example.com/mcp
+# requiresOAuth: true
+# # Stage rollout with coordination disabled (the default). Once EVERY replica is upgraded,
+# # pause MCP traffic and drain active refreshes/callbacks on EVERY replica before changing
+# # this flag. Apply the same value everywhere while paused, then resume. For rollback, drain,
+# # disable everywhere, replace the replicas, then resume. Do not toggle during live traffic.
+# # All coordinated replicas must use the same Redis cache.
+# oauthRefreshCoordination: false
+# # Peer refresh wait; capped at 30000 ms by the refresh execution budget.
+# oauthRefreshWaitTimeout: 15000
+# # Callback/adoption persistence wait; raise for longer publication budgets (max 840000 ms).
+# oauthPersistenceWaitTimeout: 15000
# private-openid:
# type: streamable-http
# url: https://mcp.example.com/mcp
diff --git a/packages/api/src/flow/manager.test.ts b/packages/api/src/flow/manager.test.ts
index 8f90b1b5b1..43a8d9c78b 100644
--- a/packages/api/src/flow/manager.test.ts
+++ b/packages/api/src/flow/manager.test.ts
@@ -48,6 +48,42 @@ describe('FlowStateManager', () => {
jest.clearAllMocks();
});
+ it.each([false, true])(
+ 'preserves named failures across serialized stores (guarded: %s)',
+ async (guarded) => {
+ jest.useFakeTimers();
+ const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse });
+ const owner = new FlowStateManager<string>(keyv, { ttl: 30000, ci: true });
+ const peer = new FlowStateManager<string>(keyv, { ttl: 30000, ci: true });
+ try {
+ await owner.initFlow('refresh', 'mcp_get_tokens');
+ const flow = await owner.getFlowState('refresh', 'mcp_get_tokens');
+ const waiting = peer.createFlowWithHandler(
+ 'refresh',
+ 'mcp_get_tokens',
+ async () => 'unexpected',
+ );
+ const result = waiting.catch((error: Error) => error);
+ const expected = {
+ name: 'MCPTokenRefreshUnavailableError',
+ message: 'retry later',
+ };
+ await Promise.resolve();
+ const error = new Error('retry later');
+ error.name = 'MCPTokenRefreshUnavailableError';
+ if (guarded) {
+ await owner.failFlowIfCurrent('refresh', 'mcp_get_tokens', flow!.createdAt, '', error);
+ } else {
+ await owner.failFlow('refresh', 'mcp_get_tokens', error);
+ }
+ await jest.advanceTimersByTimeAsync(2000);
+ expect(await result).toMatchObject(expected);
+ } finally {
+ jest.useRealTimers();
+ }
+ },
+ );
+
describe('Concurrency Tests', () => {
it('atomically updates the default in-memory Keyv envelope', async () => {
const keyv = new Keyv({
diff --git a/packages/api/src/flow/manager.ts b/packages/api/src/flow/manager.ts
index 50cc2a7638..54979587b7 100644
--- a/packages/api/src/flow/manager.ts
+++ b/packages/api/src/flow/manager.ts
@@ -61,6 +61,7 @@ if state ~= ARGV[2] then return -1 end
if flow.status == 'COMPLETED' then return -1 end
flow.status = 'FAILED'
flow.error = ARGV[3]
+flow.errorName = ARGV[6]
flow.failedAt = tonumber(ARGV[4])
data.expires = tonumber(ARGV[4]) + tonumber(ARGV[5])
redis.call('SET', KEYS[1], cjson.encode(data), 'PX', ARGV[5])
@@ -457,6 +458,7 @@ export class FlowStateManager<T = unknown> {
): Promise<GuardedMutationResult> {
const flowKey = this.getFlowKey(flowId, type);
const message = error instanceof Error ? error.message : error;
+ const errorName = error instanceof Error ? error.name : 'Error';
const failedAt = Date.now();
const redisKey = this.getRedisKey(flowKey);
if (redisKey) {
@@ -466,6 +468,7 @@ export class FlowStateManager<T = unknown> {
message,
String(failedAt),
String(this.ttl),
+ errorName,
]);
return FlowStateManager.guardedResult(result);
}
@@ -483,6 +486,7 @@ export class FlowStateManager<T = unknown> {
...current,
status: 'FAILED',
error: message,
+ errorName,
failedAt,
};
memoryEntry.envelope.expires = failedAt + this.ttl;
@@ -504,6 +508,7 @@ export class FlowStateManager<T = unknown> {
...current,
status: 'FAILED',
error: message,
+ errorName,
failedAt,
};
await this.keyv.set(flowKey, updatedState, this.ttl);
@@ -798,7 +803,9 @@ export class FlowStateManager<T = unknown> {
if (!this.retainedFailureTypes.has(type)) {
await this.keyv.delete(flowKey);
}
- reject(new Error(flowState.error ?? `${type} flow failed`));
+ const error = new Error(flowState.error ?? `${type} flow failed`);
+ error.name = flowState.errorName ?? 'Error';
+ reject(error);
}
return;
}
@@ -949,6 +956,7 @@ export class FlowStateManager<T = unknown> {
...flowState,
status: 'FAILED',
error: error instanceof Error ? error.message : error,
+ errorName: error instanceof Error ? error.name : 'Error',
failedAt: Date.now(),
};
diff --git a/packages/api/src/flow/types.ts b/packages/api/src/flow/types.ts
index edd9fad3b1..aa60cd7b81 100644
--- a/packages/api/src/flow/types.ts
+++ b/packages/api/src/flow/types.ts
@@ -12,6 +12,8 @@ export interface FlowState<T = unknown> {
createdAt: number;
result?: T;
error?: string;
+ /** Additive wire field; older flow records retain the default Error name. */
+ errorName?: string;
completedAt?: number;
failedAt?: number;
}
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index 2ddf0ca81a..07fa1b4114 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -71,6 +71,7 @@ type OAuthRequiredEvent = {
status?: number;
statusCode?: number;
skipSilentRefresh?: boolean;
+ rejectedCredentialSetId?: string | null;
};
type OAuthRecoveryPhase = 'silent-refresh' | 'interactive' | 'terminal';
@@ -925,6 +926,9 @@ export class MCPConnectionFactory {
}
private getTokenFlowId(): string {
+ // Before activation, keep joining legacy readers: splitting their flow would permit duplicate
+ // redemption while some replicas still cannot take the coordination lease.
+ if (this.serverConfig.oauthRefreshCoordination !== true) return this.getBaseFlowId();
return MCPOAuthHandler.generateTokenFlowId(this.userId!, this.serverName, this.tenantId);
}
@@ -967,9 +971,13 @@ export class MCPConnectionFactory {
deleteTokens: this.tokenMethods!.deleteTokens,
refreshTokens: this.createRefreshTokensFunction(),
singleFlightScope: this.getOAuthBindingDigest(),
+ refreshWaitTimeoutMs: this.serverConfig.oauthRefreshWaitTimeout,
+ coordinateRefresh: this.serverConfig.oauthRefreshCoordination,
+ persistenceWaitTimeoutMs: this.serverConfig.oauthPersistenceWaitTimeout,
flowManager: this.flowManager,
onRefreshSuccess: (refreshed) => this.handleOAuthRefreshSuccess(refreshed),
onRefreshPreparing: () => this.prepareOAuthRefreshSuccess(),
+ onTokensAdopted: (adopted) => this.handleAdoptedCredentials(adopted),
}),
);
},
@@ -980,13 +988,30 @@ export class MCPConnectionFactory {
return await readTokens();
} catch (error) {
if (!(error instanceof FlowStateNotFoundError)) {
- throw error;
+ if (
+ MCPConnectionFactory.isRefreshUnavailable(error) ||
+ MCPConnectionFactory.isReauthenticationRequired(error)
+ ) {
+ throw error;
+ }
+ // Legacy flow records and cache failures carry no typed outcome. Retry storage first.
+ throw new MCPTokenStorageUnavailableError(this.serverName, error);
}
logger.info(
`${this.logPrefix} Token flow was invalidated while waiting on it; re-reading stored tokens`,
);
await this.onOAuthCredentialsInvalidated?.();
- return await readTokens();
+ try {
+ return await readTokens();
+ } catch (retryError) {
+ if (
+ MCPConnectionFactory.isRefreshUnavailable(retryError) ||
+ MCPConnectionFactory.isReauthenticationRequired(retryError)
+ ) {
+ throw retryError;
+ }
+ throw new MCPTokenStorageUnavailableError(this.serverName, retryError);
+ }
}
}
@@ -1020,10 +1045,16 @@ export class MCPConnectionFactory {
serverName: this.serverName,
findToken: this.tokenMethods!.findToken!,
}),
- ]),
+ ]).catch((error: unknown) => {
+ throw new MCPTokenStorageUnavailableError(this.serverName, error);
+ }),
);
if (!isCurrentAccessToken) {
- throw new Error(`${this.logPrefix} Cached OAuth access token is stale`);
+ await this.invalidateGetTokensFlow();
+ throw new MCPTokenStorageUnavailableError(
+ this.serverName,
+ new Error('Cached OAuth access token is stale'),
+ );
}
MCPTokenStorage.assertCredentialSetBinding(
this.serverName,
@@ -1042,7 +1073,7 @@ export class MCPConnectionFactory {
}
return tokens;
} catch (error) {
- if (error instanceof ReauthenticationRequiredError) {
+ if (MCPConnectionFactory.isReauthenticationRequired(error)) {
logger.info(`${this.logPrefix} Reauthentication required; triggering OAuth flow`);
return null;
}
@@ -1113,7 +1144,9 @@ export class MCPConnectionFactory {
* in-flight promise means every fresh 401 after settlement triggers a
* fresh redemption.
*/
- protected async attemptSilentTokenRefresh(): Promise<MCPOAuthTokens | null> {
+ protected async attemptSilentTokenRefresh(
+ rejectedCredentialSetId?: string | null,
+ ): Promise<MCPOAuthTokens | null> {
if (!this.tokenMethods?.findToken || !this.tokenMethods?.createToken) {
return null;
}
@@ -1121,7 +1154,15 @@ export class MCPConnectionFactory {
// Scope the lock by tenant and OAuth binding so neither another tenant nor a
// same-name server whose URL/client configuration changed can join the refresh.
const bindingDigest = this.getOAuthBindingDigest();
- const lockKey = `${this.tenantId ?? ''}:${this.userId ?? ''}:${this.serverName}:${bindingDigest}`;
+ const lockKey = JSON.stringify([
+ this.tenantId ?? '',
+ this.userId ?? '',
+ this.serverName,
+ bindingDigest,
+ ...(this.serverConfig.oauthRefreshCoordination === true
+ ? [rejectedCredentialSetId === undefined ? ['unknown'] : ['known', rejectedCredentialSetId]]
+ : []),
+ ]);
const inflight = MCPConnectionFactory.inflightSilentRefreshes.get(lockKey);
if (inflight) {
logger.debug(`${this.logPrefix} Joining in-flight silent refresh attempt`);
@@ -1132,8 +1173,12 @@ export class MCPConnectionFactory {
const abortController = new AbortController();
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let abortGraceTimeoutId: ReturnType<typeof setTimeout> | null = null;
- const refreshPromise = this.runSilentRefresh(abortController.signal, bindingDigest);
- const promise = new Promise<MCPOAuthTokens | null>((resolve) => {
+ const refreshPromise = this.runSilentRefresh(
+ abortController.signal,
+ bindingDigest,
+ rejectedCredentialSetId,
+ );
+ const promise = new Promise<MCPOAuthTokens | null>((resolve, reject) => {
timeoutId = setTimeout(() => {
abortController.abort();
abortGraceTimeoutId = setTimeout(
@@ -1141,12 +1186,22 @@ export class MCPConnectionFactory {
MCPConnectionFactory.SILENT_REFRESH_ABORT_GRACE_MS,
);
logger.info(
- `${this.logPrefix} Silent token refresh timed out after ${timeoutMs}ms, falling back to interactive OAuth`,
+ `${this.logPrefix} Silent token refresh timed out after ${timeoutMs}ms; deferring recovery`,
+ );
+ reject(
+ new MCPTokenRefreshUnavailableError(
+ this.serverName,
+ new Error('Silent refresh timed out'),
+ ),
);
- resolve(null);
}, timeoutMs);
- refreshPromise.then(resolve, () => {
+ refreshPromise.then(resolve, (error: unknown) => {
+ /** Every joiner waits on this same contended credential, so they share the retry. */
+ if (MCPConnectionFactory.isRefreshUnavailable(error)) {
+ reject(error);
+ return;
+ }
logger.info(
`${this.logPrefix} Silent token refresh failed, falling back to interactive OAuth`,
);
@@ -1179,6 +1234,7 @@ export class MCPConnectionFactory {
private async runSilentRefresh(
signal: AbortSignal,
singleFlightScope: string,
+ rejectedCredentialSetId?: string | null,
): Promise<MCPOAuthTokens | null> {
try {
const tokens = await this.runWithCapturedTenant(async () =>
@@ -1191,6 +1247,10 @@ export class MCPConnectionFactory {
deleteTokens: this.tokenMethods!.deleteTokens,
refreshTokens: this.createRefreshTokensFunction(),
singleFlightScope,
+ rejectedCredentialSetId,
+ refreshWaitTimeoutMs: this.serverConfig.oauthRefreshWaitTimeout,
+ coordinateRefresh: this.serverConfig.oauthRefreshCoordination,
+ persistenceWaitTimeoutMs: this.serverConfig.oauthPersistenceWaitTimeout,
signal,
/**
* Drop any previously cached `mcp_get_tokens` result so the next
@@ -1201,6 +1261,7 @@ export class MCPConnectionFactory {
*/
onRefreshSuccess: (refreshed) => this.handleOAuthRefreshSuccess(refreshed),
onRefreshPreparing: () => this.prepareOAuthRefreshSuccess(),
+ onTokensAdopted: (adopted) => this.handleAdoptedCredentials(adopted),
flowManager: this.flowManager,
}),
);
@@ -1212,6 +1273,16 @@ export class MCPConnectionFactory {
}
return tokens;
} catch (error) {
+ /**
+ * Contention with another replica's redemption is retryable and must not read as a failed
+ * refresh. Collapsing it to null sends this path to interactive OAuth, so a peer that merely
+ * held the credential slightly too long would prompt the user to authorize the server again,
+ * which is the outcome the cross-replica flight exists to prevent. The next request retries
+ * once the peer releases, by which time its rotated credential is there to be adopted.
+ */
+ if (MCPConnectionFactory.isRefreshUnavailable(error)) {
+ throw error;
+ }
if (error instanceof ReauthenticationRequiredError) {
logger.info(
`${this.logPrefix} Reauthentication required; falling back to interactive OAuth`,
@@ -1225,11 +1296,33 @@ export class MCPConnectionFactory {
}
}
- /**
- * Clears stale token-fetch cache after fresh credentials are known. COMPLETED
- * entries are deleted; PENDING entries are completed with fresh tokens so
- * concurrent waiters do not fail or later publish server-rejected tokens.
- */
+ /** Flow serialization preserves domain names, not class identity. */
+ private static isReauthenticationRequired(error: unknown): boolean {
+ return (
+ error instanceof ReauthenticationRequiredError ||
+ (error instanceof Error && error.name === 'ReauthenticationRequiredError')
+ );
+ }
+
+ private static isRefreshUnavailable(error: unknown): boolean {
+ return (
+ error instanceof MCPTokenRefreshUnavailableError ||
+ error instanceof MCPTokenStorageUnavailableError ||
+ (error instanceof Error &&
+ (error.name === 'MCPTokenRefreshUnavailableError' ||
+ error.name === 'MCPTokenStorageUnavailableError'))
+ );
+ }
+
+ /** Carries the peer's publication generation to every waiter without publishing it again. */
+ private async handleAdoptedCredentials(adoptedTokens: MCPOAuthTokens): Promise<void> {
+ const generation = await this.onOAuthCredentialsInvalidated?.();
+ if (generation) {
+ adoptedTokens.publication_generation = generation;
+ }
+ await this.invalidateGetTokensFlow(adoptedTokens, generation || undefined);
+ }
+
private async handleOAuthRefreshSuccess(freshTokens: MCPOAuthTokens): Promise<void> {
if (this.userId != null) {
await this.onOAuthCredentialsChanged?.({
@@ -1277,29 +1370,38 @@ export class MCPConnectionFactory {
if (!this.flowManager || !this.userId) {
return;
}
- const flowId = this.getTokenFlowId();
- try {
- const state = await this.flowManager.getFlowState(flowId, 'mcp_get_tokens');
- if (!state) {
- return;
- }
- if (state.status === 'PENDING' && freshTokens) {
- await this.flowManager.completeFlow(
- flowId,
- 'mcp_get_tokens',
- publicationGeneration
- ? { ...freshTokens, publication_generation: publicationGeneration }
- : freshTokens,
- );
- return;
- }
- if (state.status !== 'COMPLETED') {
- return;
- }
- await this.flowManager.deleteFlow(flowId, 'mcp_get_tokens');
- } catch {
- logger.debug(`${this.logPrefix} Failed to invalidate mcp_get_tokens cache`);
- }
+ const flowManager = this.flowManager;
+ // Both protocols remain valid cache readers across an enable/rollback transition.
+ const flowIds = new Set([
+ this.getBaseFlowId(),
+ MCPOAuthHandler.generateTokenFlowId(this.userId, this.serverName, this.tenantId),
+ ]);
+ await Promise.all(
+ [...flowIds].map(async (flowId) => {
+ try {
+ const state = await flowManager.getFlowState(flowId, 'mcp_get_tokens');
+ if (!state) {
+ return;
+ }
+ if (state.status === 'PENDING' && freshTokens) {
+ await flowManager.completeFlow(
+ flowId,
+ 'mcp_get_tokens',
+ publicationGeneration
+ ? { ...freshTokens, publication_generation: publicationGeneration }
+ : freshTokens,
+ );
+ return;
+ }
+ if (state.status !== 'COMPLETED') {
+ return;
+ }
+ await flowManager.deleteFlow(flowId, 'mcp_get_tokens');
+ } catch {
+ logger.debug(`${this.logPrefix} Failed to invalidate mcp_get_tokens cache`);
+ }
+ }),
+ );
}
/**
@@ -1577,6 +1679,10 @@ export class MCPConnectionFactory {
return;
}
+ const rejectedCredentialSetId =
+ data.rejectedCredentialSetId !== undefined
+ ? data.rejectedCredentialSetId
+ : connection.getOAuthCredentialSetId();
const oauthLeaseId = getMCPOAuthLeaseId(this.userId!, this.serverName, this.tenantId);
let oauthLeaseGeneration: number | null;
try {
@@ -1599,7 +1705,27 @@ export class MCPConnectionFactory {
if (!isRequestRecovery || recoveryPhase === 'silent-refresh') {
recoveryPhase = 'interactive';
if (!data.skipSilentRefresh && this.shouldAttemptSilentTokenRefresh(data)) {
- const refreshedTokens = await this.attemptSilentTokenRefresh();
+ let refreshedTokens: MCPOAuthTokens | null;
+ try {
+ refreshedTokens = await this.attemptSilentTokenRefresh(rejectedCredentialSetId);
+ } catch (error) {
+ if (!MCPConnectionFactory.isRefreshUnavailable(error)) {
+ throw error;
+ }
+ /**
+ * Another replica is redeeming this credential. Falling through would start a
+ * replacement authorization while that redemption is still live, asking the user to
+ * approve a server whose credential is about to be valid. Failing the connection
+ * defers to the next request instead, matching how the stored-token path reports the
+ * same error, and mirroring the teardown gate below in choosing not to prompt.
+ */
+ logger.info(
+ `${this.logPrefix} Another replica is rotating this credential; deferring recovery`,
+ );
+ recoveryPhase = 'silent-refresh';
+ connection.emit('oauthFailed', error);
+ return;
+ }
if (refreshedTokens) {
connection.setOAuthTokens(refreshedTokens);
connection.emit('oauthHandled', 'silent-refresh' satisfies t.OAuthHandledSource);
@@ -1715,6 +1841,7 @@ export class MCPConnectionFactory {
authorizationUrl,
tenantId: this.tenantId,
serverGeneration: getMCPServerGeneration(this.serverDefinition as t.ParsedServerConfig),
+ oauthPersistenceWaitTimeout: this.serverConfig.oauthPersistenceWaitTimeout,
};
const publicationLease = await this.flowManager!.acquireLease(oauthLeaseId, {
expectedGeneration: oauthLeaseGeneration,
@@ -2187,6 +2314,7 @@ export class MCPConnectionFactory {
authorizationUrl,
tenantId: this.tenantId,
serverGeneration: getMCPServerGeneration(this.serverDefinition as t.ParsedServerConfig),
+ oauthPersistenceWaitTimeout: this.serverConfig.oauthPersistenceWaitTimeout,
};
const publicationLease = await this.flowManager.acquireLease(oauthLeaseId, {
expectedGeneration: oauthLeaseGeneration,
diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.ts
index 429df3af63..738a6e179e 100644
--- a/packages/api/src/mcp/MCPManager.ts
+++ b/packages/api/src/mcp/MCPManager.ts
@@ -543,7 +543,10 @@ export class MCPManager extends UserConnectionManager {
connectionTimeout: args.connectionTimeout,
deadlineMs: args.deadlineMs,
onOAuthCredentialsChanged: args.onOAuthCredentialsChanged,
+ onOAuthCredentialsAdopted: args.onOAuthCredentialsAdopted,
onOAuthCredentialsChanging: args.onOAuthCredentialsChanging,
+ onOAuthCredentialsInvalidated: () =>
+ getMCPToolsChangedGeneration({ userId: user.id, serverName }),
onDiscoveryDetached: args.onDiscoveryDetached,
oboTokenResolver: args.oboTokenResolver,
oboTrustChecker: args.oboTrustChecker,
@@ -767,6 +770,7 @@ Please follow these instructions when using tools from the respective MCP server
flowManager: FlowStateManager<MCPOAuthTokens | null>,
signal?: AbortSignal,
allowsTakeover = true,
+ rejectedCredentialSetId?: string | null,
): Promise<void> {
const existingRecovery = this.oauthRecoveries.get(connection);
if (existingRecovery) {
@@ -807,6 +811,7 @@ Please follow these instructions when using tools from the respective MCP server
connection.emit('oauthReauthenticationRequired', {
serverName,
error,
+ rejectedCredentialSetId,
serverUrl: connection.url,
userId,
}),
@@ -1414,6 +1419,8 @@ Please follow these instructions when using tools from the respective MCP server
requestBody,
onOAuthCredentialsChanged,
onOAuthCredentialsChanging,
+ onOAuthCredentialsInvalidated: () =>
+ getMCPToolsChangedGeneration({ userId, serverName }),
},
connection!,
);
@@ -1421,7 +1428,9 @@ Please follow these instructions when using tools from the respective MCP server
connection.setRequestHeaders(resolvedHeaders);
+ const checkedCredentialSetId = connection.getOAuthCredentialSetId?.();
const connectionIsActive = await connection.isConnected(options?.signal);
+ const recordedCredentialSetId = connection.getLastConnectionCheckCredentialSetId?.();
const connectionCheckError = connectionIsActive
? undefined
: connection.getLastConnectionCheckError();
@@ -1496,6 +1505,9 @@ Please follow these instructions when using tools from the respective MCP server
flowManager,
options?.signal,
!recoveryTakeoverConsumed,
+ recordedCredentialSetId !== undefined
+ ? recordedCredentialSetId
+ : checkedCredentialSetId,
),
);
} catch (recoveryError) {
@@ -1530,6 +1542,7 @@ Please follow these instructions when using tools from the respective MCP server
},
);
+ const requestedCredentialSetId = connection.getOAuthCredentialSetId?.();
let result: Awaited<ReturnType<typeof requestTool>>;
try {
result = await requestTool();
@@ -1602,6 +1615,7 @@ Please follow these instructions when using tools from the respective MCP server
flowManager,
options?.signal,
!recoveryTakeoverConsumed,
+ requestedCredentialSetId,
),
);
} catch (recoveryError) {
diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.ts
index 8ee4c63d56..62a3861bda 100644
--- a/packages/api/src/mcp/UserConnectionManager.ts
+++ b/packages/api/src/mcp/UserConnectionManager.ts
@@ -838,11 +838,10 @@ export abstract class UserConnectionManager {
}
};
const recaptureCredentialGeneration: t.UserConnectionContext['onOAuthCredentialsInvalidated'] =
- ephemeralConnection
- ? undefined
- : async () => {
- credentialGeneration = await getMCPToolsChangedGeneration({ userId, serverName });
- };
+ async () => {
+ credentialGeneration = await getMCPToolsChangedGeneration({ userId, serverName });
+ return credentialGeneration;
+ };
const useOAuth = usesDirectOpenIDBearerRecovery(config)
? false
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
index 5e505685fe..674ac4f616 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -18,7 +18,13 @@ import { MCPConnection } from '~/mcp/connection';
import { processMCPEnv } from '~/utils';
jest.mock('~/mcp/connection');
-jest.mock('~/mcp/oauth');
+jest.mock('~/mcp/oauth', () => ({
+ ...jest.createMockFromModule<typeof import('~/mcp/oauth')>('~/mcp/oauth'),
+ MCPTokenRefreshUnavailableError:
+ jest.requireActual('~/mcp/oauth').MCPTokenRefreshUnavailableError,
+ MCPTokenStorageUnavailableError:
+ jest.requireActual('~/mcp/oauth').MCPTokenStorageUnavailableError,
+}));
jest.mock('~/utils/graph', () => ({
...jest.requireActual('~/utils/graph'),
preProcessGraphTokens: jest.fn(async (options) => options),
@@ -79,8 +85,18 @@ class InspectableMCPConnectionFactory extends MCPConnectionFactory {
return await this.getOAuthTokens();
}
- public async attemptSilentTokenRefreshForTest(): Promise<MCPOAuthTokens | null> {
- return await this.attemptSilentTokenRefresh();
+ public async attemptSilentTokenRefreshForTest(
+ rejected?: string | null,
+ ): Promise<MCPOAuthTokens | null> {
+ return await this.attemptSilentTokenRefresh(rejected);
+ }
+
+ public bindRequestRecoveryForTest(connection: MCPConnection): () => void {
+ return this.handleOAuthEvents(connection, 'oauthReauthenticationRequired');
+ }
+
+ public async invalidateTokenFlowsForTest(tokens?: MCPOAuthTokens): Promise<void> {
+ await this.invalidateGetTokensFlow(tokens);
}
public async handleOAuthRequiredForTest() {
@@ -153,6 +169,7 @@ describe('MCPConnectionFactory', () => {
connect: jest.fn(),
isConnected: jest.fn(),
setOAuthTokens: jest.fn(),
+ getOAuthCredentialSetId: jest.fn().mockReturnValue('rejected-generation'),
setAuthorizationHeader: jest.fn(),
stopReconnecting: jest.fn(),
on: jest.fn().mockReturnValue(mockConnectionInstance),
@@ -556,7 +573,9 @@ describe('MCPConnectionFactory', () => {
it('should tenant-scope mcp_get_tokens flow locks', async () => {
mockTenantStorage.getStore.mockReturnValueOnce({ tenantId: 'tenant-a' });
- mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPOAuthHandler.generateFlowId.mockImplementation((_user, _server, tenant) =>
+ tenant ? `tenant:${tenant}:flow123` : 'flow123',
+ );
const basicOptions = {
serverName: 'test-server',
@@ -619,11 +638,17 @@ describe('MCPConnectionFactory', () => {
const tokenLoadingFactory = (
hooks: Pick<
t.UserConnectionContext,
- 'onOAuthCredentialsAdopted' | 'onOAuthCredentialsInvalidated'
+ | 'onOAuthCredentialsAdopted'
+ | 'onOAuthCredentialsInvalidated'
+ | 'onOAuthCredentialsChanged'
> = {},
+ oauthRefreshCoordination?: boolean,
) =>
new InspectableMCPConnectionFactory(
- { serverName: 'test-server', serverConfig: mockServerConfig },
+ {
+ serverName: 'test-server',
+ serverConfig: { ...mockServerConfig, oauthRefreshCoordination },
+ },
{
useOAuth: true,
user: mockUser,
@@ -638,6 +663,26 @@ describe('MCPConnectionFactory', () => {
},
);
+ it.each([undefined, false, true])(
+ 'switches token protocol only when coordination is enabled (%s)',
+ async (enabled) => {
+ mockProcessMCPEnv.mockReturnValue({
+ ...mockServerConfig,
+ oauthRefreshCoordination: enabled,
+ });
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('legacy-token-flow');
+ mockMCPOAuthHandler.generateTokenFlowId.mockReturnValue('versioned-token-flow');
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
+ await tokenLoadingFactory({}, enabled).getOAuthTokensForTest();
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledWith(
+ enabled ? 'versioned-token-flow' : 'legacy-token-flow',
+ 'mcp_get_tokens',
+ expect.any(Function),
+ undefined,
+ );
+ },
+ );
+
it('re-reads stored tokens after the flow it waited on is invalidated by a credential change', async () => {
const storedTokens: MCPOAuthTokens = {
access_token: 'stored-after-change',
@@ -666,7 +711,79 @@ describe('MCPConnectionFactory', () => {
expect(onOAuthCredentialsAdopted).not.toHaveBeenCalled();
});
- it('reports the tokens missing when the re-read loses its flow as well', async () => {
+ it('does not announce a second credential change for a peer rotation it adopted', async () => {
+ const adoptedTokens: MCPOAuthTokens = {
+ access_token: 'rotated-by-a-peer',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'peer-generation',
+ };
+ const onOAuthCredentialsChanged = jest.fn().mockResolvedValue(undefined);
+ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue('peer-publication');
+ /** Run the flow handler, so the factory's own `onTokensAdopted` wiring is exercised. */
+ mockFlowManager.createFlowWithHandler.mockImplementation(
+ async (_flowId: string, _type: string, handler: () => Promise<MCPOAuthTokens | null>) =>
+ handler(),
+ );
+ mockMCPTokenStorage.getTokens.mockImplementationOnce(async (params) => {
+ await params.onTokensAdopted?.(adoptedTokens);
+ return adoptedTokens;
+ });
+ mockFlowManager.getFlowState.mockResolvedValue({
+ type: 'mcp_get_tokens',
+ status: 'COMPLETED',
+ metadata: {},
+ createdAt: Date.now(),
+ result: adoptedTokens,
+ });
+
+ await expect(
+ tokenLoadingFactory({
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsInvalidated,
+ }).getOAuthTokensForTest(),
+ ).resolves.toEqual(adoptedTokens);
+
+ /**
+ * The peer persisted and announced this rotation. Announcing it again would advance the
+ * authorization generation a second time for one rotation, retiring the generation
+ * recaptured here and leaving the build fenced against its own tool publication.
+ */
+ expect(onOAuthCredentialsChanged).not.toHaveBeenCalled();
+ expect(adoptedTokens.publication_generation).toBe('peer-publication');
+ expect(onOAuthCredentialsInvalidated).toHaveBeenCalledTimes(1);
+ /** Capture the peer generation before sharing its tokens with flow waiters. */
+ expect(mockFlowManager.deleteFlow).toHaveBeenCalled();
+ expect(onOAuthCredentialsInvalidated.mock.invocationCallOrder[0]).toBeLessThan(
+ mockFlowManager.deleteFlow.mock.invocationCallOrder[0],
+ );
+ });
+
+ it.each([false, true])(
+ 'removes both completed token protocols before rollback (%s)',
+ async (enabled) => {
+ mockProcessMCPEnv.mockReturnValue({
+ ...mockServerConfig,
+ oauthRefreshCoordination: enabled,
+ });
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('legacy-flow');
+ mockMCPOAuthHandler.generateTokenFlowId.mockReturnValue('versioned-flow');
+ mockFlowManager.getFlowState.mockResolvedValue({
+ status: 'COMPLETED',
+ type: 'mcp_get_tokens',
+ metadata: {},
+ createdAt: Date.now(),
+ });
+ await tokenLoadingFactory({}, enabled).invalidateTokenFlowsForTest();
+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('legacy-flow', 'mcp_get_tokens');
+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith(
+ 'versioned-flow',
+ 'mcp_get_tokens',
+ );
+ },
+ );
+
+ it('defers recovery when the re-read loses its flow as well', async () => {
mockFlowManager.createFlowWithHandler.mockRejectedValue(
new FlowStateNotFoundError('mcp_get_tokens'),
);
@@ -674,24 +791,82 @@ describe('MCPConnectionFactory', () => {
await expect(
tokenLoadingFactory({ onOAuthCredentialsInvalidated }).getOAuthTokensForTest(),
- ).resolves.toBeNull();
+ ).rejects.toMatchObject({ name: 'MCPTokenStorageUnavailableError' });
expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(2);
expect(onOAuthCredentialsInvalidated).toHaveBeenCalledTimes(1);
});
- it('does not re-read after a token load failure that is not a lost flow', async () => {
- mockFlowManager.createFlowWithHandler.mockRejectedValue(
- new Error('token store unavailable'),
+ it.each(['Error', 'TimeoutError', 'ReplyError', 'SyntaxError'])(
+ 'defers a %s token-flow failure without prompting',
+ async (name) => {
+ mockFlowManager.createFlowWithHandler.mockRejectedValue(
+ Object.assign(new Error('token store unavailable'), { name }),
+ );
+ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);
+
+ await expect(
+ tokenLoadingFactory({ onOAuthCredentialsInvalidated }).getOAuthTokensForTest(),
+ ).rejects.toMatchObject({ name: 'MCPTokenStorageUnavailableError' });
+
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);
+ expect(onOAuthCredentialsInvalidated).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['TimeoutError', 'ReplyError', 'SyntaxError'])(
+ 'defers a %s from the token-flow retry',
+ async (name) => {
+ mockFlowManager.createFlowWithHandler
+ .mockRejectedValueOnce(new FlowStateNotFoundError('mcp_get_tokens'))
+ .mockRejectedValueOnce(Object.assign(new Error('cache unavailable'), { name }));
+ await expect(tokenLoadingFactory().getOAuthTokensForTest()).rejects.toMatchObject({
+ name: 'MCPTokenStorageUnavailableError',
+ });
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it('preserves serialized reauthentication as an explicit interactive outcome', async () => {
+ mockFlowManager.createFlowWithHandler.mockRejectedValueOnce(
+ Object.assign(new Error('credentials missing'), {
+ name: 'ReauthenticationRequiredError',
+ }),
);
- const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);
+ await expect(tokenLoadingFactory().getOAuthTokensForTest()).resolves.toBeNull();
+ });
- await expect(
- tokenLoadingFactory({ onOAuthCredentialsInvalidated }).getOAuthTokensForTest(),
- ).resolves.toBeNull();
+ it('invalidates a stale flow token and defers the next storage read', async () => {
+ mockFlowManager.createFlowWithHandler.mockResolvedValueOnce({
+ access_token: 'stale',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ });
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValueOnce(false);
+ mockFlowManager.getFlowState.mockResolvedValueOnce({
+ type: 'mcp_get_tokens',
+ status: 'COMPLETED',
+ metadata: {},
+ createdAt: Date.now(),
+ });
+ await expect(tokenLoadingFactory().getOAuthTokensForTest()).rejects.toMatchObject({
+ name: 'MCPTokenStorageUnavailableError',
+ });
+ expect(mockFlowManager.deleteFlow).toHaveBeenCalled();
+ });
- expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);
- expect(onOAuthCredentialsInvalidated).not.toHaveBeenCalled();
+ it('defers a failed client metadata verification read', async () => {
+ mockFlowManager.createFlowWithHandler.mockResolvedValueOnce({
+ access_token: 'stored',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ });
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockRejectedValueOnce(
+ new SyntaxError('cache unavailable'),
+ );
+ await expect(tokenLoadingFactory().getOAuthTokensForTest()).rejects.toMatchObject({
+ name: 'MCPTokenStorageUnavailableError',
+ });
});
it('adopts the generation carried by tokens another authorization released', async () => {
@@ -2052,6 +2227,112 @@ describe('MCPConnectionFactory', () => {
expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();
});
+ it('defers instead of prompting when another replica holds the refresh', async () => {
+ const sseConfig = {
+ ...mockServerConfig,
+ url: 'https://api.example.com',
+ type: 'sse' as const,
+ } as t.SSEOptions;
+
+ const basicOptions = { serverName: 'test-server', serverConfig: sseConfig };
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart: jest.fn(),
+ oauthEnd: jest.fn(),
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+
+ mockProcessMCPEnv.mockReturnValue(sseConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ /** Named rather than constructed, because these errors cross the built package boundary. */
+ const contended = new Error(
+ 'OAuth token refresh is temporarily unavailable for "test-server"',
+ );
+ contended.name = 'MCPTokenRefreshUnavailableError';
+ mockMCPTokenStorage.forceRefreshTokens.mockRejectedValueOnce(contended);
+ mockFlowManager.getFlowState.mockResolvedValue(null);
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+
+ let oauthRequiredHandler: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+
+ try {
+ await MCPConnectionFactory.create(basicOptions, oauthOptions);
+ } catch {
+ // Expected
+ }
+
+ await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });
+
+ /**
+ * A peer redeeming this credential is not a reason to ask the user to authorize the server
+ * again: its rotation is about to land and the next request adopts it. Prompting here is the
+ * outcome the cross-replica flight exists to prevent, so the connection defers instead.
+ */
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ expect(oauthOptions.oauthStart).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthFailed', contended);
+ });
+
+ it('retries silent recovery after contention without spending the interactive phase', async () => {
+ const factory = new InspectableMCPConnectionFactory(
+ {
+ serverName: 'test-server',
+ serverConfig: { type: 'sse', url: 'https://api.example.com' },
+ },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+ let handler!: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, listener) => {
+ if (event === 'oauthReauthenticationRequired') handler = listener as typeof handler;
+ return mockConnectionInstance;
+ });
+ factory.bindRequestRecoveryForTest(mockConnectionInstance);
+ const unavailable = Object.assign(new Error('retry'), {
+ name: 'MCPTokenRefreshUnavailableError',
+ });
+ const tokens = { access_token: 'fresh', token_type: 'Bearer', obtained_at: Date.now() };
+ mockMCPTokenStorage.forceRefreshTokens
+ .mockRejectedValueOnce(unavailable)
+ .mockResolvedValueOnce(tokens);
+ await handler({ serverUrl: 'https://api.example.com' });
+ await handler({
+ serverUrl: 'https://api.example.com',
+ rejectedCredentialSetId: null,
+ });
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledWith(
+ expect.objectContaining({ rejectedCredentialSetId: 'rejected-generation' }),
+ );
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenLastCalledWith(
+ expect.objectContaining({ rejectedCredentialSetId: null }),
+ );
+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(tokens);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ });
+
it('should bypass any flow cache on silent refresh and invalidate mcp_get_tokens cache (regression for stale cached token reuse)', async () => {
// Reproduces the cache-collision flagged by Codex on PR #13369: when an
// earlier `getOAuthTokens` call cached its (now server-rejected) tokens
@@ -2327,64 +2608,70 @@ describe('MCPConnectionFactory', () => {
expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(refreshedTokens);
});
- it('does not coalesce silent refreshes across different server bindings', async () => {
- const makeConfig = (url: string): t.SSEOptions => ({
- type: 'sse',
- url,
- initTimeout: 15000,
- });
- const tokenMethods = {
- findToken: jest.fn(),
- createToken: jest.fn(),
- updateToken: jest.fn(),
- deleteTokens: jest.fn(),
- };
- mockProcessMCPEnv.mockImplementation(({ options }) => options as t.MCPOptions);
+ it.each([false, true])(
+ 'coalesces legacy identities only within the same binding (different: %s)',
+ async (different) => {
+ const makeConfig = (url: string): t.SSEOptions => ({
+ type: 'sse',
+ url,
+ initTimeout: 15000,
+ });
+ const tokenMethods = {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ };
+ mockProcessMCPEnv.mockImplementation(({ options }) => options as t.MCPOptions);
- const factoryA = new InspectableMCPConnectionFactory(
- { serverName: 'test-server', serverConfig: makeConfig('https://server-a.example.com/mcp') },
- { useOAuth: true, user: mockUser, flowManager: mockFlowManager, tokenMethods },
- );
- const factoryB = new InspectableMCPConnectionFactory(
- { serverName: 'test-server', serverConfig: makeConfig('https://server-b.example.com/mcp') },
- { useOAuth: true, user: mockUser, flowManager: mockFlowManager, tokenMethods },
- );
+ const factoryA = new InspectableMCPConnectionFactory(
+ {
+ serverName: 'test-server',
+ serverConfig: makeConfig('https://server-a.example.com/mcp'),
+ },
+ { useOAuth: true, user: mockUser, flowManager: mockFlowManager, tokenMethods },
+ );
+ const factoryB = new InspectableMCPConnectionFactory(
+ {
+ serverName: 'test-server',
+ serverConfig: makeConfig(
+ different ? 'https://server-b.example.com/mcp' : 'https://server-a.example.com/mcp',
+ ),
+ },
+ { useOAuth: true, user: mockUser, flowManager: mockFlowManager, tokenMethods },
+ );
- const resolutions: Array<(tokens: MCPOAuthTokens) => void> = [];
- mockMCPTokenStorage.forceRefreshTokens.mockImplementation(
- () =>
- new Promise<MCPOAuthTokens>((resolve) => {
- resolutions.push(resolve);
- }),
- );
+ const resolutions: Array<(tokens: MCPOAuthTokens) => void> = [];
+ mockMCPTokenStorage.forceRefreshTokens.mockImplementation(
+ () =>
+ new Promise<MCPOAuthTokens>((resolve) => {
+ resolutions.push(resolve);
+ }),
+ );
- const attemptA = factoryA.attemptSilentTokenRefreshForTest();
- await Promise.resolve();
- const attemptB = factoryB.attemptSilentTokenRefreshForTest();
- await Promise.resolve();
+ const attemptA = factoryA.attemptSilentTokenRefreshForTest();
+ await Promise.resolve();
+ const attemptB = factoryB.attemptSilentTokenRefreshForTest(null);
+ await Promise.resolve();
- expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);
- const scopeA = mockMCPTokenStorage.forceRefreshTokens.mock.calls[0][0].singleFlightScope;
- const scopeB = mockMCPTokenStorage.forceRefreshTokens.mock.calls[1][0].singleFlightScope;
- expect(scopeA).toEqual(expect.any(String));
- expect(scopeB).toEqual(expect.any(String));
- expect(scopeA).not.toBe(scopeB);
- const tokensA: MCPOAuthTokens = {
- access_token: 'server-a-token',
- token_type: 'Bearer',
- obtained_at: Date.now(),
- };
- const tokensB: MCPOAuthTokens = {
- access_token: 'server-b-token',
- token_type: 'Bearer',
- obtained_at: Date.now(),
- };
- resolutions[0](tokensA);
- resolutions[1](tokensB);
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(different ? 2 : 1);
+ const tokensA: MCPOAuthTokens = {
+ access_token: 'server-a-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ const tokensB: MCPOAuthTokens = {
+ access_token: 'server-b-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ resolutions[0](tokensA);
+ resolutions[1]?.(tokensB);
- await expect(attemptA).resolves.toEqual(tokensA);
- await expect(attemptB).resolves.toEqual(tokensB);
- });
+ await expect(attemptA).resolves.toEqual(tokensA);
+ await expect(attemptB).resolves.toEqual(different ? tokensB : tokensA);
+ },
+ );
it('should keep the in-flight silent-refresh lock until the aborted refresh settles', async () => {
// A timed-out caller should fall back to interactive OAuth immediately,
@@ -2477,7 +2764,11 @@ describe('MCPConnectionFactory', () => {
).inflightSilentRefreshes;
expect(inflightMap.size).toBe(1);
expect(refreshSignal?.aborted).toBe(true);
- expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith(
+ 'oauthFailed',
+ expect.objectContaining({ name: 'MCPTokenRefreshUnavailableError' }),
+ );
const secondAttempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });
await secondAttempt;
@@ -2588,7 +2879,7 @@ describe('MCPConnectionFactory', () => {
}
});
- it('should reserve interactive OAuth fallback time when initTimeout is omitted', async () => {
+ it('defers recovery when the silent refresh budget expires with initTimeout omitted', async () => {
const sseConfig = {
url: 'https://api.example.com',
type: 'sse' as const,
@@ -2656,7 +2947,11 @@ describe('MCPConnectionFactory', () => {
await attempt;
expect(refreshSignal?.aborted).toBe(true);
- expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith(
+ 'oauthFailed',
+ expect.objectContaining({ name: 'MCPTokenRefreshUnavailableError' }),
+ );
} finally {
jest.useRealTimers();
}
@@ -2736,7 +3031,11 @@ describe('MCPConnectionFactory', () => {
await attempt;
expect(refreshSignal?.aborted).toBe(true);
- expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith(
+ 'oauthFailed',
+ expect.objectContaining({ name: 'MCPTokenRefreshUnavailableError' }),
+ );
} finally {
jest.useRealTimers();
}
@@ -3633,7 +3932,9 @@ describe('MCPConnectionFactory', () => {
(getTenantId as jest.Mock).mockReturnValue('tenant-a');
mockProcessMCPEnv.mockReturnValue(sseConfig);
- mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPOAuthHandler.generateFlowId.mockImplementation((_user, _server, tenant) =>
+ tenant ? `tenant:${tenant}:flow123` : 'flow123',
+ );
// Mirror the real storage contract: `onRefreshSuccess` runs inside the
// shared redemption after the rotated tokens are persisted.
mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce(async (params) => {
@@ -4870,6 +5171,7 @@ describe('MCPConnectionFactory', () => {
}),
isConnected: jest.fn().mockResolvedValue(false),
setOAuthTokens: jest.fn(),
+ getOAuthCredentialSetId: jest.fn().mockReturnValue('rejected-generation'),
on: jest.fn(),
once: jest.fn(),
off: jest.fn(),
@@ -4981,6 +5283,7 @@ describe('MCPConnectionFactory', () => {
}),
isConnected: jest.fn().mockResolvedValue(false),
setOAuthTokens: jest.fn(),
+ getOAuthCredentialSetId: jest.fn().mockReturnValue('rejected-generation'),
on: jest.fn(),
once: jest.fn(),
off: jest.fn(),
@@ -5287,7 +5590,7 @@ describe('MCPConnectionFactory', () => {
const oauthOptions = makeOAuthOptions();
mockProcessMCPEnv.mockReturnValue(serverConfig);
- mockFlowManager.createFlowWithHandler.mockRejectedValue(new Error('no tokens'));
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
const mockTokens: MCPOAuthTokens = {
access_token: 'bq-token',
@@ -5455,7 +5758,7 @@ describe('MCPConnectionFactory', () => {
const oauthOptions = makeOAuthOptions();
mockProcessMCPEnv.mockReturnValue(serverConfig);
- mockFlowManager.createFlowWithHandler.mockRejectedValue(new Error('no tokens'));
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
mockConnectionInstance.isConnected.mockResolvedValue(true);
const connection = await MCPConnectionFactory.create(
@@ -5531,7 +5834,7 @@ describe('MCPConnectionFactory', () => {
};
mockProcessMCPEnv.mockReturnValue(serverConfig);
- mockFlowManager.createFlowWithHandler.mockRejectedValue(new Error('no tokens'));
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
const mockFlowData = {
authorizationUrl: 'https://accounts.google.com/o/oauth2/auth',
@@ -5567,7 +5870,7 @@ describe('MCPConnectionFactory', () => {
const oauthOptions = makeOAuthOptions();
mockProcessMCPEnv.mockReturnValue(serverConfig);
- mockFlowManager.createFlowWithHandler.mockRejectedValue(new Error('no tokens'));
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
wireEventHandlers(mockConnectionInstance);
mockConnectionInstance.isConnected.mockResolvedValue(false);
@@ -5600,7 +5903,7 @@ describe('MCPConnectionFactory', () => {
const oauthOptions = makeOAuthOptions();
mockProcessMCPEnv.mockReturnValue(serverConfig);
- mockFlowManager.createFlowWithHandler.mockRejectedValue(new Error('no tokens'));
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);
const mockTokens: MCPOAuthTokens = {
access_token: 'cleanup-token',
diff --git a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
index 531351fc23..40a3fa79a9 100644
--- a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
+++ b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
@@ -64,6 +64,21 @@ describe('MCP OAuth flow state across Redis-backed instances', () => {
);
});
+ it('preserves a retryable handler failure across Redis pods', async () => {
+ const flowId = createFlowId();
+ await podA.initFlow(flowId, FLOW_TYPE);
+ const flow = await podA.getFlowState(flowId, FLOW_TYPE);
+ const waiter = podB.createFlowWithHandler(flowId, FLOW_TYPE, async () => 'unexpected');
+ const error = new Error('refresh lease unavailable');
+ error.name = 'MCPTokenRefreshUnavailableError';
+ await podA.failFlowIfCurrent(flowId, FLOW_TYPE, flow!.createdAt, '', error);
+ await expect(waiter).rejects.toMatchObject({ name: error.name, message: error.message });
+ expect(await podB.getFlowState(flowId, FLOW_TYPE)).toMatchObject({
+ error: error.message,
+ errorName: error.name,
+ });
+ });
+
it('retains a terminal OAuth failure for polling on another pod', async () => {
const flowId = createFlowId();
diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.ts
index 976e22fbe4..3970263c12 100644
--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts
@@ -1127,6 +1127,19 @@ describe('MCPManager', () => {
}),
connection,
);
+ const generationSpy = jest
+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')
+ .mockResolvedValue('request-peer-generation');
+ try {
+ const oauthOptions = (MCPConnectionFactory.attachRequestOAuthHandler as jest.Mock).mock
+ .calls[0][1];
+ await expect(oauthOptions.onOAuthCredentialsInvalidated()).resolves.toBe(
+ 'request-peer-generation',
+ );
+ expect(generationSpy).toHaveBeenCalledWith({ userId: mockUser.id, serverName });
+ } finally {
+ generationSpy.mockRestore();
+ }
expect(connection.listenerCount('oauthReauthenticationRequired')).toBe(0);
});
@@ -1522,6 +1535,46 @@ describe('MCPManager', () => {
expect(request.mock.calls[1]).toEqual(request.mock.calls[0]);
});
+ it('carries the request credential through a delayed 401 after the connection rotates', async () => {
+ let credential = 'credential-a';
+ const request = jest
+ .fn()
+ .mockImplementationOnce(async () => {
+ credential = 'credential-b';
+ throw new Error('Non-200 status code (401)');
+ })
+ .mockResolvedValueOnce(toolResult);
+ const connection = createConnection(request);
+ connection.getOAuthCredentialSetId = jest.fn(() => credential);
+ const events: unknown[] = [];
+ connection.on('oauthReauthenticationRequired', (event) => events.push(event));
+ attachOAuthHandler();
+ const manager = await createManager(connection);
+ await expect(callTool(manager)).resolves.toBeDefined();
+ expect(events).toEqual([
+ expect.objectContaining({ rejectedCredentialSetId: 'credential-a' }),
+ ]);
+ expect(credential).toBe('credential-b');
+ });
+
+ it.each(['credential-a', null])(
+ 'preserves the recorded transport identity %s',
+ async (rejected) => {
+ const connection = createConnection(jest.fn().mockResolvedValue(toolResult));
+ const error = new Error('Non-200 status code (401)');
+ (connection.isConnected as jest.Mock).mockResolvedValueOnce(false);
+ (connection.getLastConnectionCheckError as jest.Mock).mockReturnValue(error);
+ connection.getOAuthCredentialSetId = jest.fn(() => 'credential-b');
+ connection.getLastConnectionCheckCredentialSetId = jest.fn(() => rejected);
+ const events: unknown[] = [];
+ connection.on('oauthReauthenticationRequired', (event) => events.push(event));
+ attachOAuthHandler();
+ const manager = await createManager(connection);
+ await expect(callTool(manager)).resolves.toBeDefined();
+ expect(events).toEqual([expect.objectContaining({ rejectedCredentialSetId: rejected })]);
+ },
+ );
+
it('joins recovery registered between cached checkout and lease acquisition', async () => {
const request = jest.fn().mockResolvedValue(toolResult);
const connection = createConnection(request);
@@ -4540,6 +4593,7 @@ describe('MCPManager', () => {
});
const onDiscoveryDetached = jest.fn();
+ const onOAuthCredentialsAdopted = jest.fn();
const manager = await MCPManager.createInstance(newMCPServersConfig());
const result = await manager.discoverServerTools({
serverName,
@@ -4547,6 +4601,7 @@ describe('MCPManager', () => {
flowManager: mockFlowManager as unknown as t.ToolDiscoveryOptions['flowManager'],
graphTokenResolver: jest.fn(),
onDiscoveryDetached,
+ onOAuthCredentialsAdopted,
});
expect(result.tools).toEqual(mockTools);
@@ -4560,8 +4615,21 @@ describe('MCPManager', () => {
useOAuth: true,
graphTokenResolver: expect.any(Function),
onDiscoveryDetached,
+ onOAuthCredentialsAdopted,
}),
);
+ const generationSpy = jest
+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')
+ .mockResolvedValue('discovery-peer-generation');
+ try {
+ const oauthOptions = (MCPConnectionFactory.discoverTools as jest.Mock).mock.calls[0][1];
+ await expect(oauthOptions.onOAuthCredentialsInvalidated()).resolves.toBe(
+ 'discovery-peer-generation',
+ );
+ expect(generationSpy).toHaveBeenCalledWith({ userId: mockUser.id, serverName });
+ } finally {
+ generationSpy.mockRestore();
+ }
});
});
@@ -5899,6 +5967,29 @@ describe('MCPManager', () => {
}
});
+ it('lets an ephemeral flow owner carry the peer generation to persistent waiters', async () => {
+ const generationSpy = jest
+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')
+ .mockResolvedValue('peer-generation');
+ let captured: string | void;
+ const { serverConfig, flowManager } = adoptingOAuthServer(async (options) => {
+ captured = await options.onOAuthCredentialsInvalidated?.();
+ });
+ try {
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ await manager.getUserConnection({
+ serverName,
+ user: mockUser,
+ flowManager,
+ serverConfig,
+ ephemeralConnection: true,
+ });
+ expect(captured!).toBe('peer-generation');
+ } finally {
+ generationSpy.mockRestore();
+ }
+ });
+
it('re-captures the generation before re-reading credentials a change invalidated', async () => {
const generationSpy = jest
.spyOn(toolsChanged, 'getMCPToolsChangedGeneration')
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts
index dcacd2b18e..10a89011a0 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts
@@ -133,6 +133,40 @@ describe('MCPConnection OAuth Events — Real Server', () => {
await connectPromise.catch(() => undefined);
});
+ it.each(['credential-a', undefined])(
+ 'retains a delayed transport identity including absence (%s)',
+ async (credential) => {
+ const accessToken = await exchangeCodeForToken(server.url);
+ connection = new MCPConnection({
+ serverName: 'test-server',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ userId: 'user-1',
+ oauthTokens: {
+ access_token: accessToken,
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: credential,
+ },
+ });
+ await connection.connect();
+ connection.setOAuthTokens({
+ access_token: 'new-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'credential-b',
+ });
+ const error = new Error('Error POSTing to endpoint (HTTP 401): Unauthorized');
+ const transport = (
+ connection as unknown as { transport: { onerror: (error: Error) => void } }
+ ).transport;
+ transport.onerror(error);
+ expect(await connection.isConnected()).toBe(false);
+ expect(connection.getLastConnectionCheckError()).toBe(error);
+ expect(connection.getLastConnectionCheckCredentialSetId()).toBe(credential ?? null);
+ expect(connection.getOAuthCredentialSetId()).toBe(credential ?? null);
+ },
+ );
+
it('should not emit oauthRequired when connecting with a valid token', async () => {
const accessToken = await exchangeCodeForToken(server.url);
@@ -236,6 +270,7 @@ describe('MCPConnection OAuth Events — Real Server', () => {
userId: 'user-1',
oauthTokens: {
access_token: accessToken,
+ credential_set_id: 'expired-credential',
token_type: 'Bearer',
} as MCPOAuthTokens,
});
@@ -250,7 +285,8 @@ describe('MCPConnection OAuth Events — Real Server', () => {
// Reconnect should trigger oauthRequired since token is expired on the server
let oauthFired = false;
- connection.on('oauthRequired', () => {
+ connection.on('oauthRequired', (event) => {
+ expect(event.rejectedCredentialSetId).toBe('expired-credential');
oauthFired = true;
connection!.emit('oauthFailed', new Error('Will retry with fresh token'));
});
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
index ffb84a918b..6d6920a32e 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
@@ -276,7 +276,14 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
const budgetMs = 2_000;
const startedAt = Date.now();
const discovery = ProviderRefreshFactory.discoverTools(
- { serverName: 'test-srv', serverConfig: { type: 'streamable-http', url: server.url } },
+ {
+ serverName: 'test-srv',
+ serverConfig: {
+ type: 'streamable-http',
+ url: server.url,
+ oauthRefreshCoordination: true,
+ },
+ },
{
useOAuth: true,
user: { id: 'u1' } as IUser,
@@ -384,7 +391,14 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
>,
) =>
new TokenLoadingFactory(
- { serverName: 'test-srv', serverConfig: { type: 'streamable-http', url: server.url } },
+ {
+ serverName: 'test-srv',
+ serverConfig: {
+ type: 'streamable-http',
+ url: server.url,
+ oauthRefreshCoordination: true,
+ },
+ },
{
useOAuth: true,
user: { id: 'u1' } as IUser,
@@ -1067,3 +1081,38 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
});
});
});
+
+describe('mixed-version token flow isolation', () => {
+ it.each([undefined, 'tenant/a'])(
+ 'does not expose typed failures to legacy readers (%s)',
+ async (tenantId) => {
+ const manager = new FlowStateManager<MCPOAuthTokens>(new Keyv(), { ci: true, ttl: 30_000 });
+ const legacyId = MCPOAuthHandler.generateFlowId('u1', 'test-srv', tenantId);
+ const currentId = MCPOAuthHandler.generateTokenFlowId('u1', 'test-srv', tenantId);
+ expect(currentId).not.toBe(legacyId);
+ await manager.initFlow(legacyId, 'mcp_get_tokens');
+ await manager.initFlow(currentId, 'mcp_get_tokens');
+ const failure = Object.assign(new Error('retry later'), {
+ name: 'MCPTokenRefreshUnavailableError',
+ });
+ await manager.failFlow(currentId, 'mcp_get_tokens', failure);
+ expect(await manager.getFlowState(legacyId, 'mcp_get_tokens')).toMatchObject({
+ status: 'PENDING',
+ });
+ expect(await manager.getFlowState(currentId, 'mcp_get_tokens')).toMatchObject({
+ status: 'FAILED',
+ errorName: failure.name,
+ });
+ await manager.completeFlow(legacyId, 'mcp_get_tokens', {
+ access_token: 'legacy-token',
+ obtained_at: Date.now(),
+ token_type: 'Bearer',
+ });
+ expect(await manager.getFlowState(currentId, 'mcp_get_tokens')).toMatchObject({
+ status: 'FAILED',
+ });
+ await manager.deleteFlow(legacyId, 'mcp_get_tokens');
+ await manager.deleteFlow(currentId, 'mcp_get_tokens');
+ },
+ );
+});
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
index 6cc2215ab2..e635d9f140 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
@@ -5,6 +5,7 @@
* refresh callback wiring, and ReauthenticationRequiredError paths.
*/
+import { Keyv } from 'keyv';
import type { TokenMethods } from '@librechat/data-schemas';
import type { MCPOAuthTokens } from '~/mcp/oauth';
import {
@@ -12,8 +13,11 @@ import {
MCPTokenRefreshUnavailableError,
MCPTokenStorageUnavailableError,
ReauthenticationRequiredError,
+ getMCPOAuthLeaseId,
+ getMCPOAuthRefreshFlightLeaseId,
} from '~/mcp/oauth';
import { InMemoryTokenStore } from './helpers/oauthTestServer';
+import { FlowStateManager } from '~/flow/manager';
const credentialSetId = 'credential-set-a';
const storedTokenMetadata = { credential_set_id: credentialSetId };
@@ -1301,7 +1305,14 @@ describe('MCPTokenStorage', () => {
);
});
- it('should handle unauthorized_client refresh error', async () => {
+ it.each([
+ 'unauthorized_client',
+ 'unsupported_grant_type',
+ 'invalid_request',
+ 'invalid_scope',
+ 'invalid_target',
+ 'access_denied',
+ ])('handles permanent endpoint rejection %s', async (code) => {
const { logger } = await import('@librechat/data-schemas');
await createBoundToken(store, {
@@ -1319,7 +1330,7 @@ describe('MCPTokenStorage', () => {
expiresIn: 86400,
});
- const refreshTokens = jest.fn().mockRejectedValue(new Error('unauthorized_client'));
+ const refreshTokens = jest.fn().mockRejectedValue(new Error(code));
const result = await MCPTokenStorage.getTokens({
userId: 'u1',
@@ -1330,9 +1341,11 @@ describe('MCPTokenStorage', () => {
});
expect(result).toBeNull();
- expect(logger.info).toHaveBeenCalledWith(
- expect.stringContaining('does not support refresh tokens'),
- );
+ if (code === 'unauthorized_client') {
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining('does not support refresh tokens'),
+ );
+ }
});
it('should delete client registration and refresh token on invalid_client when deleteTokens provided', async () => {
@@ -2034,6 +2047,7 @@ describe('MCPTokenStorage', () => {
});
const refreshParams = (refreshTokens: GetTokensRefresh, serverName = 'srv1') => ({
+ coordinateRefresh: true,
userId: 'u1',
serverName,
findToken: store.findToken,
@@ -2155,7 +2169,13 @@ describe('MCPTokenStorage', () => {
const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
const flowManager = {
getLeaseGeneration: jest.fn().mockResolvedValue(7),
- acquireLease: jest.fn().mockResolvedValue(null),
+ /** The refresh flight is free; the persistence fence is what teardown holds. */
+ acquireLease: jest.fn(
+ async (_leaseId: string, options?: { expectedGeneration?: number }) =>
+ options?.expectedGeneration === undefined
+ ? { generation: 0, release: jest.fn().mockResolvedValue(undefined) }
+ : null,
+ ),
};
await expect(
@@ -2205,6 +2225,772 @@ describe('MCPTokenStorage', () => {
).toMatchObject({ token: 'enc:rt-2' });
});
+ /**
+ * The process-local `inflightRefreshes` map coalesces one Node process; these cover the
+ * cross-replica flight that keeps two pods from redeeming the same refresh token.
+ */
+ describe('cross-replica refresh flight', () => {
+ /** Simulates the peer replica's completed redemption landing in shared storage. */
+ const peerRotates = async (serverName: string, generation: number) => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: `mcp:${serverName}`,
+ token: `enc:at-${generation}`,
+ expiresIn: 3600,
+ });
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: `mcp:${serverName}:refresh`,
+ token: `enc:rt-${generation}`,
+ expiresIn: 86400,
+ });
+ };
+
+ /** Answers the persistence fence, and the flight only once `freeFlight` is true. */
+ const flightManager = (isFlightFree: () => Promise<boolean>) => ({
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(
+ async (_leaseId: string, options?: { expectedGeneration?: number }) => {
+ if (options?.expectedGeneration !== undefined) {
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }
+ return (await isFlightFree())
+ ? { generation: 0, release: jest.fn().mockResolvedValue(undefined) }
+ : null;
+ },
+ ),
+ });
+
+ it('serializes independent refresh owners with real shared leases and adopts the winner', async () => {
+ const serverName = 'real-flight';
+ await seedRefreshableTokens(serverName);
+ const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse });
+ const firstManager = new FlowStateManager(keyv, { ttl: 30000, ci: true });
+ const secondManager = new FlowStateManager(keyv, { ttl: 30000, ci: true });
+ let resolveProvider!: (tokens: MCPOAuthTokens) => void;
+ const provider = jest.fn(
+ () =>
+ new Promise<MCPOAuthTokens>((resolve) => {
+ resolveProvider = resolve;
+ }),
+ );
+ const first = MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(provider, serverName),
+ singleFlightScope: 'pod-a',
+ flowManager: firstManager,
+ });
+ await waitFor(() => provider.mock.calls.length === 1);
+ const acquire = jest.spyOn(secondManager, 'acquireLease');
+ const second = MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(provider, serverName),
+ singleFlightScope: 'pod-b',
+ flowManager: secondManager,
+ });
+ await waitFor(() => acquire.mock.calls.length > 0);
+ resolveProvider(rotatedTokens(2));
+ const results = await Promise.all([first, second]);
+ expect(results[0]).toMatchObject({ access_token: 'at-2' });
+ expect(results[1]).toMatchObject({ access_token: 'at-2' });
+ expect(provider).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([undefined, false])(
+ 'keeps the legacy refresh path until rollout is enabled (%s)',
+ async (coordinateRefresh) => {
+ const serverName = 'rollout-disabled';
+ await seedRefreshableTokens(serverName);
+ const flowManager = flightManager(async () => true);
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, serverName),
+ flowManager,
+ coordinateRefresh,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-2' });
+ expect(flowManager.acquireLease.mock.calls.map(([id]) => id)).not.toContain(
+ getMCPOAuthRefreshFlightLeaseId('u1', serverName),
+ );
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('coalesces different request identities while coordination is disabled', async () => {
+ const serverName = 'legacy-local-coalescing';
+ await seedRefreshableTokens(serverName);
+ let finish!: (tokens: MCPOAuthTokens) => void;
+ const refreshTokens = jest.fn(
+ () =>
+ new Promise<MCPOAuthTokens>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const params = {
+ ...refreshParams(refreshTokens, serverName),
+ coordinateRefresh: false,
+ flowManager: flightManager(async () => true),
+ };
+ const first = MCPTokenStorage.forceRefreshTokens(params);
+ await waitFor(() => refreshTokens.mock.calls.length === 1);
+ const second = MCPTokenStorage.forceRefreshTokens({
+ ...params,
+ rejectedCredentialSetId: credentialSetId,
+ });
+ const unauthenticated = MCPTokenStorage.forceRefreshTokens({
+ ...params,
+ rejectedCredentialSetId: null,
+ });
+ finish(rotatedTokens(2));
+ const results = await Promise.all([first, second, unauthenticated]);
+ expect(results.map((tokens) => tokens?.access_token)).toEqual(['at-2', 'at-2', 'at-2']);
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds a flight distinct from the teardown lease and releases it after redeeming', async () => {
+ await seedRefreshableTokens('flight-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ const release = jest.fn().mockResolvedValue(undefined);
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn().mockResolvedValue({ generation: 0, release }),
+ };
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'flight-srv'),
+ flowManager: flowManager as never,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-2' });
+
+ const flightLeaseId = getMCPOAuthRefreshFlightLeaseId('u1', 'flight-srv');
+ expect(flightLeaseId).not.toBe(getMCPOAuthLeaseId('u1', 'flight-srv'));
+ expect(flowManager.acquireLease).toHaveBeenCalledWith(
+ flightLeaseId,
+ expect.objectContaining({ waitMs: 0 }),
+ );
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ expect(release).toHaveBeenCalled();
+ });
+
+ it('adopts the tokens another replica rotated while the flight was held', async () => {
+ await seedRefreshableTokens('adopt-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(9));
+ const onRefreshSuccess = jest.fn().mockResolvedValue(undefined);
+ const onTokensAdopted = jest.fn().mockResolvedValue(undefined);
+ let attempts = 0;
+ const flowManager = flightManager(async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ return false;
+ }
+ /** The peer completed its redemption and rotated the credential. */
+ await peerRotates('adopt-srv', 3);
+ return true;
+ });
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'adopt-srv'),
+ flowManager: flowManager as never,
+ onRefreshSuccess,
+ onTokensAdopted,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-3', refresh_token: 'rt-3' });
+
+ expect(refreshTokens).not.toHaveBeenCalled();
+ /**
+ * The adopted credential was published by the peer under a generation only the store
+ * knows, so the caller is told it adopted rather than refreshed: the refresh callback
+ * would leave this replica's captured generation pointing before the peer's rotation.
+ */
+ expect(onTokensAdopted).toHaveBeenCalledWith(
+ expect.objectContaining({ access_token: 'at-3' }),
+ );
+ expect(onRefreshSuccess).not.toHaveBeenCalled();
+ });
+
+ it('holds the flight through adoption publication and releases it when the callback fails', async () => {
+ const serverName = 'adoption-publication';
+ await seedRefreshableTokens(serverName);
+ const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse });
+ const flowManager = new FlowStateManager(keyv, { ttl: 30000, ci: true });
+ const leaseId = getMCPOAuthRefreshFlightLeaseId('u1', serverName);
+ const acquire = flowManager.acquireLease.bind(flowManager);
+ jest.spyOn(flowManager, 'acquireLease').mockImplementation(async (id, options) => {
+ if (id === leaseId) await peerRotates(serverName, 3);
+ return acquire(id, options);
+ });
+ const onTokensAdopted = jest.fn(async () => {
+ expect(await acquire(leaseId, { waitMs: 0 })).toBeNull();
+ expect(await acquire(getMCPOAuthLeaseId('u1', serverName), { waitMs: 0 })).toBeNull();
+ throw new Error('publication storage unavailable');
+ });
+ const refreshTokens = jest.fn();
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, serverName),
+ flowManager,
+ onTokensAdopted,
+ }),
+ ).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);
+ expect(onTokensAdopted).toHaveBeenCalledTimes(1);
+ expect(refreshTokens).not.toHaveBeenCalled();
+ const successor = await acquire(leaseId, { waitMs: 0 });
+ expect(successor).not.toBeNull();
+ await successor?.release();
+ const persistenceSuccessor = await acquire(getMCPOAuthLeaseId('u1', serverName), {
+ waitMs: 0,
+ });
+ expect(persistenceSuccessor).not.toBeNull();
+ await persistenceSuccessor?.release();
+ });
+
+ it('defers adoption when a callback supersedes it before the persistence fence is acquired', async () => {
+ const serverName = 'callback-before-adoption-fence';
+ await seedRefreshableTokens(serverName);
+ await peerRotates(serverName, 3);
+ const flowManager = new FlowStateManager(new Keyv(), { ttl: 30000, ci: true });
+ const acquire = flowManager.acquireLease.bind(flowManager);
+ jest.spyOn(flowManager, 'acquireLease').mockImplementation(async (id, options) => {
+ if (id === getMCPOAuthLeaseId('u1', serverName)) await peerRotates(serverName, 4);
+ return acquire(id, options);
+ });
+ const onTokensAdopted = jest.fn();
+ const refreshTokens = jest.fn();
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, serverName),
+ flowManager,
+ rejectedCredentialSetId: 'before-peer-generation',
+ onTokensAdopted,
+ }),
+ ).rejects.toBeInstanceOf(MCPTokenStorageUnavailableError);
+ expect(onTokensAdopted).not.toHaveBeenCalled();
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it.each([60000, 1e9])(
+ 'fences callback publication with a bounded persistence wait (%s)',
+ async (waitMs) => {
+ const serverName = 'callback-adoption-fence';
+ await seedRefreshableTokens(serverName);
+ await peerRotates(serverName, 3);
+ const flowManager = new FlowStateManager(new Keyv(), { ttl: 30000, ci: true });
+ let finishAdoption!: () => void;
+ const publication = new Promise<void>((resolve) => {
+ finishAdoption = resolve;
+ });
+ const onTokensAdopted = jest.fn(async () => publication);
+ const adopted = MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(jest.fn(), serverName),
+ flowManager,
+ rejectedCredentialSetId: 'before-peer-generation',
+ onTokensAdopted,
+ });
+ await waitFor(() => onTokensAdopted.mock.calls.length === 1);
+ const onStoreCommitted = jest.fn();
+ const acquireSpy = jest.spyOn(flowManager, 'acquireLease');
+ const callback = MCPTokenStorage.storeTokens({
+ ...refreshParams(jest.fn(), serverName),
+ flowManager,
+ persistenceWaitTimeoutMs: waitMs,
+ tokens: rotatedTokens(4),
+ clientInfo: { client_id: 'cid', client_secret: 'secret' },
+ metadata: storedBindingMetadata,
+ onStoreCommitted,
+ });
+ try {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ expect(onStoreCommitted).not.toHaveBeenCalled();
+ expect(acquireSpy).toHaveBeenCalledWith(getMCPOAuthLeaseId('u1', serverName), {
+ waitMs: Math.min(waitMs, 840000),
+ });
+ expect(
+ await MCPTokenStorage.isCurrentAccessToken({
+ userId: 'u1',
+ serverName,
+ findToken: store.findToken,
+ accessToken: 'at-3',
+ credentialSetId,
+ }),
+ ).toBe(true);
+ } finally {
+ finishAdoption();
+ await Promise.allSettled([adopted, callback]);
+ }
+ await expect(adopted).resolves.toMatchObject({ access_token: 'at-3' });
+ await expect(callback).resolves.toMatchObject({ access_token: 'at-4' });
+ expect(onStoreCommitted).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('still redeems when the credential is unchanged after waiting for the flight', async () => {
+ await seedRefreshableTokens('unchanged-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(4));
+ let attempts = 0;
+ const flowManager = flightManager(async () => ++attempts > 1);
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'unchanged-srv'),
+ flowManager: flowManager as never,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-4' });
+
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ });
+
+ it('defers without redeeming when the lease store cannot answer', async () => {
+ await seedRefreshableTokens('lease-down-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(5));
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(
+ async (_leaseId: string, options?: { expectedGeneration?: number }) => {
+ if (options?.expectedGeneration !== undefined) {
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }
+ throw new Error('redis unavailable');
+ },
+ ),
+ };
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'lease-down-srv'),
+ flowManager: flowManager as never,
+ }),
+ ).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);
+
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it('fails as retryable, never redeeming, when the holder keeps the flight', async () => {
+ await seedRefreshableTokens('wedged-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ const flowManager = flightManager(async () => false);
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'wedged-srv'),
+ flowManager: flowManager as never,
+ refreshWaitTimeoutMs: 400,
+ }),
+ ).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);
+
+ /** The point of the fence: no redemption raced the holder, and the credential survives. */
+ expect(refreshTokens).not.toHaveBeenCalled();
+ expect(
+ await store.findToken({
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:wedged-srv:refresh',
+ }),
+ ).toMatchObject({ token: 'enc:rt-1' });
+ });
+
+ it('releases the flight and defers when the under-lease read fails', async () => {
+ await seedRefreshableTokens('adopt-fail-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(6));
+ const release = jest.fn().mockResolvedValue(undefined);
+ let refreshReads = 0;
+ const findToken = (async (filter: { type?: string }) => {
+ /** The observed read succeeds; the read taken after acquiring the flight fails. */
+ if (filter.type === 'mcp_oauth_refresh' && ++refreshReads === 2) {
+ throw new Error('token storage unavailable');
+ }
+ return store.findToken(filter as never);
+ }) as typeof store.findToken;
+ let attempts = 0;
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(async (_id: string, options?: { expectedGeneration?: number }) =>
+ options?.expectedGeneration !== undefined || ++attempts > 1
+ ? { generation: 0, release }
+ : null,
+ ),
+ };
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'adopt-fail-srv'),
+ findToken,
+ flowManager: flowManager as never,
+ }),
+ ).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);
+
+ /** A failed read must never consume a possibly rotated credential. */
+ expect(refreshTokens).not.toHaveBeenCalled();
+ expect(release).toHaveBeenCalled();
+ });
+
+ it('serializes two OAuth binding scopes onto one stored credential', async () => {
+ await seedRefreshableTokens('rolling-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ const flightIds = new Set<string>();
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(async (id: string, options?: { expectedGeneration?: number }) => {
+ if (options?.expectedGeneration === undefined) {
+ flightIds.add(id);
+ }
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }),
+ };
+ const refresh = (singleFlightScope: string) =>
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'rolling-srv'),
+ singleFlightScope,
+ flowManager: flowManager as never,
+ });
+
+ await Promise.all([refresh('binding-a'), refresh('binding-b')]);
+
+ /**
+ * Two process-local slots, so both redeem, but one distributed flight: a rolling config
+ * change moves the binding digest without moving the stored credential, and keying the
+ * flight by that digest would let the two versions redeem the same token concurrently.
+ */
+ expect(refreshTokens).toHaveBeenCalledTimes(2);
+ expect(flightIds.size).toBe(1);
+ });
+
+ it('holds the flight past the window that aborts a stalled redemption', async () => {
+ await seedRefreshableTokens('margin-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ const leaseWindows: number[] = [];
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(async (_id: string, options?: { leaseMs?: number }) => {
+ if (options?.leaseMs != null) {
+ leaseWindows.push(options.leaseMs);
+ }
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }),
+ };
+
+ await MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'margin-srv'),
+ flowManager: flowManager as never,
+ });
+
+ /**
+ * Aborting a stalled redemption does not prove the token endpoint declined the request, so
+ * the flight has to outlive the abort rather than expire alongside it.
+ */
+ expect(leaseWindows.length).toBeGreaterThan(0);
+ expect(Math.min(...leaseWindows)).toBeGreaterThan(
+ MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS,
+ );
+ });
+
+ it('adopts a rotation that lands while the first flight attempt is failing', async () => {
+ await seedRefreshableTokens('snapshot-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(9));
+ let attempts = 0;
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(async (_id: string, options?: { expectedGeneration?: number }) => {
+ if (options?.expectedGeneration !== undefined) {
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }
+ attempts += 1;
+ if (attempts === 1) {
+ /** The holder stores and releases in the gap after this attempt fails. */
+ await peerRotates('snapshot-srv', 4);
+ return null;
+ }
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }),
+ };
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'snapshot-srv'),
+ flowManager: flowManager as never,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-4' });
+
+ /**
+ * Snapshotting after the failed attempt would have captured the rotated credential as the
+ * baseline, found it unchanged, and redeemed the token the holder had just been issued.
+ */
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it('adopts a rotation that landed before its first acquisition attempt', async () => {
+ await seedRefreshableTokens('first-acquire-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(9));
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(async (_id: string, options?: { expectedGeneration?: number }) => {
+ if (options?.expectedGeneration === undefined) {
+ /** The peer rotated and released before this replica ever contended. */
+ await peerRotates('first-acquire-srv', 4);
+ }
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }),
+ };
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'first-acquire-srv'),
+ flowManager: flowManager as never,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-4' });
+
+ /**
+ * An acquisition that succeeds first try says nothing about which credential is stored: it
+ * proves only that no peer holds the flight now, not that none held it a moment ago.
+ */
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it('keeps the fence when the pre-flight observation read fails', async () => {
+ await seedRefreshableTokens('observe-fail-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ let refreshReads = 0;
+ const findToken = (async (filter: { type?: string }) => {
+ if (filter.type === 'mcp_oauth_refresh' && ++refreshReads === 1) {
+ throw new Error('token storage unavailable');
+ }
+ return store.findToken(filter as never);
+ }) as typeof store.findToken;
+ const flightIds: string[] = [];
+ const flowManager = {
+ getLeaseGeneration: jest.fn().mockResolvedValue(0),
+ acquireLease: jest.fn(async (id: string, options?: { expectedGeneration?: number }) => {
+ if (options?.expectedGeneration === undefined) {
+ flightIds.push(id);
+ }
+ return { generation: 0, release: jest.fn().mockResolvedValue(undefined) };
+ }),
+ };
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, 'observe-fail-srv'),
+ findToken,
+ flowManager: flowManager as never,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-2' });
+
+ /**
+ * Losing the observation costs adoption and nothing else. Redeeming without the flight
+ * because a read failed is the concurrency the flight exists to remove, so only the lease
+ * store failing may reach the unfenced fallback.
+ */
+ expect(flightIds).toHaveLength(1);
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([false, true])(
+ 'adopts a rotation between access and refresh reads (missing access: %s)',
+ async (missingAccess) => {
+ const serverName = `split-probe-${missingAccess}`;
+ await seedRefreshableTokens(serverName);
+ if (missingAccess) {
+ await store.deleteTokens({
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: `mcp:${serverName}`,
+ });
+ }
+ let rotated = false;
+ const findToken: typeof store.findToken = async (filter) => {
+ const record = await store.findToken(filter);
+ if (filter.type === 'mcp_oauth' && !rotated) {
+ rotated = true;
+ await MCPTokenStorage.storeTokens({
+ ...refreshParams(jest.fn(), serverName),
+ tokens: rotatedTokens(3),
+ clientInfo: { client_id: 'cid', client_secret: 'secret' },
+ metadata: storedBindingMetadata,
+ expectedCredentialSetId: credentialSetId,
+ });
+ }
+ return record;
+ };
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(9));
+ await expect(
+ MCPTokenStorage.getTokens({
+ ...refreshParams(refreshTokens, serverName),
+ findToken,
+ flowManager: flightManager(async () => true),
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-3', refresh_token: 'rt-3' });
+ expect(refreshTokens).not.toHaveBeenCalled();
+ },
+ );
+
+ it('refreshes normally when an expired access row was removed', async () => {
+ const serverName = 'expired-access-row';
+ await seedRefreshableTokens(serverName);
+ await store.deleteTokens({
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: `mcp:${serverName}`,
+ });
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ await expect(
+ MCPTokenStorage.getTokens({
+ ...refreshParams(refreshTokens, serverName),
+ flowManager: flightManager(async () => true),
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-2' });
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ });
+
+ it('defers a failed client metadata read before provider redemption', async () => {
+ const serverName = 'client-read-failure';
+ await seedRefreshableTokens(serverName);
+ const refreshTokens = jest.fn();
+ const findToken: typeof store.findToken = async (filter) => {
+ if (filter.type === 'mcp_oauth_client') throw new Error('database unavailable');
+ return store.findToken(filter);
+ };
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, serverName),
+ findToken,
+ flowManager: flightManager(async () => true),
+ }),
+ ).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [false, false, credentialSetId],
+ [true, false, credentialSetId],
+ [false, true, credentialSetId],
+ [true, true, credentialSetId],
+ [false, false, null],
+ [true, true, null],
+ ] as const)(
+ 'adopts a newer rejected credential (contended: %s, failed snapshot: %s, rejected: %s)',
+ async (contended, failedSnapshot, rejected) => {
+ const serverName = `already-stored-${contended}`;
+ await seedRefreshableTokens(serverName);
+ await MCPTokenStorage.storeTokens({
+ ...refreshParams(jest.fn(), serverName),
+ tokens: rotatedTokens(3),
+ clientInfo: { client_id: 'cid', client_secret: 'secret' },
+ metadata: storedBindingMetadata,
+ expectedCredentialSetId: credentialSetId,
+ });
+ const findToken = jest.fn(store.findToken);
+ if (failedSnapshot) {
+ findToken.mockRejectedValueOnce(new Error('transient snapshot failure'));
+ }
+ let attempts = 0;
+ const flowManager = flightManager(async () => !contended || ++attempts > 1);
+ const refreshTokens = jest.fn();
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(refreshTokens, serverName),
+ flowManager,
+ rejectedCredentialSetId: rejected as string | null,
+ findToken,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-3', refresh_token: 'rt-3' });
+ expect(refreshTokens).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([false, true])(
+ 'separates known absence from another caller identity (unknown: %s)',
+ async (unknown) => {
+ const serverName = 'different-rejected-generations';
+ await seedRefreshableTokens(serverName);
+ const current = await MCPTokenStorage.storeTokens({
+ ...refreshParams(jest.fn(), serverName),
+ tokens: rotatedTokens(3),
+ clientInfo: { client_id: 'cid', client_secret: 'secret' },
+ metadata: storedBindingMetadata,
+ expectedCredentialSetId: credentialSetId,
+ });
+ const flowManager = new FlowStateManager(
+ new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }),
+ { ttl: 30000, ci: true },
+ );
+ let finishAdoption!: () => void;
+ const onTokensAdopted = jest.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishAdoption = resolve;
+ }),
+ );
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(4));
+ const params = { ...refreshParams(refreshTokens, serverName), flowManager };
+ const adopter = MCPTokenStorage.forceRefreshTokens({
+ ...params,
+ rejectedCredentialSetId: null,
+ onTokensAdopted,
+ });
+ await waitFor(() => onTokensAdopted.mock.calls.length === 1);
+ const rejectedCurrent = MCPTokenStorage.forceRefreshTokens({
+ ...params,
+ rejectedCredentialSetId: unknown ? undefined : current.credential_set_id,
+ });
+ finishAdoption();
+ await expect(adopter).resolves.toMatchObject({ access_token: 'at-3' });
+ await expect(rejectedCurrent).resolves.toMatchObject({ access_token: 'at-4' });
+ expect(refreshTokens).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('reuses the refresh record getTokens already loaded', async () => {
+ await seedRefreshableTokens('reuse-srv');
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));
+ let refreshReads = 0;
+ const findToken = (async (filter: { type?: string }) => {
+ if (filter.type === 'mcp_oauth_refresh') {
+ refreshReads += 1;
+ }
+ return store.findToken(filter as never);
+ }) as typeof store.findToken;
+ const flowManager = flightManager(async () => true);
+
+ await expect(
+ MCPTokenStorage.getTokens({
+ ...refreshParams(refreshTokens, 'reuse-srv'),
+ findToken,
+ flowManager: flowManager as never,
+ }),
+ ).resolves.toMatchObject({ access_token: 'at-2' });
+
+ /**
+ * Two reads: the probe `getTokens` takes to decide a refresh is needed, reused as the
+ * flight's observation baseline, and one under the flight that both proves rotation and
+ * supplies the credential redeemed. This path is on the latency budget CI measures, so a
+ * third read of the same record is a regression rather than a detail.
+ */
+ expect(refreshReads).toBe(2);
+ });
+
+ it('clamps a configured wait into the window the stale abort allows', () => {
+ const resolve = (configured?: number) =>
+ (
+ MCPTokenStorage as unknown as {
+ resolveRefreshFlightWaitMs: (value?: number) => number;
+ }
+ ).resolveRefreshFlightWaitMs(configured);
+
+ expect(resolve()).toBe(MCPTokenStorage.DEFAULT_REFRESH_FLIGHT_WAIT_MS);
+ expect(resolve(0)).toBe(MCPTokenStorage.DEFAULT_REFRESH_FLIGHT_WAIT_MS);
+ expect(resolve(2_000)).toBe(2_000);
+ /** Above the ceiling the stale abort, not the operator's wait, would decide the outcome. */
+ expect(resolve(10 * MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS)).toBe(
+ MCPTokenStorage.MAX_REFRESH_FLIGHT_WAIT_MS,
+ );
+ expect(MCPTokenStorage.MAX_REFRESH_FLIGHT_WAIT_MS).toBe(
+ MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS / 2,
+ );
+ });
+ });
+
it('does not fence a colon-prefixed sibling server', async () => {
await seedRefreshableTokens('foo:bar');
let resolveRefresh!: (tokens: MCPOAuthTokens) => void;
diff --git a/packages/api/src/mcp/catalog/recovery.spec.ts b/packages/api/src/mcp/catalog/recovery.spec.ts
index 865796e795..f5f75a308d 100644
--- a/packages/api/src/mcp/catalog/recovery.spec.ts
+++ b/packages/api/src/mcp/catalog/recovery.spec.ts
@@ -1211,6 +1211,24 @@ describe('loadMCPServerCatalogs — credential refresh during discovery', () =>
expect(result.serversWithoutTools).toEqual([]);
});
+ it.each([false, true])(
+ 'tracks peer adoption and still fences a later writer (%s)',
+ async (superseded) => {
+ const fence = createFence();
+ const discoverServerTools = jest.fn(async (options: ToolDiscoveryOptions) => {
+ await fence.rotateOnAnotherReplica();
+ await options.onOAuthCredentialsAdopted?.('generation-2');
+ if (superseded) await fence.rotateOnAnotherReplica();
+ return { tools: listedTools };
+ });
+ const result = await loadCatalogs(fence, discoverServerTools);
+ expect(result.serverTools).toEqual(
+ superseded ? new Map() : new Map([[serverName, recoveredTools]]),
+ );
+ expect(result.serversWithoutTools).toEqual(superseded ? [serverName] : []);
+ },
+ );
+
it.each([
['another replica', 'rotateOnAnotherReplica'],
['another request on this replica', 'rotateOnThisReplica'],
diff --git a/packages/api/src/mcp/catalog/recovery.ts b/packages/api/src/mcp/catalog/recovery.ts
index a1668bceb5..8e542575a4 100644
--- a/packages/api/src/mcp/catalog/recovery.ts
+++ b/packages/api/src/mcp/catalog/recovery.ts
@@ -682,6 +682,10 @@ async function discoverCandidate(
deps.onOAuthCredentialsChanging,
trackPublication,
),
+ onOAuthCredentialsAdopted: async (generation) => {
+ // Adoption changes the generation this flight serves without writing another fence.
+ await trackPublication?.(async () => generation);
+ },
onDiscoveryDetached: onDetached,
});
/** Discovery can await work that ignores its budget — a token refresh persisting behind a
diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.ts
index 722952466f..24d1ed08b9 100644
--- a/packages/api/src/mcp/connection.ts
+++ b/packages/api/src/mcp/connection.ts
@@ -1032,6 +1032,8 @@ export class MCPConnection extends EventEmitter {
private lastPingTime: number;
private lastConnectionCheckAt: number = 0;
private lastConnectionCheckError?: unknown;
+ private lastConnectionCheckCredentialSetId?: string | null;
+ private transportCredentialSetId: string | null = null;
private oauthTokens?: MCPOAuthTokens | null;
private requestHeaders?: Record<string, string> | null;
private oauthRequired = false;
@@ -1704,6 +1706,7 @@ export class MCPConnection extends EventEmitter {
this.suspendedToolListSnapshot = undefined;
if (state === 'connected') {
this.lastConnectionCheckError = undefined;
+ this.lastConnectionCheckCredentialSetId = undefined;
const isReconnect = this.hasConnected;
this.hasConnected = true;
this.toolListRefreshSuspended = false;
@@ -1991,6 +1994,7 @@ export class MCPConnection extends EventEmitter {
this.emit('connectionChange', 'connecting');
this.connectPromise = (async () => {
+ let rejectedCredentialSetId = this.oauthTokens?.credential_set_id ?? null;
try {
if (this.transport) {
try {
@@ -2004,6 +2008,7 @@ export class MCPConnection extends EventEmitter {
}
this.transport = await runOutsideTracing(() => this.constructTransport(this.options));
+ rejectedCredentialSetId = this.getOAuthCredentialSetId();
/** `dispose()` can land while the transport is still being constructed — it finds nothing
* to close and returns, so without this check the attempt would go on to connect and
* leave a live connection on a disposed object. Ownership of teardown is ours here. */
@@ -2117,6 +2122,7 @@ export class MCPConnection extends EventEmitter {
// Emit the event
this.emit('oauthRequired', {
+ rejectedCredentialSetId,
serverName: this.serverName,
error,
serverUrl,
@@ -2239,6 +2245,8 @@ export class MCPConnection extends EventEmitter {
private setupTransportErrorHandlers(transport: Transport): void {
this.reportedStandaloneSseConflict = false;
+ const transportCredentialSetId = this.oauthTokens?.credential_set_id ?? null;
+ this.transportCredentialSetId = transportCredentialSetId;
transport.onerror = (error) => {
const rawMessage =
@@ -2331,6 +2339,7 @@ export class MCPConnection extends EventEmitter {
) {
logger.warn(`${this.getLogPrefix()} OAuth authentication error detected`);
this.lastConnectionCheckError = error;
+ this.lastConnectionCheckCredentialSetId = transportCredentialSetId;
this.connectionState = 'error';
this.emit('oauthError', error);
return;
@@ -2768,9 +2777,11 @@ export class MCPConnection extends EventEmitter {
if (now - this.lastConnectionCheckAt < mcpConfig.CONNECTION_CHECK_TTL) {
return true;
}
+ let probeCredentialSetId = this.getOAuthCredentialSetId();
const previousCheckAt = this.lastConnectionCheckAt;
this.lastConnectionCheckAt = now;
this.lastConnectionCheckError = undefined;
+ this.lastConnectionCheckCredentialSetId = undefined;
/** An aborted probe answered nothing: restore the TTL stamp so the next caller probes for
* real, instead of a dead shared connection reading as healthy for the whole TTL window. */
const probeAborted = (): boolean => signal?.aborted === true;
@@ -2799,6 +2810,7 @@ export class MCPConnection extends EventEmitter {
if (!pingUnsupported) {
this.lastConnectionCheckError = error;
+ this.lastConnectionCheckCredentialSetId = probeCredentialSetId;
logger.error(`${this.getLogPrefix()} Ping failed`);
return false;
}
@@ -2809,6 +2821,7 @@ export class MCPConnection extends EventEmitter {
);
try {
+ probeCredentialSetId = this.getOAuthCredentialSetId();
// Get server capabilities to verify connection is truly active
const capabilities = this.client.getServerCapabilities();
@@ -2835,12 +2848,20 @@ export class MCPConnection extends EventEmitter {
}
// If capability check fails, the connection is likely broken
this.lastConnectionCheckError = capabilityError;
+ this.lastConnectionCheckCredentialSetId = probeCredentialSetId;
logger.error(`${this.getLogPrefix()} Connection verification failed`);
return false;
}
}
}
+ /** Identifies the installed transport credential; pending replacement tokens are not sent yet. */
+ public getOAuthCredentialSetId(): string | null {
+ return this.transport
+ ? this.transportCredentialSetId
+ : (this.oauthTokens?.credential_set_id ?? null);
+ }
+
public setOAuthTokens(tokens: MCPOAuthTokens): void {
this.oauthTokens = tokens;
}
@@ -2854,6 +2875,10 @@ export class MCPConnection extends EventEmitter {
return isOAuthAuthenticationError(error);
}
+ public getLastConnectionCheckCredentialSetId(): string | null | undefined {
+ return this.lastConnectionCheckCredentialSetId;
+ }
+
public getLastConnectionCheckError(): unknown {
return this.lastConnectionCheckError;
}
diff --git a/packages/api/src/mcp/oauth/cleanup.test.ts b/packages/api/src/mcp/oauth/cleanup.test.ts
index 218aa7a71e..299628b81d 100644
--- a/packages/api/src/mcp/oauth/cleanup.test.ts
+++ b/packages/api/src/mcp/oauth/cleanup.test.ts
@@ -89,6 +89,7 @@ describe('cleanupMCPServerOAuth', () => {
it('retries when callback persistence crosses the credential snapshot', async () => {
const deleteTokens = jest.fn();
+ const flowManager = createFlowManager();
let clientRead = 0;
const findToken = jest.fn(async ({ type }: { type?: string }) => {
const generation =
@@ -130,10 +131,10 @@ describe('cleanupMCPServerOAuth', () => {
pluginKey: 'mcp_test-server',
serverConfigOverride: { type: 'streamable-http', url: 'https://example.com/mcp' },
dependencies: {
- flowManager: createFlowManager() as never,
+ flowManager: flowManager as never,
oauthHandler: {
generateFlowId: jest.fn(() => 'user-1:test-server'),
- generateTokenFlowId: jest.fn(() => 'user-1:test-server'),
+ generateTokenFlowId: jest.fn(() => 'tokens-v2:user-1:test-server'),
deleteFlowAndStateMapping: jest.fn(),
revokeOAuthToken: jest.fn(),
},
@@ -150,6 +151,11 @@ describe('cleanupMCPServerOAuth', () => {
},
});
+ expect(flowManager.deleteFlow).toHaveBeenCalledWith(
+ 'tokens-v2:user-1:test-server',
+ 'mcp_get_tokens',
+ );
+ expect(flowManager.deleteFlow).toHaveBeenCalledWith('user-1:test-server', 'mcp_get_tokens');
expect(findToken).toHaveBeenCalledTimes(8);
expect(deleteTokens).toHaveBeenCalledTimes(3);
for (const [filter] of deleteTokens.mock.calls) {
diff --git a/packages/api/src/mcp/oauth/cleanup.ts b/packages/api/src/mcp/oauth/cleanup.ts
index 7a89e9687b..a3e1c18e67 100644
--- a/packages/api/src/mcp/oauth/cleanup.ts
+++ b/packages/api/src/mcp/oauth/cleanup.ts
@@ -230,6 +230,7 @@ export async function clearStoredMCPOAuthState({
const baseFlowId = dependencies.oauthHandler.generateFlowId(userId, serverName);
const flowDeletes = [
[dependencies.oauthHandler.generateTokenFlowId(userId, serverName, tenantId), 'mcp_get_tokens'],
+ [dependencies.oauthHandler.generateFlowId(userId, serverName, tenantId), 'mcp_get_tokens'],
[baseFlowId, 'mcp_get_tokens'],
...(!skipOAuthFlows
? ([
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index 83c2b568f2..3d8d61de66 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -1476,9 +1476,13 @@ export class MCPOAuthHandler {
};
}
- /** Same shape as `generateFlowId`; kept distinct so token-fetch flows can diverge from OAuth flows */
+ /**
+ * Token readers using typed retryable outcomes cannot share pending work with legacy readers,
+ * which reconstruct every serialized failure as an untyped Error and initiate consent. Keep
+ * OAuth callback IDs stable, but isolate this version of the token-read protocol in its own key.
+ */
public static generateTokenFlowId(userId: string, serverName: string, tenantId?: string): string {
- return this.generateFlowId(userId, serverName, tenantId);
+ return `tokens-v2:${this.generateFlowId(userId, serverName, tenantId)}`;
}
/**
diff --git a/packages/api/src/mcp/oauth/tokens.ts b/packages/api/src/mcp/oauth/tokens.ts
index 51d401c44f..3f246f4ded 100644
--- a/packages/api/src/mcp/oauth/tokens.ts
+++ b/packages/api/src/mcp/oauth/tokens.ts
@@ -1,5 +1,6 @@
import jwt from 'jsonwebtoken';
import { randomUUID } from 'crypto';
+import { MAX_MCP_OAUTH_PERSISTENCE_WAIT_MS } from 'librechat-data-provider';
import { logger, encryptV2, decryptV2, getTenantId } from '@librechat/data-schemas';
import type {
TokenMethods,
@@ -46,6 +47,9 @@ export class MCPTokenRefreshUnavailableError extends Error {
}
interface StoreTokensParams {
+ /** Interactive writers share the persistence fence with refresh, adoption, and teardown. */
+ flowManager?: Pick<FlowStateManager, 'acquireLease'>;
+ persistenceWaitTimeoutMs?: number;
userId: string;
serverName: string;
tokens: OAuthTokens | ExtendedOAuthTokens | MCPOAuthTokens;
@@ -106,6 +110,27 @@ interface GetTokensParams {
onRefreshPreparing?: () => Promise<(tokens?: MCPOAuthTokens) => Promise<void>>;
/** Separates in-flight redemptions for the same named server under different OAuth bindings. */
singleFlightScope?: string;
+ /**
+ * Invoked instead of `onRefreshSuccess` when this replica adopted a credential another
+ * replica rotated. Distinct because the two carry different information: after our own
+ * redemption we know the generation we published, whereas an adopted credential was
+ * published by a peer under a generation only the store knows, so the caller has to
+ * re-read it rather than assume the one it captured before the rotation.
+ */
+ onTokensAdopted?: (tokens: MCPOAuthTokens) => Promise<void>;
+ /**
+ * The refresh record the caller already loaded, reused as the pre-flight observation baseline.
+ * `getTokens` reads it to decide a refresh is needed, so passing it keeps the flight off a path
+ * the repository's latency budget already counts.
+ */
+ existingRefreshToken?: IToken | null;
+ /** Rejected credential: null means known absence; undefined means no request identity was captured. */
+ rejectedCredentialSetId?: string | null;
+ /** Per-server `oauthRefreshWaitTimeout`: how long to wait on another replica's redemption. */
+ refreshWaitTimeoutMs?: number;
+ /** Staged capability: enable only when every writer honors the persistence fence. */
+ coordinateRefresh?: boolean;
+ persistenceWaitTimeoutMs?: number;
/** Shared cache-backed fence used to serialize refresh persistence with server teardown. */
flowManager?: Pick<FlowStateManager, 'getLeaseGeneration' | 'acquireLease'>;
}
@@ -116,6 +141,27 @@ export const getMCPOAuthLeaseId = (
tenantId: string | undefined = getTenantId(),
): string => JSON.stringify([tenantId ?? '', userId, serverName]);
+/**
+ * Lease that serializes refresh-token redemption for one stored credential across replicas.
+ *
+ * Keyed by what is stored — tenant, user, server name — and deliberately *not* by the caller's
+ * OAuth binding scope, even though the process-local single-flight key carries it. The refresh
+ * record lives at `mcp:<serverName>:refresh`, with no binding in its identifier, and
+ * `assertCredentialSetBinding` compares only `credential_set_id`, so a config change that moves the
+ * binding digest without invalidating the stored credential still permits refresh. Scoping this
+ * lease by that digest would then hand two replicas different locks over one stored token during a
+ * rolling config change, which is the concurrency the lease exists to remove. The scope stays where
+ * it decides which callers may share a returned result, not which redemptions may run at once.
+ *
+ * Distinct from `getMCPOAuthLeaseId`: that lease is the teardown/persistence fence taken *inside* a
+ * redemption, so one shared key would make a redemption wait on a lease it already holds.
+ */
+export const getMCPOAuthRefreshFlightLeaseId = (
+ userId: string,
+ serverName: string,
+ tenantId: string | undefined = getTenantId(),
+): string => JSON.stringify(['refresh', tenantId ?? '', userId, serverName]);
+
/**
* Reads the `exp` claim (RFC 7519 §4.1.4 / RFC 9068) from a JWT-format access
* token, returned as epoch milliseconds. Returns null for opaque (non-JWT)
@@ -168,6 +214,21 @@ function cloneTokenMetadata(tokenData: IToken): Record<string, unknown> | Map<st
return {};
}
+/** Outcome of trying to take the cross-replica refresh flight (`beginRefreshFlight`). */
+interface MCPRefreshFlight {
+ /** Held flight; the caller redeems under it and releases it once the redemption settles. */
+ lease: FlowLease | null;
+ /** Tokens a peer rotated while this replica waited, adopted instead of redeeming again. */
+ adoptedTokens?: MCPOAuthTokens;
+ /**
+ * The refresh record read under the flight, handed to the redemption so one read serves both
+ * rotation detection and the credential submitted. Absent when no flight manager is supplied.
+ */
+ leasedRefreshToken?: IToken | null;
+ /** Teardown or the stale timer fired during the wait; the caller resolves null. */
+ aborted?: boolean;
+}
+
export class MCPTokenStorage {
/**
* Process-local in-flight refresh-token redemptions, keyed by
@@ -180,6 +241,10 @@ export class MCPTokenStorage {
* not merely wasteful — they destroy the freshly issued tokens. Only
* in-flight promises are held (no result caching): each new refresh request
* after settlement triggers a fresh redemption.
+ *
+ * This map coalesces one process. Replicas are serialized by the cross-replica
+ * refresh flight in `beginRefreshFlight`, because a `Map` in pod A says nothing
+ * about what pod B is redeeming.
*/
private static inflightRefreshes = new Map<string, Promise<MCPOAuthTokens | null>>();
private static inflightRefreshControllers = new Map<string, AbortController>();
@@ -195,6 +260,57 @@ export class MCPTokenStorage {
*/
static readonly INFLIGHT_REFRESH_STALE_MS = 60_000;
+ /**
+ * How long the cross-replica refresh flight is held: deliberately longer than the stale window
+ * above, rather than equal to it.
+ *
+ * Aborting a redemption stops this process from waiting on the response. It does not prove the
+ * token endpoint has not already consumed the refresh token, because the request may have been
+ * processed with its response lost, and a stalled event loop can delay the abort past its own
+ * deadline. A replica that took the flight the instant the abort fired could therefore redeem a
+ * credential the provider had already rotated, which is the replay this fence exists to prevent.
+ * The margin covers that settlement instead of assuming it.
+ *
+ * A live replica releases the flight as soon as its redemption settles, so the margin is paid
+ * only by one that died holding it, and paid as retryable failures rather than a revoked grant.
+ * Expiry remains the only recovery from a dead holder, which is why there is no renewal
+ * heartbeat: nothing has to keep running for the flight to be reclaimed.
+ */
+ private static readonly REFRESH_FLIGHT_LEASE_MS: number =
+ MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS * 2;
+
+ /**
+ * How long a replica waits on a flight another replica holds before failing the attempt as
+ * retryable. Not a safety bound: the waiter never redeems unfenced, so this only trades latency
+ * against how long a caller blocks. A contended wait normally ends within a second, when the
+ * holder's rotation lands and is adopted; this governs the holder that died.
+ */
+ static readonly DEFAULT_REFRESH_FLIGHT_WAIT_MS = 15_000;
+
+ /**
+ * Ceiling for a configured wait: half the stale window, because the wait runs *inside* the
+ * redemption whose stale timer aborts it, and the other half is what remains to redeem once the
+ * flight is acquired. A larger value would hand the outcome to that abort instead of the wait.
+ */
+ static readonly MAX_REFRESH_FLIGHT_WAIT_MS: number =
+ MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS / 2;
+
+ /** Interval between checks for a peer's rotation landing, or for its flight coming free. */
+ private static readonly REFRESH_FLIGHT_POLL_MS = 250;
+
+ /** Clamps a server's `oauthRefreshWaitTimeout` into the window the stale abort allows. */
+ private static resolveRefreshFlightWaitMs(configured?: number): number {
+ if (configured == null || !Number.isFinite(configured) || configured <= 0) {
+ return this.DEFAULT_REFRESH_FLIGHT_WAIT_MS;
+ }
+ return Math.min(configured, this.MAX_REFRESH_FLIGHT_WAIT_MS);
+ }
+
+ private static resolvePersistenceWaitMs(configured?: number): number {
+ if (configured == null || !Number.isFinite(configured) || configured <= 0) return 15_000;
+ return Math.min(configured, MAX_MCP_OAUTH_PERSISTENCE_WAIT_MS);
+ }
+
static getLogPrefix(userId: string, serverName: string): string {
return isSystemUserId(userId)
? `[MCP][${serverName}]`
@@ -383,7 +499,28 @@ export class MCPTokenStorage {
* @param params.existingTokens - Optional: Pass existing token state to avoid duplicate DB calls.
* This is useful when refreshing tokens, as getTokens() already has the token state.
*/
- static async storeTokens({
+ static async storeTokens(params: StoreTokensParams): Promise<MCPOAuthTokens> {
+ const lease = params.flowManager
+ ? await params.flowManager.acquireLease(
+ getMCPOAuthLeaseId(params.userId, params.serverName),
+ { waitMs: this.resolvePersistenceWaitMs(params.persistenceWaitTimeoutMs) },
+ )
+ : undefined;
+ if (params.flowManager && !lease) {
+ throw new MCPTokenStorageUnavailableError(
+ params.serverName,
+ new Error('OAuth persistence fence unavailable'),
+ );
+ }
+ try {
+ return await this.storeTokensUnderLease(params);
+ } finally {
+ if (lease)
+ await this.releaseRefreshFlight(lease, this.getLogPrefix(params.userId, params.serverName));
+ }
+ }
+
+ private static async storeTokensUnderLease({
userId,
serverName,
tokens,
@@ -861,6 +998,13 @@ export class MCPTokenStorage {
userId,
serverName,
singleFlightScope ?? '',
+ ...(params.coordinateRefresh === true
+ ? [
+ params.rejectedCredentialSetId === undefined
+ ? ['unknown']
+ : ['known', params.rejectedCredentialSetId],
+ ]
+ : []),
]);
const inflight = this.inflightRefreshes.get(refreshKey);
if (inflight) {
@@ -901,24 +1045,111 @@ export class MCPTokenStorage {
logger.debug(`${logPrefix} Skipping token refresh during OAuth teardown`);
return null;
}
- return this.executeTokenRefresh({
- ...params,
- refreshTokens,
- createToken,
- signal: executionController.signal,
- leaseId,
- leaseGeneration,
- });
- })().finally(() => {
- if (staleTimerRef.current) {
- clearTimeout(staleTimerRef.current);
+ /** Serialize with the redemptions other replicas may be running for this credential. */
+ let flight: MCPRefreshFlight | null = null;
+ if (flowManager && params.coordinateRefresh === true) {
+ try {
+ flight = await this.beginRefreshFlight({
+ userId,
+ serverName,
+ findToken: params.findToken,
+ flowManager,
+ existingRefreshToken: params.existingRefreshToken,
+ existingAccessToken: params.existingAccessToken,
+ rejectedCredentialSetId: params.rejectedCredentialSetId,
+ waitMs: this.resolveRefreshFlightWaitMs(params.refreshWaitTimeoutMs),
+ signal: executionController.signal,
+ logPrefix,
+ });
+ } catch (flightError) {
+ if (flightError instanceof MCPTokenRefreshUnavailableError) {
+ throw flightError;
+ }
+ throw new MCPTokenRefreshUnavailableError(serverName, flightError);
+ }
}
- if (this.inflightRefreshes.get(refreshKey) === refreshPromise) {
- this.inflightRefreshes.delete(refreshKey);
- this.inflightRefreshControllers.delete(refreshKey);
- this.inflightRefreshOwners.delete(refreshKey);
+ if (flight?.aborted) {
+ logger.debug(`${logPrefix} Token refresh aborted while waiting for another replica`);
+ return null;
}
- });
+ try {
+ if (flight?.adoptedTokens) {
+ const adoptionLease = await flowManager!.acquireLease(leaseId, {
+ waitMs: this.resolvePersistenceWaitMs(params.persistenceWaitTimeoutMs),
+ });
+ if (!adoptionLease) {
+ throw new MCPTokenStorageUnavailableError(
+ serverName,
+ new Error('OAuth adoption fence unavailable'),
+ );
+ }
+ try {
+ if (
+ !(await this.isCurrentAccessToken({
+ userId,
+ serverName,
+ findToken: params.findToken,
+ accessToken: flight.adoptedTokens.access_token,
+ credentialSetId: flight.adoptedTokens.credential_set_id,
+ }))
+ ) {
+ throw new MCPTokenStorageUnavailableError(
+ serverName,
+ new Error('Adopted credential was superseded'),
+ );
+ }
+ logger.info(`${logPrefix} Adopted tokens rotated by another replica`);
+ /**
+ * The peer's redemption did the persisting, so only this replica's view needs
+ * updating: its cached `mcp_get_tokens` result still holds the tokens it was
+ * about to replace. `onRefreshPreparing`'s publication fence is deliberately
+ * skipped — that fence exists to order writes this replica makes.
+ */
+ if (params.onTokensAdopted) {
+ await params.onTokensAdopted(flight.adoptedTokens);
+ } else {
+ await params.onRefreshSuccess?.(flight.adoptedTokens);
+ }
+ return flight.adoptedTokens;
+ } finally {
+ await this.releaseRefreshFlight(adoptionLease, logPrefix);
+ }
+ }
+ return await this.executeTokenRefresh({
+ ...params,
+ refreshTokens,
+ createToken,
+ leasedRefreshToken: flight?.leasedRefreshToken,
+ signal: executionController.signal,
+ leaseId,
+ leaseGeneration,
+ });
+ } finally {
+ if (flight?.lease) {
+ await this.releaseRefreshFlight(flight.lease, logPrefix);
+ }
+ }
+ })()
+ .catch((error: unknown) => {
+ if (
+ error instanceof ReauthenticationRequiredError ||
+ error instanceof MCPTokenRefreshUnavailableError ||
+ error instanceof MCPTokenStorageUnavailableError
+ ) {
+ throw error;
+ }
+ throw new MCPTokenRefreshUnavailableError(serverName, error);
+ })
+ .finally(() => {
+ if (staleTimerRef.current) {
+ clearTimeout(staleTimerRef.current);
+ }
+ if (this.inflightRefreshes.get(refreshKey) === refreshPromise) {
+ this.inflightRefreshes.delete(refreshKey);
+ this.inflightRefreshControllers.delete(refreshKey);
+ this.inflightRefreshOwners.delete(refreshKey);
+ }
+ });
/**
* Safety valve for wedged executions: after the stale window the execution
* is aborted so it can never reach the token endpoint with a refresh token
@@ -953,6 +1184,286 @@ export class MCPTokenStorage {
return this.raceWithAbort(refreshPromise, signal);
}
+ /**
+ * Serializes refresh-token redemption for one credential across replicas.
+ *
+ * `inflightRefreshes` coalesces callers inside a single Node process. Behind a load
+ * balancer without session affinity, one user's concurrent requests (a second browser
+ * tab mounting the app, a tool-call fan-out, a 401 on two pods) land on different
+ * replicas, each reads the same not-yet-rotated refresh token from storage and redeems
+ * it. RFC 9700 §4.13.2 servers treat the second redemption of a rotated token as replay
+ * and revoke the whole grant family, including the tokens the first redeemer just
+ * received — the user is then asked to authorize the server again.
+ *
+ * The flight is the cross-replica lease the OAuth teardown fence already uses
+ * (`FlowStateManager.acquireLease`: a Redis Lua compare-and-set when `USE_REDIS` is
+ * configured, process-static otherwise), so single-replica deployments and deployments
+ * without Redis behave exactly as before.
+ *
+ * Returns the held lease, or the tokens a peer rotated while this replica waited — the
+ * cross-replica equivalent of "Joining in-flight token refresh". Redeeming again after
+ * the wait would be correct but pointless: it burns a second rotation on a credential
+ * that was just replaced.
+ */
+ private static async beginRefreshFlight({
+ userId,
+ serverName,
+ findToken,
+ flowManager,
+ existingRefreshToken,
+ existingAccessToken,
+ rejectedCredentialSetId,
+ waitMs,
+ signal,
+ logPrefix,
+ }: {
+ userId: string;
+ serverName: string;
+ findToken: GetTokensParams['findToken'];
+ flowManager: NonNullable<GetTokensParams['flowManager']>;
+ existingRefreshToken?: IToken | null;
+ existingAccessToken?: IToken | null;
+ rejectedCredentialSetId?: string | null;
+ waitMs: number;
+ /** Internal stale-abort signal owned by `forceRefreshTokens`, also fired by teardown. */
+ signal: AbortSignal;
+ logPrefix: string;
+ }): Promise<MCPRefreshFlight> {
+ const flightLeaseId = getMCPOAuthRefreshFlightLeaseId(userId, serverName);
+ const leaseMs = MCPTokenStorage.REFRESH_FLIGHT_LEASE_MS;
+
+ /**
+ * Baseline for recognizing a peer's rotation: the stored credential changing under us, rather
+ * than timestamps another pod's clock wrote. Taken before the first acquisition attempt, since
+ * a holder that stores and releases during that attempt would otherwise be observed
+ * post-rotation and its fresh credential redeemed a second time.
+ *
+ * `getTokens` already read this record to decide a refresh was needed, so the common path pays
+ * nothing for the baseline. When no record is supplied and the read fails, the baseline is
+ * simply absent: that costs the adoption optimization and nothing else, and it must not skip
+ * the flight, because proceeding unfenced over a storage error is how two replicas come to
+ * redeem one credential. Lease-store failures also defer the attempt.
+ */
+ let observedRefreshToken = existingRefreshToken ?? null;
+ if (!observedRefreshToken) {
+ try {
+ observedRefreshToken = await this.readRefreshTokenRecord({
+ userId,
+ serverName,
+ findToken,
+ });
+ } catch (snapshotError) {
+ logger.debug(`${logPrefix} Could not observe the credential before the refresh flight`, {
+ error: snapshotError,
+ });
+ }
+ }
+
+ /**
+ * Polled rather than delegated to `acquireLease`'s own wait, for two reasons: OAuth teardown
+ * aborts in-flight redemptions and then awaits them, so it must not sit blocked on a peer's
+ * lease; and every acquisition has to be followed by a rotation check, including the first,
+ * because a peer can rotate and release before this replica's first attempt.
+ */
+ const waitUntil = Date.now() + waitMs;
+ let announcedWait = false;
+ while (!signal.aborted) {
+ const lease = await flowManager.acquireLease(flightLeaseId, { leaseMs, waitMs: 0 });
+ if (lease) {
+ return await this.resolveAcquiredFlight({
+ userId,
+ serverName,
+ findToken,
+ lease,
+ observedRefreshToken,
+ existingAccessToken,
+ rejectedCredentialSetId,
+ logPrefix,
+ });
+ }
+ if (Date.now() >= waitUntil) {
+ /**
+ * The holder outlived the wait. Redeeming now would race a redemption that may still reach
+ * the token endpoint, so the attempt fails as retryable instead of unfenced: `getTokens`
+ * callers defer connection recovery on this error, the stored credential is left intact,
+ * and a later attempt acquires the flight once the holder's own stale abort releases it.
+ */
+ throw new MCPTokenRefreshUnavailableError(
+ serverName,
+ new Error(`Another replica held the OAuth refresh flight for longer than ${waitMs}ms`),
+ );
+ }
+ if (!announcedWait) {
+ announcedWait = true;
+ logger.debug(`${logPrefix} Waiting for a token refresh held by another replica`);
+ }
+ await new Promise((resolve) => setTimeout(resolve, MCPTokenStorage.REFRESH_FLIGHT_POLL_MS));
+ }
+ return { lease: null, aborted: true };
+ }
+
+ /**
+ * Decides what a held flight is for, and the only place that decision is made.
+ *
+ * Acquiring the flight is the sole proof that no peer is mid-redemption, so it is also the moment
+ * a peer's completed rotation becomes safe to read. That applies to the first acquisition exactly
+ * as much as to one that followed a wait: a peer can rotate, store and release before this replica
+ * ever contends, and an acquisition that looks uncontended says nothing about which credential is
+ * stored now.
+ *
+ * The record read here serves both purposes: it is the evidence of rotation and, when nothing
+ * rotated, the credential the redemption submits. Reading it once under the flight is what keeps
+ * the fence off the serial-read budget the auth and startup paths are measured against.
+ */
+ private static async resolveAcquiredFlight({
+ userId,
+ serverName,
+ findToken,
+ lease,
+ observedRefreshToken,
+ existingAccessToken,
+ rejectedCredentialSetId,
+ logPrefix,
+ }: {
+ userId: string;
+ serverName: string;
+ findToken: GetTokensParams['findToken'];
+ lease: FlowLease;
+ observedRefreshToken: IToken | null;
+ existingAccessToken?: IToken | null;
+ rejectedCredentialSetId?: string | null;
+ logPrefix: string;
+ }): Promise<MCPRefreshFlight> {
+ let leasedRefreshToken: IToken | null;
+ try {
+ leasedRefreshToken = await this.readRefreshTokenRecord({ userId, serverName, findToken });
+ } catch (readError) {
+ await this.releaseRefreshFlight(lease, logPrefix);
+ throw new MCPTokenRefreshUnavailableError(serverName, readError);
+ }
+
+ let adoptedTokens: MCPOAuthTokens | null;
+ try {
+ adoptedTokens = await this.adoptRotatedTokens({
+ userId,
+ serverName,
+ findToken,
+ observedRefreshToken,
+ existingAccessToken,
+ rejectedCredentialSetId,
+ leasedRefreshToken,
+ });
+ } catch (adoptionError) {
+ await this.releaseRefreshFlight(lease, logPrefix);
+ throw new MCPTokenRefreshUnavailableError(serverName, adoptionError);
+ }
+ if (!adoptedTokens) {
+ return { lease, leasedRefreshToken };
+ }
+ return { lease, adoptedTokens };
+ }
+
+ /** Releases a flight lease without letting a release failure mask the caller's outcome. */
+ private static async releaseRefreshFlight(lease: FlowLease, logPrefix: string): Promise<void> {
+ try {
+ await lease.release();
+ } catch (releaseError) {
+ logger.warn(`${logPrefix} Failed to release the OAuth refresh flight`, {
+ error: releaseError,
+ });
+ }
+ }
+
+ private static readRefreshTokenRecord({
+ userId,
+ serverName,
+ findToken,
+ }: {
+ userId: string;
+ serverName: string;
+ findToken: GetTokensParams['findToken'];
+ }): Promise<IToken | null> {
+ return findToken({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `mcp:${serverName}:refresh`,
+ });
+ }
+
+ /**
+ * Returns the tokens another replica stored before this one took the refresh flight, or null
+ * when nothing usable was rotated. The stored refresh record changing between the two reads it
+ * is given is the evidence of a completed peer redemption: `storeTokens` rewrites the access and
+ * refresh records together, so a different ciphertext or credential set means the pair
+ * on disk is no longer the one this caller read.
+ *
+ * An unchanged record is not adopted even when the access token still looks valid,
+ * because `forceRefreshTokens` is also the 401 path: there the resource server — not
+ * `expiresAt` — is the authority, and returning the token it just rejected would loop.
+ */
+ private static async adoptRotatedTokens({
+ userId,
+ serverName,
+ findToken,
+ observedRefreshToken,
+ existingAccessToken,
+ rejectedCredentialSetId,
+ leasedRefreshToken,
+ }: {
+ userId: string;
+ serverName: string;
+ findToken: GetTokensParams['findToken'];
+ /** The credential as this replica saw it before contending for the flight. */
+ observedRefreshToken: IToken | null;
+ existingAccessToken?: IToken | null;
+ rejectedCredentialSetId?: string | null;
+ /** The credential as stored once the flight was held. */
+ leasedRefreshToken: IToken | null;
+ }): Promise<MCPOAuthTokens | null> {
+ if (!leasedRefreshToken || (!observedRefreshToken && rejectedCredentialSetId === undefined)) {
+ return null;
+ }
+ const rotated =
+ (rejectedCredentialSetId !== undefined &&
+ rejectedCredentialSetId !== getCredentialSetId(leasedRefreshToken)) ||
+ (observedRefreshToken != null &&
+ (leasedRefreshToken.token !== observedRefreshToken.token ||
+ getCredentialSetId(leasedRefreshToken) !== getCredentialSetId(observedRefreshToken))) ||
+ (existingAccessToken != null &&
+ getCredentialSetId(leasedRefreshToken) !== getCredentialSetId(existingAccessToken));
+ if (!rotated && existingAccessToken !== null) {
+ return null;
+ }
+
+ const accessTokenData = await findToken({
+ userId,
+ type: 'mcp_oauth',
+ identifier: `mcp:${serverName}`,
+ });
+ if (
+ !rotated &&
+ (!accessTokenData || (accessTokenData.expiresAt && new Date() >= accessTokenData.expiresAt))
+ ) {
+ return null;
+ }
+ if (
+ !accessTokenData ||
+ getCredentialSetId(accessTokenData) !== getCredentialSetId(leasedRefreshToken)
+ ) {
+ throw new MCPTokenRefreshUnavailableError(
+ serverName,
+ new Error('Peer credential is not coherent'),
+ );
+ }
+ if (accessTokenData.expiresAt && new Date() >= accessTokenData.expiresAt) {
+ throw new MCPTokenRefreshUnavailableError(
+ serverName,
+ new Error('Peer credential already expired'),
+ );
+ }
+ return await this.readStoredTokens({ userId, serverName, findToken, accessTokenData });
+ }
+
/**
* Wraps the shared redemption promise for a single waiter: if the waiter's
* `signal` aborts first, that waiter receives `null` (matching the prior
@@ -1001,6 +1512,7 @@ export class MCPTokenStorage {
deleteTokens,
refreshTokens,
existingAccessToken,
+ leasedRefreshToken,
onRefreshSuccess,
onRefreshPreparing,
signal,
@@ -1009,6 +1521,12 @@ export class MCPTokenStorage {
leaseGeneration,
}: GetTokensParams & {
existingAccessToken?: IToken | null;
+ /**
+ * The refresh record already read under the flight this redemption holds. Reused rather than
+ * re-read, because a read taken under the flight is exactly what this redemption needs. Never
+ * `existingRefreshToken`, which predates the flight and may name a consumed credential.
+ */
+ leasedRefreshToken?: IToken | null;
refreshTokens: NonNullable<GetTokensParams['refreshTokens']>;
createToken: NonNullable<GetTokensParams['createToken']>;
/** Internal stale-abort signal owned by `forceRefreshTokens` — never a caller's. */
@@ -1019,11 +1537,13 @@ export class MCPTokenStorage {
const logPrefix = this.getLogPrefix(userId, serverName);
const identifier = `mcp:${serverName}`;
- const refreshTokenData = await findToken({
- userId,
- type: 'mcp_oauth_refresh',
- identifier: `${identifier}:refresh`,
- });
+ const refreshTokenData =
+ leasedRefreshToken ??
+ (await findToken({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ }));
if (!refreshTokenData) {
logger.debug(`${logPrefix} No refresh token in storage`);
@@ -1076,8 +1596,8 @@ export class MCPTokenStorage {
}
}
}
- } catch {
- logger.debug(`${logPrefix} No client info found`);
+ } catch (error) {
+ throw new MCPTokenStorageUnavailableError(serverName, error);
}
if (
@@ -1090,6 +1610,15 @@ export class MCPTokenStorage {
throw new ReauthenticationRequiredError(serverName, 'binding');
}
this.assertCredentialSetBinding(serverName, refreshCredentialSetId, storedClientMetadata);
+ if (
+ existingAccessToken &&
+ getCredentialSetId(existingAccessToken) !== refreshCredentialSetId
+ ) {
+ throw new MCPTokenRefreshUnavailableError(
+ serverName,
+ new Error('OAuth credential changed before redemption'),
+ );
+ }
const decryptedRefreshToken = await decryptV2(refreshTokenData.token);
const metadata = {
@@ -1113,7 +1642,22 @@ export class MCPTokenStorage {
throw new Error('Token refresh aborted before reaching the token endpoint');
}
- const newTokens = await refreshTokens(decryptedRefreshToken, metadata, signal);
+ let newTokens: MCPOAuthTokens;
+ try {
+ newTokens = await refreshTokens(decryptedRefreshToken, metadata, signal);
+ } catch (error) {
+ // These endpoint responses reject the refresh request permanently; a new grant can recover.
+ // Classify only provider failures here, never a similarly worded persistence failure.
+ const message = error instanceof Error ? error.message : String(error);
+ if (
+ /\b(unsupported_grant_type|invalid_request|invalid_scope|invalid_target|access_denied)\b/i.test(
+ message,
+ )
+ ) {
+ return null;
+ }
+ throw error;
+ }
logger.debug(`${logPrefix} Refresh completed`, {
has_new_access_token: !!newTokens.access_token,
@@ -1142,7 +1686,7 @@ export class MCPTokenStorage {
let storedTokens: MCPOAuthTokens;
try {
let preparedRefreshCommit: ((tokens?: MCPOAuthTokens) => Promise<void>) | undefined;
- storedTokens = await this.storeTokens({
+ storedTokens = await this.storeTokensUnderLease({
userId,
serverName,
tokens: newTokens,
@@ -1261,9 +1805,13 @@ export class MCPTokenStorage {
deleteTokens,
refreshTokens,
singleFlightScope,
+ refreshWaitTimeoutMs,
+ coordinateRefresh,
+ persistenceWaitTimeoutMs,
flowManager,
onRefreshSuccess,
onRefreshPreparing,
+ onTokensAdopted,
}: GetTokensParams): Promise<MCPOAuthTokens | null> {
const logPrefix = this.getLogPrefix(userId, serverName);
@@ -1285,10 +1833,10 @@ export class MCPTokenStorage {
logger.info(`${logPrefix} Access token ${isMissing ? 'missing' : 'expired'}`);
/** Probe for a refresh token first so we can throw `ReauthenticationRequiredError`
- * when none exists, matching the prior contract. The probe result is
- * intentionally not passed to `forceRefreshTokens` — the redemption
- * re-reads storage under its single-flight lock so it never replays a
- * refresh token that a concurrent refresh already consumed. */
+ * when none exists, matching the prior contract. The probe result is passed on as the
+ * cross-replica flight's observation baseline, which saves a read on this latency-counted
+ * path, and never as the credential to redeem — the redemption reads storage again under
+ * the flight, so it cannot replay a refresh token a concurrent refresh already consumed. */
const refreshTokenData = await findToken({
userId,
type: 'mcp_oauth_refresh',
@@ -1312,10 +1860,15 @@ export class MCPTokenStorage {
deleteTokens,
refreshTokens,
singleFlightScope,
+ refreshWaitTimeoutMs,
+ coordinateRefresh,
+ persistenceWaitTimeoutMs,
flowManager,
onRefreshSuccess,
onRefreshPreparing,
+ onTokensAdopted,
existingAccessToken: accessTokenData,
+ existingRefreshToken: refreshTokenData,
});
}
@@ -1324,44 +1877,12 @@ export class MCPTokenStorage {
return null;
}
- const credentialSetId = getCredentialSetId(accessTokenData);
- if (!credentialSetId) {
- throw new ReauthenticationRequiredError(serverName, 'binding');
- }
-
- const decryptedAccessToken = await decryptV2(accessTokenData.token);
-
- /** Get refresh token if available */
- const refreshTokenData = await findToken({
- userId,
- type: 'mcp_oauth_refresh',
- identifier: `${identifier}:refresh`,
- });
-
- const clientInfoData = await findToken({
+ const tokens = await this.readStoredTokens({
userId,
- type: 'mcp_oauth_client',
- identifier: `${identifier}:client`,
- });
- this.assertCredentialSetBinding(
serverName,
- credentialSetId,
- getTokenMetadata(clientInfoData),
- );
-
- const tokens: MCPOAuthTokens = {
- access_token: decryptedAccessToken,
- token_type: 'Bearer',
- credential_set_id: credentialSetId,
- obtained_at: accessTokenData.createdAt.getTime(),
- expires_at: accessTokenData.expiresAt?.getTime(),
- };
-
- if (refreshTokenData && getCredentialSetId(refreshTokenData) === credentialSetId) {
- tokens.refresh_token = await decryptV2(refreshTokenData.token);
- } else if (refreshTokenData) {
- logger.warn(`${logPrefix} Ignoring refresh token from a different OAuth credential set`);
- }
+ findToken,
+ accessTokenData,
+ });
logger.debug(`${logPrefix} Loaded existing OAuth tokens from storage`);
return tokens;
@@ -1377,6 +1898,66 @@ export class MCPTokenStorage {
}
}
+ /**
+ * Rebuilds the token pair from storage around an access-token record the caller already
+ * read. Expiry is the caller's business: `getTokens` checks it before reading, and the
+ * adoption path checks it against the record a peer just wrote.
+ *
+ * Throws `ReauthenticationRequiredError('binding')` when the access record carries no
+ * credential set or its client metadata no longer agrees with it.
+ */
+ private static async readStoredTokens({
+ userId,
+ serverName,
+ findToken,
+ accessTokenData,
+ }: {
+ userId: string;
+ serverName: string;
+ findToken: GetTokensParams['findToken'];
+ accessTokenData: IToken;
+ }): Promise<MCPOAuthTokens> {
+ const logPrefix = this.getLogPrefix(userId, serverName);
+ const identifier = `mcp:${serverName}`;
+
+ const credentialSetId = getCredentialSetId(accessTokenData);
+ if (!credentialSetId) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+
+ const decryptedAccessToken = await decryptV2(accessTokenData.token);
+
+ /** Get refresh token if available */
+ const refreshTokenData = await findToken({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ });
+
+ const clientInfoData = await findToken({
+ userId,
+ type: 'mcp_oauth_client',
+ identifier: `${identifier}:client`,
+ });
+ this.assertCredentialSetBinding(serverName, credentialSetId, getTokenMetadata(clientInfoData));
+
+ const tokens: MCPOAuthTokens = {
+ access_token: decryptedAccessToken,
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ obtained_at: accessTokenData.createdAt.getTime(),
+ expires_at: accessTokenData.expiresAt?.getTime(),
+ };
+
+ if (refreshTokenData && getCredentialSetId(refreshTokenData) === credentialSetId) {
+ tokens.refresh_token = await decryptV2(refreshTokenData.token);
+ } else if (refreshTokenData) {
+ logger.warn(`${logPrefix} Ignoring refresh token from a different OAuth credential set`);
+ }
+
+ return tokens;
+ }
+
static async getClientInfoAndMetadata({
userId,
serverName,
diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.ts
index c16ac7c1c4..57f2c1764c 100644
--- a/packages/api/src/mcp/oauth/types.ts
+++ b/packages/api/src/mcp/oauth/types.ts
@@ -99,6 +99,8 @@ export interface MCPOAuthFlowMetadata extends FlowMetadata {
serverUrl: string;
/** Identity of the effective server definition that admitted this authorization attempt. */
serverGeneration?: string;
+ /** Persistence wait admitted with the server configuration; preserved across the OAuth redirect. */
+ oauthPersistenceWaitTimeout?: number;
state: string;
codeVerifier?: string;
clientInfo?: OAuthClientInformation;
diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.ts
index ddd6c0d80e..a8e51c3014 100644
--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts
+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts
@@ -122,6 +122,9 @@ const ADMIN_CONFIGURABLE_FIELDS = [
'customUserVars',
'timeout',
'sseReadTimeout',
+ 'oauthRefreshWaitTimeout',
+ 'oauthRefreshCoordination',
+ 'oauthPersistenceWaitTimeout',
'initTimeout',
] as const;
diff --git a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts
index 3192792cd2..6b6f153080 100644
--- a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts
@@ -1448,6 +1448,20 @@ describe('MCPServersRegistry', () => {
expect(result['langfuse-docs'].source).toBe('yaml');
});
+ it.each([
+ ['oauthRefreshWaitTimeout', 25000],
+ ['oauthPersistenceWaitTimeout', 60000],
+ ['oauthRefreshCoordination', true],
+ ] as const)('retains an admin-only %s override', async (field, value) => {
+ await registry['cacheConfigsRepo'].add('langfuse-docs', yamlLangfuseConfig);
+ const configServers = await registry.ensureConfigServers({
+ 'langfuse-docs': { ...yamlLangfuseConfig, [field]: value },
+ });
+ expect(configServers['langfuse-docs'][field]).toBe(value);
+ const result = await registry.getAllServerConfigs('user-1', configServers);
+ expect(result['langfuse-docs'][field]).toBe(value);
+ });
+
it('preserves user-DB tier (source: "user") over config-tier overrides', async () => {
const userDbEntry: t.ParsedServerConfig = {
type: 'streamable-http',
diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.ts
index ee6d02767e..c029753f00 100644
--- a/packages/api/src/mcp/types/index.ts
+++ b/packages/api/src/mcp/types/index.ts
@@ -297,7 +297,7 @@ export interface UserConnectionContext {
* invalidated its cached token flow. A caller leasing a generation captured earlier re-captures
* it here, ahead of the read, so a rotation that follows the read still fences the build.
*/
- onOAuthCredentialsInvalidated?: () => Promise<void>;
+ onOAuthCredentialsInvalidated?: () => Promise<string | void>;
}
export interface RequestScopedMCPConnectionStore {
@@ -363,6 +363,8 @@ export interface ToolDiscoveryOptions {
deadlineMs?: number;
onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>;
onOAuthCredentialsChanging?: UserConnectionContext['onOAuthCredentialsChanging'];
+ /** Updates the discovery flight when it adopts credentials published by a peer. */
+ onOAuthCredentialsAdopted?: (generation: string) => Promise<void>;
onDiscoveryDetached?: UserConnectionContext['onDiscoveryDetached'];
/** Pre-resolved config-source servers for tenant-scoped lookup */
configServers?: Record<string, ParsedServerConfig>;
diff --git a/packages/data-provider/specs/mcp.spec.ts b/packages/data-provider/specs/mcp.spec.ts
index 10a73e3ad1..d80b59048c 100644
--- a/packages/data-provider/specs/mcp.spec.ts
+++ b/packages/data-provider/specs/mcp.spec.ts
@@ -890,3 +890,35 @@ describe('MCP_USER_INPUT_FIELDS', () => {
expect(MCP_USER_INPUT_FIELDS.has('env')).toBe(false);
});
});
+
+describe('OAuth coordination rollout configuration', () => {
+ const server = { type: 'sse', url: 'https://mcp.example.com' };
+ it('leaves coordination disabled unless explicitly enabled', () => {
+ expect(MCPOptionsSchema.parse(server).oauthRefreshCoordination).not.toBe(true);
+ expect(
+ MCPOptionsSchema.parse({ ...server, oauthRefreshCoordination: true })
+ .oauthRefreshCoordination,
+ ).toBe(true);
+ });
+ it.each([0, -1, 1.5, 840001])(
+ 'rejects an invalid persistence wait %s',
+ (oauthPersistenceWaitTimeout) => {
+ expect(MCPOptionsSchema.safeParse({ ...server, oauthPersistenceWaitTimeout }).success).toBe(
+ false,
+ );
+ },
+ );
+ it('accepts a longer publication wait and keeps coordination admin-managed', () => {
+ expect(
+ MCPOptionsSchema.parse({ ...server, oauthPersistenceWaitTimeout: 90000 })
+ .oauthPersistenceWaitTimeout,
+ ).toBe(90000);
+ const user = MCPServerUserInputSchema.parse({
+ ...server,
+ oauthRefreshCoordination: true,
+ oauthPersistenceWaitTimeout: 90000,
+ });
+ expect(user).not.toHaveProperty('oauthRefreshCoordination');
+ expect(user).not.toHaveProperty('oauthPersistenceWaitTimeout');
+ });
+});
diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.ts
index c37f9b3cea..9742b9fdfb 100644
--- a/packages/data-provider/src/mcp.ts
+++ b/packages/data-provider/src/mcp.ts
@@ -9,6 +9,9 @@ import { extractEnvVariable } from './utils';
*/
export const MAX_MCP_ICON_PATH_LENGTH = 256 * 1024;
+/** Keep persistence admission waits below the shared lease's 15-minute lifetime. */
+export const MAX_MCP_OAUTH_PERSISTENCE_WAIT_MS = 14 * 60_000;
+
const validateOAuthClientCredentials = (
oauth: {
client_id?: string;
@@ -208,6 +211,26 @@ const BaseOptionsSchema = z.object({
/** Timeout (ms) for the long-lived SSE GET stream body before undici aborts it. Default: 300_000 (5 min). */
sseReadTimeout: z.number().int().positive().optional(),
initTimeout: z.number().int().nonnegative().optional(),
+ /**
+ * How long (ms) a replica waits for another replica's in-flight OAuth refresh-token redemption
+ * before failing the attempt as retryable. Raise it for a slow token endpoint; lower it to fail
+ * faster. Default when unset: 15_000. Clamped to 30_000, half the window after which a
+ * redemption aborts itself, because this wait runs inside the redemption that window governs.
+ *
+ * Positive rather than non-negative: zero would mean "never wait for a peer", which fails every
+ * contended refresh instead of adopting the rotation a peer is about to store, and that is the
+ * common case this wait exists to serve. Omit the field to take the default.
+ */
+ oauthRefreshWaitTimeout: z.number().int().positive().optional(),
+ /** Enable only after every replica has upgraded to the coordinated OAuth writer protocol. Default: false. */
+ oauthRefreshCoordination: z.boolean().optional(),
+ /** Wait (ms) for callback/adoption persistence and publication. Default: 15_000; maximum: 840_000. */
+ oauthPersistenceWaitTimeout: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_MCP_OAUTH_PERSISTENCE_WAIT_MS)
+ .optional(),
/**
* Whether the server is offered in chat.
*
@@ -471,6 +494,9 @@ const omitServerManagedFields = <T extends z.ZodObject<z.ZodRawShape>>(schema: T
timeout: true,
sseReadTimeout: true,
initTimeout: true,
+ oauthRefreshWaitTimeout: true,
+ oauthRefreshCoordination: true,
+ oauthPersistenceWaitTimeout: true,
chatMenu: true,
serverInstructions: true,
requiresOAuth: true,