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 Reporting Rejected MCP Credentials as Authorized (#16571)
lia-by-librechat[bot]3b4e7b1e5e81
diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex b1fc7814d3..a774118948 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -863,6 +863,48 @@ describe('tests for the new helper functions used by the MCP connection status e});});+ it('does not report rejected stored credentials as connected after the OAuth flow is gone', async () => {+ const { findToken } = require('~/models');+ const credentialSetId = 'rejected-generation';+ mockGetOAuthReconnectionManager.mockReturnValue({ isReconnecting: jest.fn(() => false) });+ mockGetFlowStateManager.mockReturnValue({ getFlowState: jest.fn(() => null) });+ mockGetLogStores.mockReturnValue({});+ findToken.mockImplementation(async ({ type }) => {+ if (type === 'mcp_oauth_client') {+ return {+ token: 'enc:{"client_id":"dynamic-client"}',+ metadata: {+ credential_set_id: credentialSetId,+ rejected_credential_set_id: credentialSetId,+ authorization_endpoint: 'https://auth.example.com/authorize',+ token_endpoint: 'https://auth.example.com/token',+ server_url: 'https://mcp.example.com/',+ client_source: 'dynamic',+ },+ };+ }+ return {+ expiresAt: new Date(Date.now() + 60000),+ metadata: { credential_set_id: credentialSetId },+ };+ });++ const result = await getServerConnectionStatus(+ mockUserId,+ mockServerName,+ { ...mockConfig, url: 'https://mcp.example.com/' },+ new Map(),+ new Map(),+ new Set([mockServerName]),+ );++ expect(result).toEqual({+ requiresOAuth: true,+ connectionState: 'disconnected',+ authorizationState: 'needs_authorization',+ });+ });+it('should derive runtime-detected OAuth readiness from bound token storage', async () => {const appConnections = new Map();const userConnections = new Map();diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 01f52f9349..7f5b9de457 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -413,6 +413,7 @@ export class MCPConnectionFactory {let connection: MCPConnection | null = null;let oauthHandler: (() => void) | null = null;+ let rejectionRecorded: Promise<void> | undefined;if (shouldAttemptAuthenticatedDiscovery) {connection = new MCPConnection({serverName: this.serverName,@@ -432,6 +433,7 @@ export class MCPConnectionFactory {`${this.logPrefix} [Discovery] OAuth required; skipping URL generation in discovery mode`,);oauthRequired = true;+ rejectionRecorded = this.recordRejectedOAuthAuthorization(oauthTokens?.credential_set_id);connection?.emit('oauthFailed', new Error('OAuth required during tool discovery'));};@@ -445,10 +447,16 @@ export class MCPConnectionFactory {if (await connection.isConnected(abortSignal)) {const snapshot = await connection.fetchOrderedToolsSnapshot(this.deadlineMs, abortSignal);connection.removeListener('oauthRequired', oauthHandler);+ const rejectedOAuth = this.useOAuth && snapshot.authenticationError != null;+ if (rejectedOAuth) {+ await this.waitForDiscoveryRejection(+ this.recordRejectedOAuthAuthorization(oauthTokens?.credential_set_id),+ );+ }return {tools: snapshot.complete ? snapshot.tools : null,connection,- oauthRequired: false,+ oauthRequired: rejectedOAuth,oauthUrl: null,...(snapshot.authenticationError != null && {authenticationError: snapshot.authenticationError,@@ -467,6 +475,7 @@ export class MCPConnectionFactory {* discovery never holds two concurrent connects to the same server. */connection.removeListener('oauthRequired', oauthHandler);await this.disposeQuietly(connection);+ await this.waitForDiscoveryRejection(rejectionRecorded);connection = null;oauthHandler = null;}@@ -1213,7 +1222,8 @@ export class MCPConnectionFactory {* would hand back stale tokens on a subsequent 401 (e.g. when the freshly* minted token is revoked before its local expiry). Caching only the* in-flight promise means every fresh 401 after settlement triggers a- * fresh redemption.+ * fresh redemption. Token storage owns rejection persistence inside the+ * common flight shared with expired-token loading.*/protected async attemptSilentTokenRefresh(rejectedCredentialSetId?: string | null,@@ -1753,6 +1763,34 @@ export class MCPConnectionFactory {connection.emit('oauthFailed', error);}+ /** Cancellation ends discovery's wait, never the generation-guarded persistence operation. */+ private async waitForDiscoveryRejection(pending?: Promise<void>): Promise<void> {+ if (!pending) return;+ const recorded = await waitUntilDeadline(pending, this.deadlineMs, this.signal);+ if (!recorded.settled) this.onDiscoveryDetached?.(pending);+ }++ private async recordRejectedOAuthAuthorization(credentialSetId?: string | null): Promise<void> {+ if (!credentialSetId || !this.tokenMethods?.findToken || !this.tokenMethods.updateToken) {+ return;+ }+ try {+ await this.runWithCapturedTenant(() =>+ MCPTokenStorage.markAuthorizationRejected({+ userId: this.userId!,+ serverName: this.serverName,+ credentialSetId,+ findToken: this.tokenMethods!.findToken!,+ updateToken: this.tokenMethods!.updateToken!,+ flowManager: this.flowManager,+ persistenceWaitTimeoutMs: this.serverConfig.oauthPersistenceWaitTimeout,+ }),+ );+ } catch (error) {+ logger.warn(`${this.logPrefix} Failed to record upstream OAuth rejection`, error);+ }+ }+/** Sets up OAuth event handlers for the connection */protected handleOAuthEvents(connection: MCPConnection,@@ -1776,6 +1814,11 @@ export class MCPConnectionFactory {return;}logger.info(`${this.logPrefix} Cached connection requires a live OAuth request handler`);+ await this.recordRejectedOAuthAuthorization(+ data.rejectedCredentialSetId !== undefined+ ? data.rejectedCredentialSetId+ : connection.getOAuthCredentialSetId(),+ );connection.emit('oauthFailed', new Error('OAuth reauthentication required'));return;}@@ -1798,6 +1841,7 @@ export class MCPConnectionFactory {}if (isRequestRecovery && recoveryPhase === 'terminal') {+ await this.recordRejectedOAuthAuthorization(rejectedCredentialSetId);logger.warn(`${this.logPrefix} OAuth recovery phase budget exhausted`);connection.emit('oauthFailed', new Error('OAuth recovery phase budget exhausted'));return;@@ -1846,6 +1890,8 @@ export class MCPConnectionFactory {}}+ await this.recordRejectedOAuthAuthorization(rejectedCredentialSetId);+if (isRequestRecovery) {recoveryPhase = 'terminal';}diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.tsindex 1b6fead036..e6582f8e0c 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts@@ -1,5 +1,5 @@import { Keyv } from 'keyv';-import type { IUser } from '@librechat/data-schemas';+import type { TokenMethods, IUser } from '@librechat/data-schemas';import type {OAuthClientInformation,OAuthStoredClientMetadata,@@ -230,6 +230,49 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (expect(postHeaders).toEqual([undefined]);});+ it('keeps rejected refreshed credentials unauthorized across discovery and status reads', async () => {+ server = await createOAuthMCPServer({ issueRefreshTokens: true, rejectRefreshTokens: 1 });+ const initial = await issueTokens(server);+ await storeTokens(tokenStore, server, { ...initial, expires_at: Date.now() - 1000 });+ const tokenMethods = {+ findToken: tokenStore.findToken,+ createToken: tokenStore.createToken,+ replaceTokenIfCurrent: jest.fn(),+ updateToken: tokenStore.updateToken,+ deleteTokens: tokenStore.deleteTokens,+ };+ const result = await MCPConnectionFactory.discoverTools(+ {+ serverName: SERVER_NAME,+ serverConfig: { type: 'streamable-http', url: server.url, requiresOAuth: true },+ },+ {+ useOAuth: true,+ user: { id: USER_ID } as IUser,+ flowManager: createFlowManager(),+ tokenMethods,+ },+ );+ connection = result.connection;+ const hasStoredAuthorization = () =>+ MCPTokenStorage.hasStoredAuthorization({+ userId: USER_ID,+ serverName: SERVER_NAME,+ findToken: tokenStore.findToken,+ validateClientBinding: (clientInfo, metadata) =>+ MCPOAuthHandler.assertStoredClientBinding(SERVER_NAME, server.url, clientInfo, metadata),+ });++ expect(result.oauthRequired).toBe(true);+ expect(+ server.tokenRequests.filter((request) => request.grantType === 'refresh_token'),+ ).toHaveLength(1);+ await expect(hasStoredAuthorization()).resolves.toBe(false);++ await storeTokens(tokenStore, server, await issueTokens(server));+ await expect(hasStoredAuthorization()).resolves.toBe(true);+ });+it('does not cancel finished SDK requests when a shared run signal is aborted', async () => {let resourcePosts = 0;server = await createOAuthMCPServer({@@ -673,6 +716,206 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (}});+ it.each([undefined, true])(+ 'coalesces concurrent rejection persistence and refresh (coordination: %s)',+ async (oauthRefreshCoordination) => {+ server = await createOAuthMCPServer({+ issueRefreshTokens: true,+ refreshGate: async () => {+ server.issuedTokens.clear();+ },+ });+ const initialTokens = await storeTokens(tokenStore, server, await issueTokens(server));+ const flowManager = createFlowManager();+ let rejectionStarted!: () => void;+ let releaseRejection!: () => void;+ let firstRecoveryDone!: () => void;+ const started = new Promise<void>((resolve) => (rejectionStarted = resolve));+ const blocked = new Promise<void>((resolve) => (releaseRejection = resolve));+ const recovered = new Promise<void>((resolve) => (firstRecoveryDone = resolve));+ let holdingRejection = false;+ const updateToken: TokenMethods['updateToken'] = async (query, update) => {+ const marker =+ update.metadata instanceof Map+ ? update.metadata.get('rejected_credential_set_id')+ : update.metadata?.rejected_credential_set_id;+ if (marker === initialTokens.credential_set_id) {+ holdingRejection = true;+ rejectionStarted();+ await blocked;+ holdingRejection = false;+ }+ return tokenStore.updateToken(query, update);+ };+ const basic = {+ serverName: SERVER_NAME,+ serverConfig: {+ type: 'streamable-http' as const,+ url: server.url,+ requiresOAuth: true,+ oauthRefreshCoordination,+ },+ ephemeralConnection: true,+ };+ const options = {+ useOAuth: true as const,+ user: { id: USER_ID } as IUser,+ flowManager,+ tokenMethods: {+ findToken: tokenStore.findToken,+ createToken: tokenStore.createToken,+ replaceTokenIfCurrent: jest.fn(),+ updateToken,+ deleteTokens: tokenStore.deleteTokens,+ },+ };+ connection = await MCPConnectionFactory.create(basic, options);+ const second = await MCPConnectionFactory.create(basic, options);+ const cleanFirst = MCPConnectionFactory.attachRequestOAuthHandler(basic, options, connection);+ const cleanSecond = MCPConnectionFactory.attachRequestOAuthHandler(basic, options, second);+ type RecoveryHandler = (challenge: {+ serverUrl: string;+ rejectedCredentialSetId?: string;+ }) => Promise<void>;+ const firstHandler = connection.listeners(+ 'oauthReauthenticationRequired',+ )[0] as RecoveryHandler;+ const secondHandler = second.listeners('oauthReauthenticationRequired')[0] as RecoveryHandler;+ const acquireLease = flowManager.acquireLease.bind(flowManager);+ const acquireSpy = jest+ .spyOn(flowManager, 'acquireLease')+ .mockImplementation(async (...args) => {+ if (holdingRejection) await recovered;+ return acquireLease(...args);+ });+ const generationSpy = jest.spyOn(flowManager, 'getLeaseGeneration');+ const challenge = {+ serverUrl: server.url,+ rejectedCredentialSetId: initialTokens.credential_set_id,+ };+ try {+ server.issuedTokens.delete(initialTokens.access_token);+ const firstRecovery = firstHandler(challenge);+ void firstRecovery.then(firstRecoveryDone, firstRecoveryDone);+ await started;+ const secondRecovery = secondHandler(challenge);+ await waitFor(() => generationSpy.mock.calls.length >= 2);+ releaseRejection();+ await Promise.all([firstRecovery, secondRecovery]);++ expect(+ server.tokenRequests.filter((request) => request.grantType === 'refresh_token'),+ ).toHaveLength(1);+ expect(connection.getOAuthCredentialSetId()).toBe(second.getOAuthCredentialSetId());+ cleanFirst();+ cleanSecond();+ await Promise.all([connection.disconnect(), second.disconnect()]);+ await Promise.all([connection.connect(), second.connect()]);+ const tools = await Promise.all([connection.fetchTools(), second.fetchTools()]);+ expect(tools.every((catalog) => catalog.some((tool) => tool.name === 'echo'))).toBe(true);+ } finally {+ releaseRejection();+ firstRecoveryDone();+ cleanFirst();+ cleanSecond();+ acquireSpy.mockRestore();+ generationSpy.mockRestore();+ await safeDisconnect(second);+ }+ },+ );++ it.each([undefined, false, true])(+ 'joins a token-loader refresh during 401 recovery (coordination: %s)',+ async (oauthRefreshCoordination) => {+ server = await createOAuthMCPServer({+ issueRefreshTokens: true,+ refreshGate: async () => server.issuedTokens.clear(),+ });+ const initial = await storeTokens(tokenStore, server, await issueTokens(server));+ const flowManager = createFlowManager();+ const basic = {+ serverName: SERVER_NAME,+ serverConfig: {+ type: 'streamable-http' as const,+ url: server.url,+ requiresOAuth: true,+ oauthRefreshCoordination,+ },+ };+ const options = {+ useOAuth: true as const,+ user: { id: USER_ID } as IUser,+ flowManager,+ tokenMethods: {+ findToken: tokenStore.findToken,+ createToken: tokenStore.createToken,+ replaceTokenIfCurrent: jest.fn(),+ updateToken: tokenStore.updateToken,+ deleteTokens: tokenStore.deleteTokens,+ },+ };+ connection = await MCPConnectionFactory.create(basic, options);+ const cleanup = MCPConnectionFactory.attachRequestOAuthHandler(basic, options, connection);+ type RecoveryHandler = (challenge: {+ serverUrl: string;+ rejectedCredentialSetId?: string;+ }) => Promise<void>;+ const recover = connection.listeners('oauthReauthenticationRequired')[0] as RecoveryHandler;+ let publicationStarted!: () => void;+ let releasePublication!: () => void;+ let rejectionStarted!: () => void;+ const started = new Promise<void>((resolve) => (publicationStarted = resolve));+ const blocked = new Promise<void>((resolve) => (releasePublication = resolve));+ const rejection = new Promise<void>((resolve) => (rejectionStarted = resolve));+ const acquireLease = flowManager.acquireLease.bind(flowManager);+ const acquireSpy = jest.spyOn(flowManager, 'acquireLease').mockImplementation((...args) => {+ rejectionStarted();+ return acquireLease(...args);+ });+ try {+ server.issuedTokens.delete(initial.access_token);+ await tokenStore.updateToken(+ { userId: USER_ID, type: 'mcp_oauth', identifier: `mcp:${SERVER_NAME}` },+ { expiresIn: -1 },+ );+ const loading = new TokenLoadingFactory(basic, {+ ...options,+ flowManager: createFlowManager(),+ onOAuthCredentialsChanging: async () => async () => {+ publicationStarted();+ await blocked;+ return 'loader-publication';+ },+ }).loadTokens();+ void loading.catch(() => undefined);+ await started;+ const recovering = recover({+ serverUrl: server.url,+ rejectedCredentialSetId: initial.credential_set_id,+ });+ void recovering.catch(() => undefined);+ await rejection;+ releasePublication();+ const [loaded] = await Promise.all([loading, recovering]);++ expect(+ server.tokenRequests.filter((request) => request.grantType === 'refresh_token'),+ ).toHaveLength(1);+ expect(server.issuedTokens.has(loaded!.access_token)).toBe(true);+ cleanup();+ await connection.disconnect();+ await connection.connect();+ expect(loaded?.credential_set_id).toBe(connection.getOAuthCredentialSetId());+ expect((await connection.fetchTools()).some((tool) => tool.name === 'echo')).toBe(true);+ } finally {+ releasePublication();+ cleanup();+ acquireSpy.mockRestore();+ }+ },+ );+it('lets an in-flight request finish before a concurrent OAuth reconnect', async () => {let markSlowRequestStarted: (() => void) | undefined;let releaseFirstSlowRequest: (() => void) | undefined;@@ -904,6 +1147,15 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (expect(oauthStart).toHaveBeenCalledTimes(1);const authorizationUrl = new URL(oauthStart.mock.calls[0][0]);expect(authorizationUrl.searchParams.get('resource')).toBe(server.resourceUrl);+ await expect(+ MCPTokenStorage.hasStoredAuthorization({+ userId: USER_ID,+ serverName: SERVER_NAME,+ findToken: tokenStore.findToken,+ validateClientBinding: (clientInfo, metadata) =>+ MCPOAuthHandler.assertStoredClientBinding(SERVER_NAME, server.url, clientInfo, metadata),+ }),+ ).resolves.toBe(false);});it('does not silently refresh an SDK insufficient_scope challenge before starting OAuth', async () => {diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.tsindex a9893fbea8..4c9916dd9a 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts@@ -2349,6 +2349,9 @@ describe('MCPConnectionFactory', () => {await handler(challenge);expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);+ expect(mockMCPTokenStorage.markAuthorizationRejected).toHaveBeenCalledWith(+ expect.objectContaining({ credentialSetId: 'grant-1' }),+ );expect(mockMCPTokenStorage.isCurrentAccessToken).toHaveBeenCalledWith(expect.objectContaining({ accessToken: 'renewed-access', credentialSetId: 'grant-1' }),);@@ -2801,10 +2804,13 @@ describe('MCPConnectionFactory', () => {// persistent `mockImplementation`) ensures this never-resolving promise// does not leak into later tests' default mock behavior.let resolveRefresh: ((tokens: MCPOAuthTokens) => void) | undefined;+ let started: (() => void) | undefined;+ const refreshStarted = new Promise<void>((resolve) => (started = resolve));mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce(() =>new Promise<MCPOAuthTokens>((res) => {resolveRefresh = res;+ started?.();}),);mockConnectionInstance.isConnected.mockResolvedValue(false);@@ -2829,7 +2835,7 @@ describe('MCPConnectionFactory', () => {const second = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });// Let the in-flight lock register, then resolve the single redemption.- await Promise.resolve();+ await refreshStarted;resolveRefresh!(refreshedTokens);await Promise.all([first, second]);@@ -2905,6 +2911,53 @@ describe('MCPConnectionFactory', () => {},);+ it('coalesces the common storage refresh while timing out its local waiters', async () => {+ jest.useFakeTimers();+ let releaseRejection!: () => void;+ const blocked = new Promise<void>((resolve) => (releaseRejection = resolve));+ mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce(async () => {+ await blocked;+ return null;+ });+ const factory = new InspectableMCPConnectionFactory(+ {+ serverName: 'test-server',+ serverConfig: { type: 'sse', url: 'https://api.example.com', initTimeout: 5000 },+ },+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ replaceTokenIfCurrent: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ },+ );+ try {+ const first = factory.attemptSilentTokenRefreshForTest('rejected-generation');+ const second = factory.attemptSilentTokenRefreshForTest('rejected-generation');+ void first.catch(() => undefined);+ void second.catch(() => undefined);+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledWith(+ expect.objectContaining({ rejectedCredentialSetId: 'rejected-generation' }),+ );+ await jest.advanceTimersByTimeAsync(2001);+ await expect(first).rejects.toMatchObject({ name: 'MCPTokenRefreshUnavailableError' });+ await expect(second).rejects.toMatchObject({ name: 'MCPTokenRefreshUnavailableError' });+ releaseRejection();+ await jest.advanceTimersByTimeAsync(0);+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);+ } finally {+ releaseRejection();+ jest.useRealTimers();+ }+ });+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,// but the shared lock must remain briefly while the underlying abortable@@ -3439,9 +3492,25 @@ describe('MCPConnectionFactory', () => {error: new Error('Non-200 status code (401)'),};- await Promise.all([requestOAuthHandler!(challenge), requestOAuthHandler!(challenge)]);- await requestOAuthHandler!(challenge);- await requestOAuthHandler!(challenge);+ const rejection = (rejectedCredentialSetId: string) => ({+ ...challenge,+ rejectedCredentialSetId,+ });+ await Promise.all([+ requestOAuthHandler!(rejection('original-generation')),+ requestOAuthHandler!(rejection('original-generation')),+ ]);+ await requestOAuthHandler!(rejection('refreshed-generation'));+ await requestOAuthHandler!(rejection('interactive-generation'));++ expect(+ mockMCPTokenStorage.markAuthorizationRejected.mock.calls.map(+ ([params]) => params.credentialSetId,+ ),+ ).toEqual(['refreshed-generation', 'interactive-generation']);+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledWith(+ expect.objectContaining({ rejectedCredentialSetId: 'original-generation' }),+ );expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalledTimes(1);@@ -3522,6 +3591,9 @@ describe('MCPConnectionFactory', () => {expect(mockFlowManager.createFlow).not.toHaveBeenCalled();expect(oauthStart).not.toHaveBeenCalled();expect(oauthEnd).not.toHaveBeenCalled();+ expect(mockMCPTokenStorage.markAuthorizationRejected).toHaveBeenCalledWith(+ expect.objectContaining({ credentialSetId: 'rejected-generation' }),+ );expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthFailed',expect.objectContaining({ message: 'OAuth reauthentication required' }),@@ -5189,6 +5261,43 @@ describe('MCPConnectionFactory', () => {expect(mockMCPConnection).toHaveBeenCalledTimes(1);});+ it('records OAuth rejection when tools/list fails after a successful handshake', async () => {+ mockFlowManager.createFlowWithHandler.mockResolvedValue({+ access_token: 'rejected-access',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ credential_set_id: 'rejected-generation',+ });+ mockConnectionInstance.connect.mockResolvedValue(undefined);+ mockConnectionInstance.isConnected.mockResolvedValue(true);+ mockConnectionInstance.fetchOrderedToolsSnapshot = jest.fn().mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError: Object.assign(new Error('unauthorized'), { status: 401 }),+ });+ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ replaceTokenIfCurrent: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ },+ );++ expect(result.oauthRequired).toBe(true);+ expect(result.tools).toBeNull();+ expect(mockMCPTokenStorage.markAuthorizationRejected).toHaveBeenCalledWith(+ expect.objectContaining({ credentialSetId: 'rejected-generation' }),+ );+ });+it('does not expose an incomplete discovery snapshot as authoritative', async () => {const basicOptions = {serverName: 'test-server',@@ -5621,6 +5730,90 @@ describe('MCPConnectionFactory', () => {expect(Date.now() - start).toBeLessThan(2000);});+ describe('OAuth rejection persistence', () => {+ it.each([+ ['handshake', 'deadline'],+ ['handshake', 'abort'],+ ['tools/list', 'deadline'],+ ['tools/list', 'abort'],+ ])('hands off %s rejection persistence when discovery stops at %s', async (phase, stop) => {+ jest.useFakeTimers();+ let finishRecording!: () => void;+ let recordingStarted!: () => void;+ const started = new Promise<void>((resolve) => (recordingStarted = resolve));+ const pendingWrite = new Promise<void>((resolve) => (finishRecording = resolve));+ mockMCPTokenStorage.markAuthorizationRejected.mockImplementationOnce(() => {+ recordingStarted();+ return pendingWrite;+ });+ const controller = new AbortController();+ const onDiscoveryDetached = jest.fn();+ mockFlowManager.createFlowWithHandler.mockResolvedValue({+ access_token: 'rejected-access',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ credential_set_id: 'rejected-generation',+ });+ let oauthHandler: (() => void) | undefined;+ mockConnectionInstance.once.mockImplementation((event, handler) => {+ if (event === 'oauthRequired') oauthHandler = handler as () => void;+ return mockConnectionInstance;+ });+ mockConnectionInstance.connect.mockImplementation(async () => {+ if (phase === 'handshake') {+ oauthHandler?.();+ throw new Error('OAuth required');+ }+ });+ mockConnectionInstance.isConnected.mockResolvedValue(true);+ mockConnectionInstance.fetchOrderedToolsSnapshot = jest.fn().mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError: Object.assign(new Error('unauthorized'), { status: 401 }),+ });+ try {+ const discovery = MCPConnectionFactory.discoverTools(+ { serverName: 'test-server', serverConfig: mockServerConfig },+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ replaceTokenIfCurrent: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ ...(stop === 'deadline'+ ? { deadlineMs: Date.now() + 100 }+ : { signal: controller.signal }),+ onDiscoveryDetached,+ },+ );+ await started;+ if (stop === 'deadline') await jest.advanceTimersByTimeAsync(100);+ else controller.abort();+ const result = await discovery;+ expect(result.tools).toBeNull();+ expect(result.oauthRequired).toBe(true);+ expect(mockMCPConnection).toHaveBeenCalledTimes(1);+ expect(onDiscoveryDetached).toHaveBeenCalledTimes(1);+ const [detached] = onDiscoveryDetached.mock.calls[0] as [Promise<void>];+ let finished = false;+ void detached.then(() => (finished = true));+ await Promise.resolve();+ expect(finished).toBe(false);+ finishRecording();+ await detached;+ expect(finished).toBe(true);+ } finally {+ finishRecording();+ jest.useRealTimers();+ }+ });+ });+describe('OAuth token loading', () => {const oauthDiscoveryOptions = (bounds: {deadlineMs?: number;@@ -5633,6 +5826,7 @@ describe('MCPConnectionFactory', () => {tokenMethods: {findToken: jest.fn(),createToken: jest.fn(),+ replaceTokenIfCurrent: jest.fn(),updateToken: jest.fn(),deleteTokens: jest.fn(),},diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.tsindex 454d7014aa..3d12cf4f67 100644--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts@@ -8,6 +8,7 @@import { Keyv } from 'keyv';import type { TokenMethods } from '@librechat/data-schemas';import type { MCPOAuthTokens } from '~/mcp/oauth';+import type { FlowLease } from '~/flow/manager';import {MCPTokenStorage,MCPTokenRefreshUnavailableError,@@ -96,6 +97,123 @@ describe('MCPTokenStorage', () => {).resolves.toBe(true);});+ it.each([false, true])(+ 'rejects a known-rejected generation even with usable refresh credentials (access removed: %s)',+ async (removeAccess) => {+ await createBoundToken(store, {+ userId: 'u1',+ type: 'mcp_oauth',+ identifier: 'mcp:srv1',+ token: 'enc:rejected-access',+ expiresIn: 3600,+ });+ await createBoundToken(store, {+ userId: 'u1',+ type: 'mcp_oauth_refresh',+ identifier: 'mcp:srv1:refresh',+ token: 'enc:usable-refresh',+ expiresIn: 3600,+ });+ await storeClient();+ await MCPTokenStorage.markAuthorizationRejected({+ userId: 'u1',+ serverName: 'srv1',+ credentialSetId,+ findToken: store.findToken,+ updateToken: store.updateToken,+ });+ if (removeAccess) {+ await store.deleteToken({ userId: 'u1', type: 'mcp_oauth', identifier: 'mcp:srv1' });+ }++ await expect(+ MCPTokenStorage.hasStoredAuthorization({+ userId: 'u1',+ serverName: 'srv1',+ findToken: store.findToken,+ validateClientBinding,+ }),+ ).resolves.toBe(false);+ const client = await store.findToken({+ userId: 'u1',+ type: 'mcp_oauth_client',+ identifier: 'mcp:srv1:client',+ });+ expect(client?.metadata).toMatchObject({+ ...storedBindingMetadata,+ rejected_credential_set_id: credentialSetId,+ });+ },+ );++ it('does not poison a newer authorization while recording an older rejection', async () => {+ await storeClient();+ const updateToken: TokenMethods['updateToken'] = async (query, update) => {+ await storeClient({ ...storedBindingMetadata, credential_set_id: 'new-generation' });+ return store.updateToken(query, update);+ };+ await MCPTokenStorage.markAuthorizationRejected({+ userId: 'u1',+ serverName: 'srv1',+ credentialSetId,+ findToken: store.findToken,+ updateToken,+ });+ const client = await store.findToken({+ userId: 'u1',+ type: 'mcp_oauth_client',+ identifier: 'mcp:srv1:client',+ });+ expect(client?.metadata).toEqual({+ ...storedBindingMetadata,+ credential_set_id: 'new-generation',+ });+ });++ it('accepts replacement credentials despite a carried-over older rejection marker', async () => {+ await createBoundToken(store, {+ userId: 'u1',+ type: 'mcp_oauth',+ identifier: 'mcp:srv1',+ token: 'enc:current-access',+ expiresIn: 3600,+ });+ await storeClient({+ ...storedBindingMetadata,+ rejected_credential_set_id: 'older-generation',+ });+ await expect(+ MCPTokenStorage.hasStoredAuthorization({+ userId: 'u1',+ serverName: 'srv1',+ findToken: store.findToken,+ validateClientBinding,+ }),+ ).resolves.toBe(true);+ });++ it('waits for credential persistence before recording rejection', async () => {+ await storeClient();+ let grantLease: ((lease: FlowLease) => void) | undefined;+ const release = jest.fn(async () => undefined);+ const flowManager = {+ acquireLease: jest.fn(() => new Promise<FlowLease>((resolve) => (grantLease = resolve))),+ };+ const findToken = jest.fn(store.findToken);+ const pending = MCPTokenStorage.markAuthorizationRejected({+ userId: 'u1',+ serverName: 'srv1',+ credentialSetId,+ findToken,+ updateToken: store.updateToken,+ flowManager,+ });+ expect(findToken).not.toHaveBeenCalled();+ grantLease?.({ generation: 0, release });+ await pending;+ expect(release).toHaveBeenCalledTimes(1);+ });+it('rejects legacy credentials without binding metadata', async () => {await store.createToken({userId: 'u1',@@ -2494,8 +2612,12 @@ describe('MCPTokenStorage', () => {await peerRotates(serverName, 3);const flowManager = new FlowStateManager(new Keyv(), { ttl: 30000, ci: true });const acquire = flowManager.acquireLease.bind(flowManager);+ let flightAcquired = false;jest.spyOn(flowManager, 'acquireLease').mockImplementation(async (id, options) => {- if (id === getMCPOAuthLeaseId('u1', serverName)) await peerRotates(serverName, 4);+ if (id === getMCPOAuthRefreshFlightLeaseId('u1', serverName)) flightAcquired = true;+ if (flightAcquired && id === getMCPOAuthLeaseId('u1', serverName)) {+ await peerRotates(serverName, 4);+ }return acquire(id, options);});const onTokensAdopted = jest.fn();@@ -3385,6 +3507,96 @@ describe('MCPTokenStorage', () => {}});+ it('never redeems after rejection persistence outlives the common storage flight', async () => {+ jest.useFakeTimers({ doNotFake: ['setImmediate', 'nextTick'] });+ let releaseWrite!: () => void;+ const blocked = new Promise<void>((resolve) => (releaseWrite = resolve));+ let recording = false;+ try {+ const serverName = 'stalled-rejection';+ await seedRefreshableTokens(serverName);+ const updateToken: TokenMethods['updateToken'] = async (...args) => {+ recording = true;+ await blocked;+ return store.updateToken(...args);+ };+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(2));+ const params = {+ ...refreshParams(refreshTokens, serverName),+ coordinateRefresh: false,+ updateToken,+ };+ const recovering = MCPTokenStorage.forceRefreshTokens({+ ...params,+ rejectedCredentialSetId: credentialSetId,+ });+ await waitFor(() => recording);+ const loading = MCPTokenStorage.getTokens(params);+ await new Promise((resolve) => setImmediate(resolve));+ jest.advanceTimersByTime(MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS + 1);+ releaseWrite();+ await expect(Promise.all([recovering, loading])).resolves.toEqual([null, null]);+ expect(refreshTokens).not.toHaveBeenCalled();+ await expect(+ MCPTokenStorage.hasStoredAuthorization({+ userId: 'u1',+ serverName,+ findToken: store.findToken,+ validateClientBinding: () => undefined,+ }),+ ).resolves.toBe(false);+ } finally {+ releaseWrite();+ jest.useRealTimers();+ }+ });++ it.each([false, true])(+ 'records a joiner rejection when the token-loader refresh fails (publication: %s)',+ async (publicationFailure) => {+ const serverName = `mixed-refresh-failure-${publicationFailure}`;+ await seedRefreshableTokens(serverName);+ let finishRefresh!: (tokens: MCPOAuthTokens) => void;+ let failRefresh!: (error: Error) => void;+ const refreshTokens = jest.fn(+ () =>+ new Promise<MCPOAuthTokens>((resolve, reject) => {+ finishRefresh = resolve;+ failRefresh = reject;+ }),+ );+ const params = {+ ...refreshParams(refreshTokens, serverName),+ coordinateRefresh: false,+ flowManager: new FlowStateManager(new Keyv(), { ttl: 30000, ci: true }),+ onRefreshSuccess: async () => {+ if (publicationFailure) throw new Error('publication unavailable');+ },+ };+ const loading = MCPTokenStorage.getTokens(params);+ void loading.catch(() => undefined);+ await waitFor(() => refreshTokens.mock.calls.length === 1);+ const recovering = MCPTokenStorage.forceRefreshTokens({+ ...params,+ rejectedCredentialSetId: credentialSetId,+ });+ void recovering.catch(() => undefined);+ if (publicationFailure) finishRefresh(rotatedTokens(2));+ else failRefresh(new Error('provider unavailable'));+ await expect(loading).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);+ await expect(recovering).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);+ expect(refreshTokens).toHaveBeenCalledTimes(1);+ await expect(+ MCPTokenStorage.hasStoredAuthorization({+ userId: 'u1',+ serverName,+ findToken: store.findToken,+ validateClientBinding: () => undefined,+ }),+ ).resolves.toBe(false);+ },+ );+it('runs onRefreshSuccess on the shared redemption even after the initiating waiter aborted', async () => {await seedRefreshableTokens('hook-srv');@@ -3455,6 +3667,69 @@ describe('MCPTokenStorage', () => {expect(onRefreshPreparing).toHaveBeenCalledTimes(1);});+ it.each([false, true])(+ 'preserves a rejection recorded during redemption when publication rolls back (refresh only: %s)',+ async (refreshOnly) => {+ const serverName = `rejected-rollback-${refreshOnly}`;+ await seedRefreshableTokens(serverName);+ if (refreshOnly) {+ await store.deleteToken({+ userId: 'u1',+ type: 'mcp_oauth',+ identifier: `mcp:${serverName}`,+ });+ } else {+ await store.updateToken(+ { userId: 'u1', type: 'mcp_oauth', identifier: `mcp:${serverName}` },+ { expiresIn: 3600 },+ );+ }+ const flowManager = new FlowStateManager(new Keyv(), { ttl: 30000, ci: true });+ let resolveRefresh!: (tokens: MCPOAuthTokens) => void;+ const refreshTokens = jest.fn(+ () => new Promise<MCPOAuthTokens>((resolve) => (resolveRefresh = resolve)),+ );+ const pending = MCPTokenStorage.forceRefreshTokens({+ ...refreshParams(refreshTokens, serverName),+ flowManager,+ onRefreshSuccess: async () => {+ throw new Error('generation publication failed');+ },+ });+ void pending.catch(() => undefined);+ await waitFor(() => refreshTokens.mock.calls.length === 1);+ await MCPTokenStorage.markAuthorizationRejected({+ userId: 'u1',+ serverName,+ credentialSetId,+ flowManager,+ findToken: store.findToken,+ updateToken: store.updateToken,+ });++ resolveRefresh(rotatedTokens(2));+ await expect(pending).rejects.toBeInstanceOf(MCPTokenRefreshUnavailableError);++ const client = await store.findToken({+ userId: 'u1',+ type: 'mcp_oauth_client',+ identifier: `mcp:${serverName}:client`,+ });+ expect(client?.metadata).toMatchObject({+ credential_set_id: credentialSetId,+ rejected_credential_set_id: credentialSetId,+ });+ await expect(+ MCPTokenStorage.hasStoredAuthorization({+ userId: 'u1',+ serverName,+ findToken: store.findToken,+ validateClientBinding: () => undefined,+ }),+ ).resolves.toBe(false);+ },+ );+it('removes refreshed credentials when their authorization fence cannot be published', async () => {await seedRefreshableTokens('unfenced-srv');const onRefreshSuccess = jest.fn().mockRejectedValue(new Error('generation unavailable'));diff --git a/packages/api/src/mcp/oauth/tokens.ts b/packages/api/src/mcp/oauth/tokens.tsindex ce58734728..d3f7bc7c8f 100644--- a/packages/api/src/mcp/oauth/tokens.ts+++ b/packages/api/src/mcp/oauth/tokens.ts@@ -362,7 +362,56 @@ export class MCPTokenStorage {};}- /** Returns whether storage contains a currently usable, generation-bound authorization. */+ /** Records upstream rejection without invalidating a newer refresh or interactive authorization. */+ static async markAuthorizationRejected({+ userId,+ serverName,+ credentialSetId,+ findToken,+ updateToken,+ flowManager,+ persistenceWaitTimeoutMs,+ }: {+ userId: string;+ serverName: string;+ credentialSetId: string;+ findToken: TokenMethods['findToken'];+ updateToken: TokenMethods['updateToken'];+ flowManager?: Pick<FlowStateManager, 'acquireLease'>;+ persistenceWaitTimeoutMs?: number;+ }): Promise<void> {+ const lease = flowManager+ ? await flowManager.acquireLease(getMCPOAuthLeaseId(userId, serverName), {+ waitMs: this.resolvePersistenceWaitMs(persistenceWaitTimeoutMs),+ })+ : undefined;+ if (flowManager && !lease) {+ throw new MCPTokenStorageUnavailableError(+ serverName,+ new Error('OAuth persistence fence unavailable'),+ );+ }+ const scope = {+ userId,+ type: 'mcp_oauth_client',+ identifier: `mcp:${serverName}:client`,+ metadataCredentialSetId: credentialSetId,+ };+ try {+ const client = await findToken(scope);+ if (!client || getTokenMetadata(client).rejected_credential_set_id === credentialSetId) {+ return;+ }+ await updateToken(+ { ...scope, token: client.token },+ { metadata: { ...getTokenMetadata(client), rejected_credential_set_id: credentialSetId } },+ );+ } finally {+ if (lease) await this.releaseRefreshFlight(lease, this.getLogPrefix(userId, serverName));+ }+ }++ /** Returns whether storage contains a usable, generation-bound authorization not rejected upstream. */static async hasStoredAuthorization({userId,serverName,@@ -384,6 +433,12 @@ export class MCPTokenStorage {findToken({ userId, type: 'mcp_oauth_client', identifier: `${identifier}:client` }),]);const clientCredentialSetId = getCredentialSetId(clientInfoData);+ if (+ clientCredentialSetId &&+ getTokenMetadata(clientInfoData).rejected_credential_set_id === clientCredentialSetId+ ) {+ return false;+ }const accessCredentialSetId = getCredentialSetId(accessTokenData);let hasUsableAuthorization = false;if (accessTokenData) {@@ -1021,7 +1076,18 @@ export class MCPTokenStorage {const inflight = this.inflightRefreshes.get(refreshKey);if (inflight) {logger.debug(`${logPrefix} Joining in-flight token refresh`);- return this.raceWithAbort(inflight, signal);+ if (!params.rejectedCredentialSetId || !params.updateToken) {+ return this.raceWithAbort(inflight, signal);+ }+ const rejection = this.recordRefreshRejection(params);+ const joined = (async () => {+ try {+ return await inflight;+ } finally {+ await rejection;+ }+ })();+ return this.raceWithAbort(joined, signal);}if (!refreshTokens) {@@ -1057,6 +1123,10 @@ export class MCPTokenStorage {logger.debug(`${logPrefix} Skipping token refresh during OAuth teardown`);return null;}+ if (params.rejectedCredentialSetId && params.updateToken) {+ await this.recordRefreshRejection(params);+ if (executionController.signal.aborted) return null;+ }/** Serialize with the redemptions other replicas may be running for this credential. */let flight: MCPRefreshFlight | null = null;if (flowManager && params.coordinateRefresh === true) {@@ -1196,6 +1266,27 @@ export class MCPTokenStorage {return this.raceWithAbort(refreshPromise, signal);}+ /** Records rejection inside the common refresh lifetime, without blocking entry-point coalescing. */+ private static async recordRefreshRejection(params: GetTokensParams): Promise<void> {+ if (!params.rejectedCredentialSetId || !params.updateToken) return;+ try {+ await this.markAuthorizationRejected({+ userId: params.userId,+ serverName: params.serverName,+ credentialSetId: params.rejectedCredentialSetId,+ findToken: params.findToken,+ updateToken: params.updateToken,+ flowManager: params.flowManager,+ persistenceWaitTimeoutMs: params.persistenceWaitTimeoutMs,+ });+ } catch (error) {+ logger.warn(+ `${this.getLogPrefix(params.userId, params.serverName)} Failed to record upstream OAuth rejection`,+ error,+ );+ }+ }+/*** Serializes refresh-token redemption for one credential across replicas.*@@ -1710,10 +1801,10 @@ export class MCPTokenStorage {deleteTokens,findToken,clientInfo,+ /** Rejection evidence may change during redemption; read its rollback snapshot under the lease. */existingTokens: {accessToken: existingAccessToken ?? undefined,refreshToken: refreshTokenData,- clientInfoToken: clientInfoData,},metadata: storedClientMetadata,expectedCredentialSetId: refreshCredentialSetId,diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.tsindex 57f2c1764c..000a21c896 100644--- a/packages/api/src/mcp/oauth/types.ts+++ b/packages/api/src/mcp/oauth/types.ts@@ -32,6 +32,8 @@ export type OAuthClientSource = 'configured' | 'dynamic';export interface OAuthStoredClientMetadata extends OAuthMetadata {/** Random identifier shared by the access, refresh, and client records from one authorization. */credential_set_id?: string;+ /** Internal upstream rejection marker, valid only while it matches this credential generation. */+ rejected_credential_set_id?: string;/** Canonical MCP server URL the tokens and client registration are bound to. */server_url: string;/** Whether the client came from server configuration or dynamic client registration. */