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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🛬 fix: Land MCP OAuth Callbacks on Waiting Connections (#15876)
Danny Avila3f2e4777cb06
diff --git a/api/config/index.js b/api/config/index.jsindex 79a1c24663..2e3ed6e018 100644--- a/api/config/index.js+++ b/api/config/index.js@@ -44,6 +44,7 @@ function getActionFlowStateManager(flowsCache) {if (!actionFlowManager) {actionFlowManager = new FlowStateManager(flowsCache, {ttl: Time.ONE_MINUTE * 3,+ redisScriptExecutor: evalKeyvRedisScript,});}return actionFlowManager;diff --git a/api/db/indexSync.js b/api/db/indexSync.jsindex 85a5524a76..ad187de111 100644--- a/api/db/indexSync.js+++ b/api/db/indexSync.js@@ -2,7 +2,7 @@ const mongoose = require('mongoose');const { MeiliSearch } = require('meilisearch');const { logger } = require('@librechat/data-schemas');const { CacheKeys } = require('librechat-data-provider');-const { isEnabled, FlowStateManager } = require('@librechat/api');+const { isEnabled, FlowStateManager, evalKeyvRedisScript } = require('@librechat/api');const { getLogStores } = require('~/cache');const { batchResetMeiliFlags } = require('./utils');@@ -372,6 +372,7 @@ async function indexSync() {const flowManager = new FlowStateManager(flowsCache, {ttl: 60000 * 10, // 10 minutes TTL for sync operations+ redisScriptExecutor: evalKeyvRedisScript,});// Use a unique flow ID for the sync operationdiff --git a/packages/api/src/flow/manager.test.ts b/packages/api/src/flow/manager.test.tsindex 04c2aacad4..8f90b1b5b1 100644--- a/packages/api/src/flow/manager.test.ts+++ b/packages/api/src/flow/manager.test.ts@@ -1,5 +1,5 @@import { Keyv } from 'keyv';-import { FlowStateManager, PENDING_STALE_MS } from './manager';+import { FlowStateManager, FlowStateNotFoundError, PENDING_STALE_MS } from './manager';import { FlowState } from './types';jest.mock('@librechat/data-schemas', () => ({@@ -571,6 +571,142 @@ describe('FlowStateManager', () => {});});+ it('serves a completed result without waiting on the monitor interval', async () => {+ const completedResult: TokenResult = {+ access_token: 'cached_token',+ refresh_token: 'refresh_token',+ expires_at: Date.now() + 3600000,+ };+ await tokenStore.set(flowKey, {+ type,+ status: 'COMPLETED',+ metadata: {},+ createdAt: Date.now() - 5000,+ completedAt: Date.now() - 4000,+ result: completedResult,+ } as FlowState<TokenResult>);+ const handlerSpy = jest.fn();++ const startedAt = Date.now();+ await expect(+ tokenFlowManager.createFlowWithHandler(flowId, type, handlerSpy),+ ).resolves.toEqual(completedResult);++ expect(Date.now() - startedAt).toBeLessThan(1000);+ expect(handlerSpy).not.toHaveBeenCalled();+ });++ it('replaces a failure nobody retains instead of waiting on it', async () => {+ await tokenStore.set(flowKey, {+ type,+ status: 'FAILED',+ metadata: {},+ createdAt: Date.now() - 5000,+ failedAt: Date.now() - 4000,+ error: 'earlier attempt failed',+ } as FlowState<TokenResult>);+ const freshResult: TokenResult = { access_token: 'fresh_token', refresh_token: 'refresh' };+ const handlerSpy = jest.fn().mockResolvedValue(freshResult);++ await expect(+ tokenFlowManager.createFlowWithHandler(flowId, type, handlerSpy),+ ).resolves.toEqual(freshResult);++ expect(handlerSpy).toHaveBeenCalledTimes(1);+ await expect(tokenFlowManager.getFlowState(flowId, type)).resolves.toEqual(+ expect.objectContaining({ status: 'COMPLETED', result: freshResult }),+ );+ });++ it('still reports a retained failure to a later attempt', async () => {+ const retainingManager = new FlowStateManager<TokenResult>(tokenStore as unknown as Keyv, {+ ttl: 30000,+ retainedFailureTypes: [type],+ ci: true,+ });+ await tokenStore.set(flowKey, {+ type,+ status: 'FAILED',+ metadata: {},+ createdAt: Date.now() - 5000,+ failedAt: Date.now() - 4000,+ error: 'earlier attempt failed',+ } as FlowState<TokenResult>);+ const handlerSpy = jest.fn();++ await expect(+ retainingManager.createFlowWithHandler(flowId, type, handlerSpy),+ ).rejects.toThrow('earlier attempt failed');++ expect(handlerSpy).not.toHaveBeenCalled();+ }, 15000);++ it('rejects with FlowStateNotFoundError when the pending flow it joined disappears', async () => {+ await tokenStore.set(flowKey, {+ type,+ status: 'PENDING',+ metadata: {},+ createdAt: Date.now(),+ } as FlowState<TokenResult>);+ const handlerSpy = jest.fn();++ const joined = tokenFlowManager.createFlowWithHandler(flowId, type, handlerSpy);+ await new Promise((resolve) => setTimeout(resolve, 300));+ await tokenFlowManager.deleteFlow(flowId, type);++ await expect(joined).rejects.toBeInstanceOf(FlowStateNotFoundError);+ await expect(joined).rejects.toThrow('mcp_get_tokens Flow state not found');+ expect(handlerSpy).not.toHaveBeenCalled();+ }, 15000);++ it('rejects instead of serving a completed result to an aborted caller', async () => {+ await tokenStore.set(flowKey, {+ type,+ status: 'COMPLETED',+ metadata: {},+ createdAt: Date.now() - 5000,+ completedAt: Date.now() - 4000,+ result: { access_token: 'cached_token', refresh_token: 'refresh' },+ } as FlowState<TokenResult>);+ const handlerSpy = jest.fn();+ const controller = new AbortController();+ controller.abort();++ await expect(+ tokenFlowManager.createFlowWithHandler(flowId, type, handlerSpy, controller.signal),+ ).rejects.toThrow('mcp_get_tokens flow aborted');++ expect(handlerSpy).not.toHaveBeenCalled();+ });++ it('leaves the shared flow in place when a joiner aborts', async () => {+ await tokenStore.set(flowKey, {+ type,+ status: 'PENDING',+ metadata: {},+ createdAt: Date.now(),+ } as FlowState<TokenResult>);+ const controller = new AbortController();+ const joiner = tokenFlowManager.createFlowWithHandler(+ flowId,+ type,+ jest.fn(),+ controller.signal,+ );+ await new Promise((resolve) => setTimeout(resolve, 50));+ controller.abort();++ await expect(joiner).rejects.toThrow('mcp_get_tokens flow aborted');+ await expect(tokenFlowManager.getFlowState(flowId, type)).resolves.toEqual(+ expect.objectContaining({ status: 'PENDING' }),+ );++ const settled: TokenResult = { access_token: 'settled_token', refresh_token: 'refresh' };+ const otherWaiter = tokenFlowManager.createFlowWithHandler(flowId, type, jest.fn());+ await tokenFlowManager.completeFlow(flowId, type, settled);+ await expect(otherWaiter).resolves.toEqual(settled);+ }, 15000);+it('should execute handler when existing flow has expired token', async () => {const expiredTokenResult: TokenResult = {access_token: 'expired_token',@@ -1135,6 +1271,65 @@ describe('FlowStateManager', () => {});});+ describe('createFlowWithHandler - atomic attempt claims', () => {+ const type = 'mcp_get_tokens';+ let claimingManager: FlowStateManager<string>;++ beforeEach(() => {+ const keyv = new Keyv({+ namespace: `flow-claim-${Date.now()}`,+ serialize: JSON.stringify,+ deserialize: JSON.parse,+ });+ claimingManager = new FlowStateManager<string>(keyv, { ttl: 30000, ci: true });+ });++ const slowHandler = (result: string) =>+ jest.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 100));+ return result;+ });++ it('runs one handler when concurrent attempts replace a failure from the same millisecond', async () => {+ const flowId = 'claimed-after-failure';+ /** A replacement created in the same millisecond as the failure shares its `createdAt`. */+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000);+ try {+ await expect(+ claimingManager.createFlowWithHandler(flowId, type, async () => {+ throw new Error('earlier attempt failed');+ }),+ ).rejects.toThrow('earlier attempt failed');+ const first = slowHandler('first');+ const second = slowHandler('second');++ const results = await Promise.all([+ claimingManager.createFlowWithHandler(flowId, type, first),+ claimingManager.createFlowWithHandler(flowId, type, second),+ ]);++ expect(new Set(results).size).toBe(1);+ expect(first.mock.calls.length + second.mock.calls.length).toBe(1);+ } finally {+ nowSpy.mockRestore();+ }+ }, 15000);++ it('runs one handler when concurrent attempts create the same absent flow', async () => {+ const flowId = 'claimed-when-absent';+ const first = slowHandler('first');+ const second = slowHandler('second');++ const results = await Promise.all([+ claimingManager.createFlowWithHandler(flowId, type, first),+ claimingManager.createFlowWithHandler(flowId, type, second),+ ]);++ expect(new Set(results).size).toBe(1);+ expect(first.mock.calls.length + second.mock.calls.length).toBe(1);+ }, 15000);+ });+describe('isFlowStale', () => {const flowId = 'test-flow-stale';const type = 'test-type';diff --git a/packages/api/src/flow/manager.ts b/packages/api/src/flow/manager.tsindex 6abfa24eaf..50cc2a7638 100644--- a/packages/api/src/flow/manager.ts+++ b/packages/api/src/flow/manager.ts@@ -13,6 +13,14 @@ export interface FlowLease {release: () => Promise<void>;}+/** The flow a waiter was monitoring disappeared before it settled. */+export class FlowStateNotFoundError extends Error {+ constructor(type: string) {+ super(`${type} Flow state not found`);+ this.name = 'FlowStateNotFoundError';+ }+}+interface InMemoryLeaseState {generation: number;owner?: string;@@ -94,6 +102,24 @@ redis.call('SET', KEYS[1], cjson.encode(data), 'PX', ARGV[5])return 1`;+/** Installs a new attempt only while the key is absent or still holds the attempt the caller+ * observed and decided to replace, so concurrent replacements run a single handler. The status+ * is part of the match because a replacement created in the same millisecond as the failure it+ * replaces shares its `createdAt`. */+const CLAIM_FLOW = `+local raw = redis.call('GET', KEYS[1])+if raw then+ if ARGV[3] == '' then return 0 end+ local flow = cjson.decode(raw).value+ if flow.createdAt ~= tonumber(ARGV[3]) then return 0 end+ local state = flow.metadata and flow.metadata.state or ''+ if state ~= ARGV[4] then return 0 end+ if flow.status ~= ARGV[5] then return 0 end+end+redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])+return 1+`;+const READ_LEASE_GENERATION = `local raw = redis.call('GET', KEYS[1])if not raw then return 0 end@@ -669,7 +695,16 @@ export class FlowStateManager<T = unknown> {return this.monitorFlow(flowKey, type, signal);}- private monitorFlow(flowKey: string, type: string, signal?: AbortSignal): Promise<T> {+ /**+ * Waits for the flow to settle. An owner that aborts takes its flow down with it; a joiner that+ * aborts leaves the flow to the attempt that owns it and to the other waiters.+ */+ private monitorFlow(+ flowKey: string,+ type: string,+ signal?: AbortSignal,+ ownsFlow = true,+ ): Promise<T> {return new Promise<T>((resolve, reject) => {const checkInterval = 2000;let isCleanedUp = false;@@ -695,10 +730,12 @@ export class FlowStateManager<T = unknown> {cleanup();logger.warn(`[${flowKey}] Flow aborted (immediate)`);const message = `${type} flow aborted`;- try {- await this.keyv.delete(flowKey);- } catch {- // Ignore delete errors during abort+ if (ownsFlow) {+ try {+ await this.keyv.delete(flowKey);+ } catch {+ // Ignore delete errors during abort+ }}reject(new Error(message));};@@ -735,7 +772,7 @@ export class FlowStateManager<T = unknown> {if (!flowState) {cleanup();logger.error(`[${flowKey}] Flow state not found after retry`);- reject(new Error(`${type} Flow state not found`));+ reject(new FlowStateNotFoundError(type));return;}}@@ -744,7 +781,9 @@ export class FlowStateManager<T = unknown> {cleanup();logger.warn(`[${flowKey}] Flow aborted`);const message = `${type} flow aborted`;- await this.keyv.delete(flowKey);+ if (ownsFlow) {+ await this.keyv.delete(flowKey);+ }reject(new Error(message));return;}@@ -939,18 +978,20 @@ export class FlowStateManager<T = unknown> {signal?: AbortSignal,): Promise<T> {const flowKey = this.getFlowKey(flowId, type);- let existingState = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;- if (existingState && !this.isTokenExpired(existingState)) {- logger.debug(`[${flowKey}] Flow already exists with valid token`);- return this.monitorFlow(flowKey, type, signal);+ let observed = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;+ let joined = this.joinExistingFlow(flowKey, type, observed, signal);+ if (joined) {+ return joined;}- await new Promise((resolve) => setTimeout(resolve, 250));+ if (!this.claimsAtomically(flowKey)) {+ await new Promise((resolve) => setTimeout(resolve, 250));- existingState = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;- if (existingState && !this.isTokenExpired(existingState)) {- logger.debug(`[${flowKey}] Flow exists on 2nd check with valid token`);- return this.monitorFlow(flowKey, type, signal);+ observed = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;+ joined = this.joinExistingFlow(flowKey, type, observed, signal);+ if (joined) {+ return joined;+ }}const initialState: FlowState = {@@ -959,8 +1000,11 @@ export class FlowStateManager<T = unknown> {metadata: {},createdAt: Date.now(),};+ if (!(await this.claimFlow(flowKey, initialState, observed))) {+ logger.debug(`[${flowKey}] Flow was claimed by a concurrent attempt; joining it`);+ return this.createFlowWithHandler(flowId, type, handler, signal);+ }logger.debug(`[${flowKey}] Creating initial flow state`);- await this.keyv.set(flowKey, initialState, this.ttl);try {const result = await handler();@@ -990,6 +1034,93 @@ export class FlowStateManager<T = unknown> {}}+ /**+ * A completed result is served as it stands and a pending attempt is monitored, as is a failure+ * of a retained type. A failure of any other type only lingers because its own attempt already+ * returned it, so the next attempt replaces it instead of waiting on it.+ */+ private joinExistingFlow(+ flowKey: string,+ type: string,+ existingState: FlowState<T> | undefined,+ signal?: AbortSignal,+ ): Promise<T> | undefined {+ if (!existingState || this.isTokenExpired(existingState)) {+ return undefined;+ }+ if (existingState.status === 'FAILED' && !this.retainedFailureTypes.has(type)) {+ return undefined;+ }+ if (signal?.aborted) {+ return Promise.reject(new Error(`${type} flow aborted`));+ }+ if (existingState.status === 'COMPLETED') {+ logger.debug(`[${flowKey}] Serving completed flow result`);+ return Promise.resolve(existingState.result as T);+ }+ logger.debug(`[${flowKey}] Flow already exists with valid token`);+ return this.monitorFlow(flowKey, type, signal, false);+ }++ /** Redis and the default in-memory store install an attempt atomically; other stores cannot. */+ private claimsAtomically(flowKey: string): boolean {+ return (+ this.getRedisKey(flowKey) != null ||+ (this.keyv instanceof Keyv && this.keyv.store instanceof Map)+ );+ }++ /**+ * Installs `initialState` only while the key is absent or still holds `observed`, the attempt+ * the caller read and decided to replace. A store without an atomic primitive installs it+ * unconditionally, as before.+ */+ private async claimFlow(+ flowKey: string,+ initialState: FlowState,+ observed: FlowState<T> | undefined,+ ): Promise<boolean> {+ const observedState =+ typeof observed?.metadata?.state === 'string' ? observed.metadata.state : '';+ const envelope = JSON.stringify({+ value: initialState,+ expires: initialState.createdAt + this.ttl,+ });+ const redisKey = this.getRedisKey(flowKey);+ if (redisKey) {+ const claimed = await this.evalRedisScript(CLAIM_FLOW, redisKey, [+ envelope,+ String(this.ttl),+ observed ? String(observed.createdAt) : '',+ observedState,+ observed?.status ?? '',+ ]);+ return Number(claimed) === 1;+ }++ if (this.keyv instanceof Keyv && this.keyv.store instanceof Map) {+ const current = this.getInMemoryEntry(flowKey);+ if (+ current &&+ (!observed ||+ current.envelope.value.status !== observed.status ||+ !FlowStateManager.isCurrentAttempt(+ current.envelope.value,+ observed.createdAt,+ observedState,+ ))+ ) {+ return false;+ }+ const key = this.keyv.namespace ? `${this.keyv.namespace}:${flowKey}` : flowKey;+ this.keyv.store.set(key, envelope);+ return true;+ }++ await this.keyv.set(flowKey, initialState, this.ttl);+ return true;+ }+/*** Deletes a flow state*/diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 81d7f7617b..95fcb8ec05 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -42,7 +42,7 @@ import {isClientRejectionMessage,createDeadlineAbortSignal,} from './utils';-import { PENDING_STALE_MS, normalizeExpiresAt } from '~/flow/manager';+import { PENDING_STALE_MS, FlowStateNotFoundError, normalizeExpiresAt } from '~/flow/manager';import { preProcessGraphTokens } from '~/utils/graph';import { MCPConnection } from './connection';import { processMCPEnv } from '~/utils';@@ -98,6 +98,8 @@ export class MCPConnectionFactory {protected readonly onOAuthCredentialsChanged?: t.UserConnectionContext['onOAuthCredentialsChanged'];protected readonly onOAuthCredentialsChanging?: t.UserConnectionContext['onOAuthCredentialsChanging'];protected readonly onDiscoveryDetached?: t.UserConnectionContext['onDiscoveryDetached'];+ protected readonly onOAuthCredentialsAdopted?: t.UserConnectionContext['onOAuthCredentialsAdopted'];+ protected readonly onOAuthCredentialsInvalidated?: t.UserConnectionContext['onOAuthCredentialsInvalidated'];protected readonly oboTokenResolver?: OboTokenResolver;protected readonly oboTrustChecker?: OboTrustChecker;protected upstreamTokenProvider?: UpstreamTokenProvider;@@ -601,6 +603,8 @@ export class MCPConnectionFactory {this.onOAuthCredentialsChanged = options?.onOAuthCredentialsChanged;this.onOAuthCredentialsChanging = options?.onOAuthCredentialsChanging;this.onDiscoveryDetached = options?.onDiscoveryDetached;+ this.onOAuthCredentialsAdopted = options?.onOAuthCredentialsAdopted;+ this.onOAuthCredentialsInvalidated = options?.onOAuthCredentialsInvalidated;this.signal = options?.signal;this.tenantContext = tenantStorage?.getStore?.();this.tenantId = this.tenantContext?.tenantId ?? getTenantId();@@ -896,13 +900,15 @@ export class MCPConnectionFactory {.digest('base64url');}- /** Retrieves existing OAuth tokens from storage or returns null */- protected async getOAuthTokens(): Promise<MCPOAuthTokens | null> {- if (!this.tokenMethods?.findToken) return null;-- try {- const flowId = this.getTokenFlowId();- const tokens = await this.flowManager!.createFlowWithHandler(+ /**+ * Reads tokens through the shared `mcp_get_tokens` flow. A flow that disappears while this call+ * waits on it was invalidated by a credential change, so the read runs once more against the+ * changed storage instead of reporting the tokens missing and prompting for authorization again.+ */+ private async loadOAuthTokens(): Promise<MCPOAuthTokens | null> {+ const flowId = this.getTokenFlowId();+ const readTokens = () =>+ this.flowManager!.createFlowWithHandler(flowId,'mcp_get_tokens',async () => {@@ -925,6 +931,35 @@ export class MCPConnectionFactory {this.signal,);+ try {+ return await readTokens();+ } catch (error) {+ if (!(error instanceof FlowStateNotFoundError)) {+ throw error;+ }+ logger.info(+ `${this.logPrefix} Token flow was invalidated while waiting on it; re-reading stored tokens`,+ );+ await this.onOAuthCredentialsInvalidated?.();+ return await readTokens();+ }+ }++ /** Tokens released by another party's authorization or refresh carry the generation it published. */+ private async adoptPublishedCredentials(tokens: MCPOAuthTokens): Promise<void> {+ if (!tokens.publication_generation) {+ return;+ }+ await this.onOAuthCredentialsAdopted?.(tokens.publication_generation);+ }++ /** Retrieves existing OAuth tokens from storage or returns null */+ protected async getOAuthTokens(): Promise<MCPOAuthTokens | null> {+ if (!this.tokenMethods?.findToken) return null;++ try {+ const tokens = await this.loadOAuthTokens();+if (tokens) {const [isCurrentAccessToken, storedClient] = await this.runWithCapturedTenant(() =>Promise.all([@@ -957,6 +992,7 @@ export class MCPConnectionFactory {storedClient?.clientMetadata as Partial<OAuthStoredClientMetadata> | undefined,this.serverConfig.oauth,);+ await this.adoptPublishedCredentials(tokens);logger.info(`${this.logPrefix} Loaded OAuth tokens`);}return tokens;@@ -1171,8 +1207,8 @@ export class MCPConnectionFactory {});return async (freshTokens) => {if (publishPreparedMutation != null) {- await publishPreparedMutation();- await this.invalidateGetTokensFlow(freshTokens);+ const publicationGeneration = await publishPreparedMutation();+ await this.invalidateGetTokensFlow(freshTokens, publicationGeneration);return;}if (freshTokens != null) {@@ -1189,7 +1225,10 @@ export class MCPConnectionFactory {};}- protected async invalidateGetTokensFlow(freshTokens?: MCPOAuthTokens): Promise<void> {+ protected async invalidateGetTokensFlow(+ freshTokens?: MCPOAuthTokens,+ publicationGeneration?: string,+ ): Promise<void> {if (!this.flowManager || !this.userId) {return;}@@ -1200,7 +1239,13 @@ export class MCPConnectionFactory {return;}if (state.status === 'PENDING' && freshTokens) {- await this.flowManager.completeFlow(flowId, 'mcp_get_tokens', freshTokens);+ await this.flowManager.completeFlow(+ flowId,+ 'mcp_get_tokens',+ publicationGeneration+ ? { ...freshTokens, publication_generation: publicationGeneration }+ : freshTokens,+ );return;}if (state.status !== 'COMPLETED') {@@ -1684,6 +1729,7 @@ export class MCPConnectionFactory {);connection.setOAuthTokens(tokens);+ await this.adoptPublishedCredentials(tokens);// Same rationale as the silent-refresh success path: invalidate the// `mcp_get_tokens` cache so the next `getOAuthTokens` reads the// freshly stored tokens rather than the just-rejected ones thediff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.tsindex 1fc14c4a16..d02c179bc5 100644--- a/packages/api/src/mcp/UserConnectionManager.ts+++ b/packages/api/src/mcp/UserConnectionManager.ts@@ -797,12 +797,15 @@ export abstract class UserConnectionManager {};/**- * A credential refresh performed while this connection is being built rotates the very- * generation captured above, so the build would otherwise fence itself: the connection- * holding the newest credentials publishes under a generation its own refresh retired.- * Recording what it published lets the fence keep pointing at foreign rotations only.+ * Credentials resolved after the capture above were published under a generation that+ * capture predates, so the build would otherwise fence itself: a refresh it performs, an+ * authorization it waits on, or a re-read after a change invalidated its token cache each+ * hand it the newest credentials, which it would then publish under a retired generation.+ * Recording the generation those credentials carry, while it is still the stored one, keeps+ * the fence pointing at rotations that follow them; a carried generation the store has+ * already retired proves nothing about the current one, so the capture stands for it.*/- let selfPublishedGeneration: string | undefined;+ let credentialGeneration: string | undefined;const trackPublishedGeneration: t.UserConnectionContext['onOAuthCredentialsChanging'] =onOAuthCredentialsChanging == null? undefined@@ -811,11 +814,25 @@ export abstract class UserConnectionManager {return async () => {const published = await publish();if (published) {- selfPublishedGeneration = published;+ credentialGeneration = published;}return published;};};+ const adoptCredentialGeneration: t.UserConnectionContext['onOAuthCredentialsAdopted'] =+ ephemeralConnection+ ? undefined+ : async (published) => {+ if ((await getMCPToolsChangedGeneration({ userId, serverName })) === published) {+ credentialGeneration = published;+ }+ };+ const recaptureCredentialGeneration: t.UserConnectionContext['onOAuthCredentialsInvalidated'] =+ ephemeralConnection+ ? undefined+ : async () => {+ credentialGeneration = await getMCPToolsChangedGeneration({ userId, serverName });+ };const useOAuth = usesDirectOpenIDBearerRecovery(config)? false@@ -848,6 +865,8 @@ export abstract class UserConnectionManager {connectionTimeout: connectionTimeout,onOAuthCredentialsChanged,onOAuthCredentialsChanging: trackPublishedGeneration,+ onOAuthCredentialsAdopted: adoptCredentialGeneration,+ onOAuthCredentialsInvalidated: recaptureCredentialGeneration,};} else {connectionOptions = {@@ -867,7 +886,7 @@ export abstract class UserConnectionManager {const effectiveGeneration = ephemeralConnection? undefined- : (selfPublishedGeneration ?? publicationGeneration);+ : (credentialGeneration ?? publicationGeneration);if (effectiveGeneration) {this.toolPublicationGenerations.set(connection, effectiveGeneration);diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.tsindex 56d595980b..2e888a7a65 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts@@ -9,10 +9,10 @@ import {OboTokenResolutionError,ReauthenticationRequiredError,} from '~/mcp/oauth';+import { PENDING_STALE_MS, FlowStateNotFoundError } from '~/flow/manager';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';import { MCPAuthenticationRejectedError } from '~/mcp/errors';import { preProcessGraphTokens } from '~/utils/graph';-import { PENDING_STALE_MS } from '~/flow/manager';import { MCPConnection } from '~/mcp/connection';import { processMCPEnv } from '~/utils';@@ -571,6 +571,104 @@ describe('MCPConnectionFactory', () => {expect(mockFlowManager.createFlowWithHandler).not.toHaveBeenCalled();});+ describe('token flow invalidated while waiting', () => {+ const tokenLoadingFactory = (+ hooks: Pick<+ t.UserConnectionContext,+ 'onOAuthCredentialsAdopted' | 'onOAuthCredentialsInvalidated'+ > = {},+ ) =>+ new InspectableMCPConnectionFactory(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ ...hooks,+ },+ );++ 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',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ credential_set_id: 'persisted-generation',+ };+ mockFlowManager.createFlowWithHandler+ .mockRejectedValueOnce(new FlowStateNotFoundError('mcp_get_tokens'))+ .mockResolvedValueOnce(storedTokens);+ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);+ const onOAuthCredentialsAdopted = jest.fn();++ await expect(+ tokenLoadingFactory({+ onOAuthCredentialsInvalidated,+ onOAuthCredentialsAdopted,+ }).getOAuthTokensForTest(),+ ).resolves.toEqual(storedTokens);++ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(2);+ expect(onOAuthCredentialsInvalidated).toHaveBeenCalledTimes(1);+ expect(onOAuthCredentialsInvalidated.mock.invocationCallOrder[0]).toBeLessThan(+ mockFlowManager.createFlowWithHandler.mock.invocationCallOrder[1],+ );+ expect(onOAuthCredentialsAdopted).not.toHaveBeenCalled();+ });++ it('reports the tokens missing when the re-read loses its flow as well', async () => {+ mockFlowManager.createFlowWithHandler.mockRejectedValue(+ new FlowStateNotFoundError('mcp_get_tokens'),+ );+ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);++ await expect(+ tokenLoadingFactory({ onOAuthCredentialsInvalidated }).getOAuthTokensForTest(),+ ).resolves.toBeNull();++ 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'),+ );+ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);++ await expect(+ tokenLoadingFactory({ onOAuthCredentialsInvalidated }).getOAuthTokensForTest(),+ ).resolves.toBeNull();++ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);+ expect(onOAuthCredentialsInvalidated).not.toHaveBeenCalled();+ });++ it('adopts the generation carried by tokens another authorization released', async () => {+ const releasedTokens: MCPOAuthTokens = {+ access_token: 'released-by-callback',+ token_type: 'Bearer',+ obtained_at: 1_700_000_000_000,+ credential_set_id: 'persisted-generation',+ publication_generation: 'generation-b',+ };+ mockFlowManager.createFlowWithHandler.mockResolvedValue(releasedTokens);+ const onOAuthCredentialsAdopted = jest.fn();++ await expect(+ tokenLoadingFactory({ onOAuthCredentialsAdopted }).getOAuthTokensForTest(),+ ).resolves.toEqual(releasedTokens);++ expect(onOAuthCredentialsAdopted).toHaveBeenCalledWith('generation-b');+ });+ });+it('rejects a cached access token before it reaches a differently bound connection', async () => {const currentConfig = {type: 'sse' as const,@@ -1940,6 +2038,82 @@ describe('MCPConnectionFactory', () => {expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('flow123', 'mcp_get_tokens');});+ it('completes a pending token flow with the generation its silent refresh published', async () => {+ const sseConfig = {+ ...mockServerConfig,+ url: 'https://api.example.com',+ type: 'sse' as const,+ } as t.SSEOptions;+ const staleCachedTokens: MCPOAuthTokens = {+ access_token: 'stale-cached-access',+ refresh_token: 'refresh123',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };+ const freshlyRefreshedTokens: MCPOAuthTokens = {+ access_token: 'freshly-refreshed-access',+ refresh_token: 'refresh456',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockFlowManager.createFlowWithHandler.mockImplementation(async (_flowId, type) =>+ type === 'mcp_get_tokens' ? staleCachedTokens : null,+ );+ mockFlowManager.getFlowState.mockResolvedValue({+ status: 'PENDING' as const,+ type: 'mcp_get_tokens',+ metadata: {},+ createdAt: Date.now(),+ });+ mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce(async (params) => {+ const commitRefresh = await params.onRefreshPreparing?.();+ await commitRefresh?.(freshlyRefreshedTokens);+ return freshlyRefreshedTokens;+ });+ 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(+ { serverName: 'test-server', serverConfig: sseConfig },+ {+ useOAuth: true as const,+ user: mockUser,+ flowManager: mockFlowManager,+ oauthStart: jest.fn(),+ onOAuthCredentialsChanging: async () => async () => 'generation-b',+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ },+ );+ } catch {+ // Expected: the connection rejects until the refresh runs below+ }++ await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });++ expect(mockFlowManager.completeFlow).toHaveBeenCalledWith('flow123', 'mcp_get_tokens', {+ ...freshlyRefreshedTokens,+ publication_generation: 'generation-b',+ });+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(freshlyRefreshedTokens);+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled', 'silent-refresh');+ });+it('should coalesce concurrent silent refresh attempts into a single redemption', async () => {// Reproduces the concurrent-redemption race flagged by Codex on PR #13369:// if two 401s for the same user/server race the silent refresh, they@@ -4987,6 +5161,47 @@ describe('MCPConnectionFactory', () => {expect(mockConnectionInstance.connect).toHaveBeenCalled();});+ it('adopts the generation carried by the tokens an interactive OAuth flow released', async () => {+ const serverConfig = makeOAuthServerConfig();+ const onOAuthCredentialsAdopted = jest.fn();+ const oauthOptions = { ...makeOAuthOptions(), onOAuthCredentialsAdopted };++ mockProcessMCPEnv.mockReturnValue(serverConfig);+ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);++ const releasedTokens: MCPOAuthTokens = {+ access_token: 'bq-token',+ token_type: 'Bearer',+ obtained_at: 1_700_000_000_000,+ credential_set_id: 'bq-generation',+ publication_generation: 'generation-b',+ };+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow-bq');+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://accounts.google.com/o/oauth2/auth?state=xyz',+ flowId: 'flow-bq',+ flowMetadata: {+ serverName: 'bigquery',+ userId: 'user123',+ serverUrl: 'https://bigquery.googleapis.com/mcp',+ state: 'state-xyz',+ clientInfo: { client_id: 'bq-client' },+ },+ });+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(releasedTokens);++ wireEventHandlers(mockConnectionInstance);+ mockConnectionInstance.isConnected.mockResolvedValue(true);++ await expect(+ MCPConnectionFactory.create({ serverName: 'bigquery', serverConfig }, oauthOptions),+ ).resolves.toBe(mockConnectionInstance);++ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(releasedTokens);+ expect(onOAuthCredentialsAdopted).toHaveBeenCalledWith('generation-b');+ });+it('should trigger proactive OAuth when oauth is configured without requiresOAuth', async () => {const serverConfig = {type: 'streamable-http' as const,diff --git a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.tsindex d57f6e0afe..531351fc23 100644--- a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts+++ b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts@@ -125,6 +125,61 @@ describe('MCP OAuth flow state across Redis-backed instances', () => {);});+ it('runs one handler when two pods replace the same failed non-retained flow', async () => {+ const flowId = createFlowId();+ const type = 'mcp_get_tokens';+ try {+ await expect(+ podA.createFlowWithHandler(flowId, type, async () => {+ throw new Error('earlier attempt failed');+ }),+ ).rejects.toThrow('earlier attempt failed');+ const first = jest.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 100));+ return 'first';+ });+ const second = jest.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 100));+ return 'second';+ });++ const results = await Promise.all([+ podA.createFlowWithHandler(flowId, type, first),+ podB.createFlowWithHandler(flowId, type, second),+ ]);++ expect(new Set(results).size).toBe(1);+ expect(first.mock.calls.length + second.mock.calls.length).toBe(1);+ } finally {+ await podA.deleteFlow(flowId, type);+ }+ }, 15000);++ it('runs one handler when two pods create the same absent flow', async () => {+ const flowId = createFlowId();+ const type = 'mcp_get_tokens';+ try {+ const first = jest.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 100));+ return 'first';+ });+ const second = jest.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 100));+ return 'second';+ });++ const results = await Promise.all([+ podA.createFlowWithHandler(flowId, type, first),+ podB.createFlowWithHandler(flowId, type, second),+ ]);++ expect(new Set(results).size).toBe(1);+ expect(first.mock.calls.length + second.mock.calls.length).toBe(1);+ } finally {+ await podA.deleteFlow(flowId, type);+ }+ }, 15000);+it('settles a fresher result over a failure from the same attempt across pods', async () => {const flowId = createFlowId();await podA.initFlow(flowId, FLOW_TYPE, { state: 'observed-state' });diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 385262174b..c6e94ed501 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -4379,6 +4379,32 @@ describe('MCPManager', () => {};};+ const adoptingOAuthServer = (+ adopt: (options: t.OAuthConnectionOptions) => Promise<void> | void,+ ) => {+ const connection = newUserConnection();+ const serverConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://oauth-mcp.example.com/mcp',+ source: 'yaml',+ startup: false,+ requiresOAuth: true,+ };+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ (MCPConnectionFactory.create as jest.Mock).mockImplementation(+ async (_basic: t.BasicConnectionOptions, options: t.OAuthConnectionOptions) => {+ await adopt(options);+ return connection;+ },+ );+ return {+ connection,+ serverConfig,+ flowManager: mockFlowManager as unknown as t.UserMCPConnectionOptions['flowManager'],+ };+ };+it('should pass useOAuth for servers with configured oauth and no requiresOAuth value', async () => {mockAppConnections({has: jest.fn().mockResolvedValue(false),@@ -5566,6 +5592,89 @@ describe('MCPManager', () => {}});+ it('leases a new connection under the carried generation while it is the one currently stored', async () => {+ const generationSpy = jest+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')+ .mockResolvedValue('generation-a');+ const renewalSpy = jest+ .spyOn(toolsChanged, 'renewMCPToolsChangedGeneration')+ .mockResolvedValue(true);+ const { serverConfig, flowManager } = adoptingOAuthServer(async (options) => {+ generationSpy.mockResolvedValue('generation-b');+ await options.onOAuthCredentialsAdopted?.('generation-b');+ });++ try {+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.getUserConnection({ serverName, user: mockUser, flowManager, serverConfig });++ expect(renewalSpy).toHaveBeenCalledWith({+ userId,+ serverName,+ publicationGeneration: 'generation-b',+ });+ } finally {+ generationSpy.mockRestore();+ renewalSpy.mockRestore();+ }+ });++ it('keeps its captured generation when the carried one is no longer stored', async () => {+ const generationSpy = jest+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')+ .mockResolvedValue('generation-a');+ const renewalSpy = jest+ .spyOn(toolsChanged, 'renewMCPToolsChangedGeneration')+ .mockResolvedValue(true);+ const { serverConfig, flowManager } = adoptingOAuthServer((options) =>+ options.onOAuthCredentialsAdopted?.('generation-b'),+ );++ try {+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.getUserConnection({ serverName, user: mockUser, flowManager, serverConfig });++ expect(renewalSpy).toHaveBeenCalledWith({+ userId,+ serverName,+ publicationGeneration: 'generation-a',+ });+ expect(renewalSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ publicationGeneration: 'generation-b' }),+ );+ } finally {+ generationSpy.mockRestore();+ renewalSpy.mockRestore();+ }+ });++ it('re-captures the generation before re-reading credentials a change invalidated', async () => {+ const generationSpy = jest+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')+ .mockResolvedValue('generation-a');+ const renewalSpy = jest+ .spyOn(toolsChanged, 'renewMCPToolsChangedGeneration')+ .mockResolvedValue(true);+ const { serverConfig, flowManager } = adoptingOAuthServer(async (options) => {+ generationSpy.mockResolvedValue('generation-c');+ await options.onOAuthCredentialsInvalidated?.();+ });++ try {+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.getUserConnection({ serverName, user: mockUser, flowManager, serverConfig });++ expect(renewalSpy).toHaveBeenCalledWith({+ userId,+ serverName,+ publicationGeneration: 'generation-c',+ });+ } finally {+ generationSpy.mockRestore();+ renewalSpy.mockRestore();+ }+ });+it('does not return a reused connection cancelled while its lease renewal is pending', async () => {const generationSpy = jest.spyOn(toolsChanged, 'getMCPToolsChangedGeneration')diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.tsindex 672ffe9611..ffb84a918b 100644--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts@@ -16,9 +16,13 @@ import { logger } from '@librechat/data-schemas';import type { IUser } from '@librechat/data-schemas';import type { OAuthTestServer } from './helpers/oauthTestServer';import type { MCPOAuthTokens } from '~/mcp/oauth';+import type * as t from '~/mcp/types';+import {+ persistMCPAuthorizationTransaction,+ prepareMCPAuthorizationMutation,+} from '~/mcp/authorization';import { MockKeyv, InMemoryTokenStore, createOAuthMCPServer } from './helpers/oauthTestServer';import { MCPTokenStorage, MCPOAuthHandler, ReauthenticationRequiredError } from '~/mcp/oauth';-import { prepareMCPAuthorizationMutation } from '~/mcp/authorization';import { FlowStateManager, PENDING_STALE_MS } from '~/flow/manager';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';@@ -343,6 +347,199 @@ describe('MCP OAuth Token Expiry Scenarios', () => {});});+ describe('A callback settles or removes the token flow a connection is waiting on', () => {+ let server: OAuthTestServer;+ let tokenStore: InMemoryTokenStore;+ let flowManager: FlowStateManager<MCPOAuthTokens | null>;+ const tokenFlowId = MCPOAuthHandler.generateTokenFlowId('u1', 'test-srv');+ const oauthFlowId = MCPOAuthHandler.generateFlowId('u1', 'test-srv');++ class TokenLoadingFactory extends MCPConnectionFactory {+ public constructor(basic: t.BasicConnectionOptions, options: t.OAuthConnectionOptions) {+ super(basic, options);+ }++ public loadTokens(): Promise<MCPOAuthTokens | null> {+ return this.getOAuthTokens();+ }+ }++ beforeEach(async () => {+ server = await createOAuthMCPServer({ tokenTTLMs: 60000, issueRefreshTokens: true });+ tokenStore = new InMemoryTokenStore();+ flowManager = new FlowStateManager<MCPOAuthTokens | null>(+ new MockKeyv<MCPOAuthTokens | null>() as unknown as Keyv,+ { ttl: 30000, ci: true },+ );+ });++ afterEach(async () => {+ await server.close();+ });++ const waitingConnection = (+ hooks: Pick<+ t.UserConnectionContext,+ 'onOAuthCredentialsAdopted' | 'onOAuthCredentialsInvalidated'+ >,+ ) =>+ new TokenLoadingFactory(+ { serverName: 'test-srv', serverConfig: { type: 'streamable-http', url: server.url } },+ {+ useOAuth: true,+ user: { id: 'u1' } as IUser,+ flowManager,+ tokenMethods: {+ findToken: tokenStore.findToken,+ createToken: tokenStore.createToken,+ updateToken: tokenStore.updateToken,+ deleteTokens: tokenStore.deleteTokens,+ },+ ...hooks,+ },+ );++ /** Mirrors the callback route: exchanges a code, then stores, publishes, and settles in one transaction. */+ const completeAuthorizationFromCallback = async () => {+ const code = await server.getAuthCode();+ const tokenRes = await fetch(`${server.url}token`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: `grant_type=authorization_code&code=${code}`,+ });+ const exchanged = (await tokenRes.json()) as {+ access_token: string;+ token_type: string;+ expires_in: number;+ refresh_token: string;+ };+ const exchangedTokens: MCPOAuthTokens = {+ ...exchanged,+ obtained_at: Date.now(),+ expires_at: Date.now() + exchanged.expires_in * 1000,+ };+ await flowManager.initFlow(oauthFlowId, 'mcp_oauth', {+ serverName: 'test-srv',+ userId: 'u1',+ serverUrl: server.url,+ state: 'callback-state',+ });+ const stored = await persistMCPAuthorizationTransaction(+ {+ scope: { userId: 'u1', serverName: 'test-srv' },+ flowIds: [tokenFlowId, oauthFlowId],+ tokens: exchangedTokens,+ completeAuthorization: async (tokens) => {+ await flowManager.completeFlow(oauthFlowId, 'mcp_oauth', tokens);+ },+ persistTokens: (tokens, onStoreCommitted) =>+ MCPTokenStorage.storeTokens({+ userId: 'u1',+ serverName: 'test-srv',+ tokens,+ createToken: tokenStore.createToken,+ updateToken: tokenStore.updateToken,+ deleteTokens: tokenStore.deleteTokens,+ findToken: tokenStore.findToken,+ clientInfo: { client_id: 'test-client' },+ metadata: bindingMetadata(server.url),+ onStoreCommitted,+ }),+ },+ {+ ensureServerActive: async () => true,+ inactiveServerError: () => new Error('deleted'),+ invalidateRecoveryGeneration: async () => 'generation-2',+ persistPublicationRetry: async () => 'retry-v1',+ clearPublicationRetry: async () => undefined,+ flowManager,+ retryDelaysMs: [0],+ },+ );+ return { exchanged, stored };+ };++ it('re-reads the tokens a callback stored after removing the failed flow it was waiting on', async () => {+ let failEarlierAttempt: (() => void) | undefined;+ const earlierAttempt = flowManager.createFlowWithHandler(+ tokenFlowId,+ 'mcp_get_tokens',+ () =>+ new Promise<MCPOAuthTokens | null>((_, reject) => {+ failEarlierAttempt = () =>+ reject(new ReauthenticationRequiredError('test-srv', 'missing'));+ }),+ );+ await waitForCondition(+ async () =>+ (await flowManager.getFlowState(tokenFlowId, 'mcp_get_tokens'))?.status === 'PENDING',+ );++ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);+ const onOAuthCredentialsAdopted = jest.fn();+ const waiting = waitingConnection({+ onOAuthCredentialsInvalidated,+ onOAuthCredentialsAdopted,+ }).loadTokens();+ await new Promise((resolve) => setTimeout(resolve, 250));++ failEarlierAttempt?.();+ await expect(earlierAttempt).rejects.toBeInstanceOf(ReauthenticationRequiredError);+ expect((await flowManager.getFlowState(tokenFlowId, 'mcp_get_tokens'))?.status).toBe(+ 'FAILED',+ );++ const { exchanged } = await completeAuthorizationFromCallback();+ expect(await flowManager.getFlowState(tokenFlowId, 'mcp_get_tokens')).toBeFalsy();++ await expect(waiting).resolves.toMatchObject({ access_token: exchanged.access_token });+ expect(onOAuthCredentialsInvalidated).toHaveBeenCalledTimes(1);+ expect(onOAuthCredentialsAdopted).not.toHaveBeenCalled();+ expect((await flowManager.getFlowState(oauthFlowId, 'mcp_oauth'))?.result).toMatchObject({+ access_token: exchanged.access_token,+ publication_generation: 'generation-2',+ });+ }, 15000);++ it('adopts the generation a callback published when it settles the flow it was waiting on', async () => {+ let finishEarlierAttempt: (() => void) | undefined;+ const earlierAttempt = flowManager.createFlowWithHandler(+ tokenFlowId,+ 'mcp_get_tokens',+ () =>+ new Promise<MCPOAuthTokens | null>((resolve) => {+ finishEarlierAttempt = () => resolve(null);+ }),+ );+ await waitForCondition(+ async () =>+ (await flowManager.getFlowState(tokenFlowId, 'mcp_get_tokens'))?.status === 'PENDING',+ );++ const onOAuthCredentialsInvalidated = jest.fn().mockResolvedValue(undefined);+ const onOAuthCredentialsAdopted = jest.fn();+ const waiting = waitingConnection({+ onOAuthCredentialsInvalidated,+ onOAuthCredentialsAdopted,+ }).loadTokens();+ await new Promise((resolve) => setTimeout(resolve, 250));++ const { exchanged } = await completeAuthorizationFromCallback();++ await expect(waiting).resolves.toMatchObject({+ access_token: exchanged.access_token,+ publication_generation: 'generation-2',+ });+ expect(onOAuthCredentialsAdopted).toHaveBeenCalledWith('generation-2');+ expect(onOAuthCredentialsInvalidated).not.toHaveBeenCalled();++ finishEarlierAttempt?.();+ await expect(earlierAttempt).resolves.toMatchObject({+ access_token: exchanged.access_token,+ });+ }, 15000);+ });+describe('Access token expired + refresh token rejected by server', () => {let tokenStore: InMemoryTokenStore;diff --git a/packages/api/src/mcp/authorization.spec.ts b/packages/api/src/mcp/authorization.spec.tsindex 530d01e7e5..99eb53f05e 100644--- a/packages/api/src/mcp/authorization.spec.ts+++ b/packages/api/src/mcp/authorization.spec.ts@@ -133,6 +133,95 @@ describe('persistMCPAuthorizationTransaction', () => {completeAuthorization.mock.invocationCallOrder[0],);});++ it('hands the published generation to the OAuth completion and pending token waiters', async () => {+ const tokens = { access_token: 'fresh' };+ const persistTokens = jest.fn(async (_tokens, onStoreCommitted) => {+ await onStoreCommitted(tokens);+ return tokens;+ });+ const completeAuthorization = jest.fn().mockResolvedValue(undefined);+ const flowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ type: 'mcp_get_tokens',+ status: 'PENDING',+ createdAt: 123,+ metadata: {},+ }),+ deleteFlow: jest.fn(),+ settleFlowIfCurrent: jest.fn().mockResolvedValue('updated'),+ };++ const transactionResult = await persistMCPAuthorizationTransaction(+ { scope, flowIds: ['token-flow'], tokens, completeAuthorization, persistTokens },+ {+ ensureServerActive: jest.fn().mockResolvedValue(true),+ inactiveServerError: () => new Error('deleted'),+ invalidateRecoveryGeneration: jest.fn().mockResolvedValue('generation-b'),+ persistPublicationRetry: jest.fn().mockResolvedValue('prepared-v1'),+ clearPublicationRetry: jest.fn().mockResolvedValue(undefined),+ flowManager,+ retryDelaysMs: [0],+ },+ );+ expect(transactionResult).toEqual({+ access_token: 'fresh',+ publication_generation: 'generation-b',+ });++ const released = { access_token: 'fresh', publication_generation: 'generation-b' };+ expect(completeAuthorization).toHaveBeenCalledWith(released);+ expect(completeAuthorization.mock.calls[0][0]).toBe(transactionResult);+ expect(flowManager.settleFlowIfCurrent).toHaveBeenCalledWith(+ 'token-flow',+ 'mcp_get_tokens',+ 123,+ '',+ released,+ );+ });++ it('releases the committed tokens unchanged when the publication reports no generation', async () => {+ const tokens = { access_token: 'fresh' };+ const persistTokens = jest.fn(async (_tokens, onStoreCommitted) => {+ await onStoreCommitted(tokens);+ return tokens;+ });+ const completeAuthorization = jest.fn().mockResolvedValue(undefined);+ const flowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ type: 'mcp_get_tokens',+ status: 'PENDING',+ createdAt: 123,+ metadata: {},+ }),+ deleteFlow: jest.fn(),+ settleFlowIfCurrent: jest.fn().mockResolvedValue('updated'),+ };++ await persistMCPAuthorizationTransaction(+ { scope, flowIds: ['token-flow'], tokens, completeAuthorization, persistTokens },+ {+ ensureServerActive: jest.fn().mockResolvedValue(true),+ inactiveServerError: () => new Error('deleted'),+ invalidateRecoveryGeneration: jest.fn().mockResolvedValue(undefined),+ persistPublicationRetry: jest.fn().mockResolvedValue('prepared-v1'),+ clearPublicationRetry: jest.fn().mockResolvedValue(undefined),+ flowManager,+ retryDelaysMs: [0],+ },+ );++ expect(completeAuthorization).toHaveBeenCalledWith(tokens);+ expect(completeAuthorization.mock.calls[0][0]).toBe(tokens);+ expect(flowManager.settleFlowIfCurrent).toHaveBeenCalledWith(+ 'token-flow',+ 'mcp_get_tokens',+ 123,+ '',+ tokens,+ );+ });});describe('finalizeMCPAuthorizationMutation', () => {diff --git a/packages/api/src/mcp/authorization.ts b/packages/api/src/mcp/authorization.tsindex a0bed04c27..63d6b7d391 100644--- a/packages/api/src/mcp/authorization.ts+++ b/packages/api/src/mcp/authorization.ts@@ -152,8 +152,12 @@ export async function prepareMCPAuthorizationMutation(});}-/** Owns the OAuth authorization transaction while the token store's rollback journal is live. */-export async function persistMCPAuthorizationTransaction<TTokens>(+/**+ * Owns the OAuth authorization transaction while the token store's rollback journal is live. The+ * tokens released to the authorization flow, to pending token waiters, and to the caller carry the+ * generation the publication wrote, so a connection built on them leases under that generation.+ */+export async function persistMCPAuthorizationTransaction<TTokens extends object>(params: PersistMCPAuthorizationTransactionParams<TTokens>,deps: PersistMCPAuthorizationTransactionDeps<TTokens>,): Promise<TTokens> {@@ -161,20 +165,26 @@ export async function persistMCPAuthorizationTransaction<TTokens>(throw deps.inactiveServerError();}const publishPreparedMutation = await prepareMCPAuthorizationMutation(params.scope, deps);- return params.persistTokens(params.tokens, async (committedTokens) => {+ let releasedTokens: TTokens | undefined;+ const storedTokens = await params.persistTokens(params.tokens, async (committedTokens) => {if (!(await deps.ensureServerActive())) {throw deps.inactiveServerError();}- await publishPreparedMutation();+ const publicationGeneration = await publishPreparedMutation();+ releasedTokens =+ publicationGeneration == null+ ? committedTokens+ : { ...committedTokens, publication_generation: publicationGeneration };await completeMCPAuthorizationWithTokenWaiters({flowIds: params.flowIds,- tokens: committedTokens,+ tokens: releasedTokens,completeAuthorization: params.completeAuthorization,},deps,);});+ return releasedTokens ?? storedTokens;}/**diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.tsindex eed6d685bb..e161a79e38 100644--- a/packages/api/src/mcp/oauth/types.ts+++ b/packages/api/src/mcp/oauth/types.ts@@ -128,6 +128,12 @@ export interface MCPOAuthTokens extends OAuthTokens {obtained_at: number;/** Calculated expiry time */expires_at?: number;+ /**+ * Tool-cache publication generation written when these tokens were persisted. Carried only by+ * tokens handed to the waiters of the authorization or refresh that stored them, never by a+ * stored row, so a connection built on them can lease under that generation.+ */+ publication_generation?: string;}/** Extended OAuth tokens that may include refresh token expiry */diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex 576f55f57d..68c7759743 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -277,6 +277,20 @@ export interface UserConnectionContext {* OAuth token flow still persisting a refresh. The work keeps running; the promise settles with it.*/onDiscoveryDetached?: (work: Promise<unknown>) => void;+ /**+ * Reports the publication generation carried by credentials the factory adopted from an+ * authorization or refresh it did not perform. A caller leasing a generation captured before it+ * resolved credentials moves the lease to the reported one while that is the generation+ * currently stored: the build then leases under the publication that stored its credentials+ * and stays fenced by any rotation that followed them.+ */+ onOAuthCredentialsAdopted?: (publicationGeneration: string) => Promise<void>;+ /**+ * Runs before the factory re-reads credentials from storage because a credential change+ * 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>;}export interface RequestScopedMCPConnectionStore {