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: Stop an MCP Credential Refresh From Fencing Its Own Connection (#15863)
Danny Avila5a2c4a043562
diff --git a/api/server/services/Config/__tests__/getCachedTools.spec.js b/api/server/services/Config/__tests__/getCachedTools.spec.jsindex dd5e231f02..efc92b4183 100644--- a/api/server/services/Config/__tests__/getCachedTools.spec.js+++ b/api/server/services/Config/__tests__/getCachedTools.spec.js@@ -431,10 +431,25 @@ describe('MCP tool cache', () => {);});+ it('reports the rotated generation so its caller can tell its own fence from a foreign one', async () => {+ mockCache.set.mockResolvedValue(true);+ mockCache.delete.mockResolvedValue(true);++ const published = await invalidateCachedTools({ userId: 'user1', serverName: 'github' });++ expect(published).toEqual(expect.any(String));+ expect(mockCache.set).toHaveBeenNthCalledWith(+ 2,+ ToolCacheKeys.MCP_SERVER_GENERATION('user1', 'github'),+ published,+ expect.any(Number),+ );+ });+it('invalidates only the static global key for broad config changes', async () => {mockCache.delete.mockResolvedValue(true);- await invalidateCachedTools({ invalidateGlobal: true });+ await expect(invalidateCachedTools({ invalidateGlobal: true })).resolves.toBeUndefined();expect(mockCache.delete).toHaveBeenCalledTimes(1);expect(mockCache.delete).toHaveBeenCalledWith(ToolCacheKeys.GLOBAL);diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.tsindex 9fa5537578..1fc14c4a16 100644--- a/packages/api/src/mcp/UserConnectionManager.ts+++ b/packages/api/src/mcp/UserConnectionManager.ts@@ -796,6 +796,27 @@ export abstract class UserConnectionManager {ephemeralConnection,};+ /**+ * 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.+ */+ let selfPublishedGeneration: string | undefined;+ const trackPublishedGeneration: t.UserConnectionContext['onOAuthCredentialsChanging'] =+ onOAuthCredentialsChanging == null+ ? undefined+ : async (scope) => {+ const publish = await onOAuthCredentialsChanging(scope);+ return async () => {+ const published = await publish();+ if (published) {+ selfPublishedGeneration = published;+ }+ return published;+ };+ };+const useOAuth = usesDirectOpenIDBearerRecovery(config)? false: requiresOAuthMachinery(runtimeConfig);@@ -826,7 +847,7 @@ export abstract class UserConnectionManager {requestBody: requestBody,connectionTimeout: connectionTimeout,onOAuthCredentialsChanged,- onOAuthCredentialsChanging,+ onOAuthCredentialsChanging: trackPublishedGeneration,};} else {connectionOptions = {@@ -844,8 +865,12 @@ export abstract class UserConnectionManager {this.assertCreationNotCancelled(creationGuard, userId, serverName);- if (publicationGeneration) {- this.toolPublicationGenerations.set(connection, publicationGeneration);+ const effectiveGeneration = ephemeralConnection+ ? undefined+ : (selfPublishedGeneration ?? publicationGeneration);++ if (effectiveGeneration) {+ this.toolPublicationGenerations.set(connection, effectiveGeneration);}if (configGeneration) {this.toolConfigGenerations.set(connection, configGeneration);@@ -857,7 +882,7 @@ export abstract class UserConnectionManager {userId,serverName,serverConfig: config,- ...(publicationGeneration && { publicationGeneration }),+ ...(effectiveGeneration && { publicationGeneration: effectiveGeneration }),...(publicationRevision && { publicationRevision }),});});diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 09474c1cac..a2caaa14b8 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -4350,6 +4350,32 @@ describe('MCPManager', () => {dispose: jest.fn().mockResolvedValue(undefined),}) as unknown as MCPConnection;+ /** An OAuth server whose connection build refreshes credentials, fencing the catalog mid-build. */+ const refreshingOAuthServer = () => {+ 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) => {+ const publish = await options.onOAuthCredentialsChanging?.({ userId, serverName });+ await publish?.();+ 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),@@ -5473,6 +5499,70 @@ describe('MCPManager', () => {}});+ it('leases a new connection under the generation its own credential refresh published', async () => {+ const generationSpy = jest+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')+ .mockResolvedValue('generation-a');+ const renewalSpy = jest+ .spyOn(toolsChanged, 'renewMCPToolsChangedGeneration')+ .mockResolvedValue(true);+ const { serverConfig, flowManager } = refreshingOAuthServer();++ try {+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.getUserConnection({+ serverName,+ user: mockUser,+ flowManager,+ serverConfig,+ onOAuthCredentialsChanging: async () => async () => 'generation-b',+ });++ expect(renewalSpy).toHaveBeenCalledWith({+ userId,+ serverName,+ publicationGeneration: 'generation-b',+ });+ } finally {+ generationSpy.mockRestore();+ renewalSpy.mockRestore();+ }+ });++ it('still fences a new connection when a rotation follows its own credential refresh', async () => {+ const generationSpy = jest+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')+ .mockResolvedValue('generation-a');+ const renewalSpy = jest+ .spyOn(toolsChanged, 'renewMCPToolsChangedGeneration')+ .mockResolvedValue(false);+ const { serverConfig, flowManager, connection } = refreshingOAuthServer();++ try {+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await expect(+ manager.getUserConnection({+ serverName,+ user: mockUser,+ flowManager,+ serverConfig,+ onOAuthCredentialsChanging: async () => async () => 'generation-b',+ }),+ ).rejects.toThrow('Publication lease is no longer current');++ expect(renewalSpy).toHaveBeenCalledWith({+ userId,+ serverName,+ publicationGeneration: 'generation-b',+ });+ expect(connection.dispose).toHaveBeenCalled();+ expect(manager.getUserConnections(userId)?.has(serverName) ?? false).toBe(false);+ } 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/authorization.ts b/packages/api/src/mcp/authorization.tsindex dc4d5feed3..2a996e2f44 100644--- a/packages/api/src/mcp/authorization.ts+++ b/packages/api/src/mcp/authorization.ts@@ -134,11 +134,14 @@ export interface PersistMCPAuthorizationTransactionDeps<TTokens>inactiveServerError: () => Error;}-/** Writes a durable intent now and returns the exact publication that clears only that intent. */+/**+ * Writes a durable intent now and returns the exact publication that clears only that intent.+ * The publication reports the generation it wrote so its own caller can adopt it.+ */export async function prepareMCPAuthorizationMutation(scope: MCPRecoveryGenerationScope,deps: MCPAuthorizationPublicationDeps,-): Promise<() => Promise<void>> {+): Promise<() => Promise<string | undefined>> {const publicationRetryVersion = await deps.persistPublicationRetry?.(scope);return () =>publishMCPAuthorizationMutation(scope, {diff --git a/packages/api/src/mcp/catalog/recovery.ts b/packages/api/src/mcp/catalog/recovery.tsindex d23c74b61b..ebce24817c 100644--- a/packages/api/src/mcp/catalog/recovery.ts+++ b/packages/api/src/mcp/catalog/recovery.ts@@ -75,7 +75,7 @@ export async function publishMCPAuthorizationMutation(retryDelaysMs?: readonly number[];attemptTimeoutMs?: number;},-): Promise<void> {+): Promise<string | undefined> {/** Persist retry intent before touching the shared cache. A credential writer can keep this* inside its rollback boundary, so a cache outage never leaves a committed mutation with no* durable path to fence other replicas. */@@ -89,8 +89,9 @@ export async function publishMCPAuthorizationMutation(const attemptTimeoutMs =deps.attemptTimeoutMs ?? DEFAULT_RECOVERY_POLICY.authorizationFenceTimeoutMs;let timeoutId: ReturnType<typeof setTimeout> | undefined;+ let published: unknown;try {- await Promise.race([+ published = await Promise.race([deps.invalidateRecoveryGeneration(scope),new Promise<never>((_, reject) => {timeoutId = setTimeout(@@ -114,7 +115,7 @@ export async function publishMCPAuthorizationMutation();}deps.clearLocalRecovery?.(scope.userId, scope.serverName);- return;+ return typeof published === 'string' && published.length > 0 ? published : undefined;} catch (error) {lastError = error;logger.warn(diff --git a/packages/api/src/mcp/catalog/store.ts b/packages/api/src/mcp/catalog/store.tsindex 574a71f4ad..21a6063367 100644--- a/packages/api/src/mcp/catalog/store.ts+++ b/packages/api/src/mcp/catalog/store.ts@@ -239,7 +239,7 @@ export interface MCPCatalogStore {userId?: string;serverName?: string;invalidateGlobal?: boolean;- }) => Promise<void>;+ }) => Promise<string | undefined>;}function isTools(value: unknown): value is LCAvailableTools {@@ -851,41 +851,46 @@ export function createMCPCatalogStore(deps: CatalogStoreDeps): MCPCatalogStore {return Number(written) === 1;}+ /** Returns the generation this invalidation published for a user and server, so a caller that+ * fenced its own credential mutation can tell that rotation apart from a foreign one. */async function invalidateCachedTools(options: {userId?: string;serverName?: string;invalidateGlobal?: boolean;} = {},- ): Promise<void> {+ ): Promise<string | undefined> {const cache = await getReadyCache();if (options.invalidateGlobal) {await runWithGlobalCacheLock(() => deleteGlobalWithinLock(cache));}const { userId, serverName } = options;- if (userId && serverName) {- await withUserQueue(userId, serverName, async () => {- if (- (await cache.set(- ToolCacheKeys.MCP_SERVER_LEGACY_FENCE(userId, serverName),- true,- generationTtl,- )) === false- ) {- throw new Error('Tool cache rejected the legacy migration fence');- }- if (- (await cache.set(- ToolCacheKeys.MCP_SERVER_GENERATION(userId, serverName),- randomUUID(),- generationTtl,- )) === false- ) {- throw new Error('Tool publication generation cache rejected invalidation');- }- await cache.delete(ToolCacheKeys.MCP_SERVER(userId, serverName));- });+ if (!userId || !serverName) {+ return undefined;}+ return withUserQueue(userId, serverName, async () => {+ const generation = randomUUID();+ if (+ (await cache.set(+ ToolCacheKeys.MCP_SERVER_LEGACY_FENCE(userId, serverName),+ true,+ generationTtl,+ )) === false+ ) {+ throw new Error('Tool cache rejected the legacy migration fence');+ }+ if (+ (await cache.set(+ ToolCacheKeys.MCP_SERVER_GENERATION(userId, serverName),+ generation,+ generationTtl,+ )) === false+ ) {+ throw new Error('Tool publication generation cache rejected invalidation');+ }+ await cache.delete(ToolCacheKeys.MCP_SERVER(userId, serverName));+ return generation;+ });}return {diff --git a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts b/packages/api/src/mcp/oauth/OAuthReconnectionManager.tsindex 77dee5d711..1e831cffc6 100644--- a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts+++ b/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts@@ -1,6 +1,6 @@import { logger } from '@librechat/data-schemas';import type { TokenMethods, IUser } from '@librechat/data-schemas';-import type { ParsedServerConfig } from '~/mcp/types';+import type { ParsedServerConfig, UserConnectionContext } from '~/mcp/types';import type { MCPOAuthTokens } from './types';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { OAuthReconnectionTracker } from './OAuthReconnectionTracker';@@ -23,10 +23,7 @@ export class OAuthReconnectionManager {serverName: string;}) => Promise<void>;- private readonly onOAuthCredentialsChanging?: (scope: {- userId: string;- serverName: string;- }) => Promise<() => Promise<void>>;+ private readonly onOAuthCredentialsChanging?: UserConnectionContext['onOAuthCredentialsChanging'];private readonly reconnectionsTracker: OAuthReconnectionTracker;@@ -42,10 +39,7 @@ export class OAuthReconnectionManager {tokenMethods: TokenMethods,reconnections?: OAuthReconnectionTracker,onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>,- onOAuthCredentialsChanging?: (scope: {- userId: string;- serverName: string;- }) => Promise<() => Promise<void>>,+ onOAuthCredentialsChanging?: UserConnectionContext['onOAuthCredentialsChanging'],): Promise<OAuthReconnectionManager> {if (OAuthReconnectionManager.instance != null) {throw new Error('OAuthReconnectionManager already initialized');@@ -68,10 +62,7 @@ export class OAuthReconnectionManager {tokenMethods: TokenMethods,reconnections?: OAuthReconnectionTracker,onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>,- onOAuthCredentialsChanging?: (scope: {- userId: string;- serverName: string;- }) => Promise<() => Promise<void>>,+ onOAuthCredentialsChanging?: UserConnectionContext['onOAuthCredentialsChanging'],) {this.flowManager = flowManager;this.tokenMethods = tokenMethods;diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex 98d1ae4ffa..03f604ff36 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -263,11 +263,15 @@ export interface UserConnectionContext {deadlineMs?: number;/** Advances application authorization state after OAuth token persistence succeeds. */onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>;- /** Persists authorization-fence intent before OAuth token rows change and returns its publisher. */+ /**+ * Persists authorization-fence intent before OAuth token rows change and returns its publisher.+ * The publisher reports the generation it wrote, so a caller that fenced its own credential+ * change can adopt that generation instead of the one it captured beforehand.+ */onOAuthCredentialsChanging?: (scope: {userId: string;serverName: string;- }) => Promise<() => Promise<void>>;+ }) => Promise<() => Promise<string | undefined>>;}export interface RequestScopedMCPConnectionStore {