Skip to content

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

🛂 fix: Back Off MCP OAuth Discovery (#15783)

Danny Avila6965f8e7d318
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js
index 607f7ce605..ca96b88e7a 100644
--- a/api/server/controllers/UserController.js
+++ b/api/server/controllers/UserController.js
@@ -13,6 +13,7 @@ const {
waitForGenerationPersistence,
deleteAllSharedLinksWithCleanup,
revokeUserCodeEnvironmentWorkers,
+ finalizeMCPAuthorizationMutation,
} = require('@librechat/api');
const { Tools, Constants, FileSources, ResourceType } = require('librechat-data-provider');
const { updateUserPluginAuth, deleteUserPluginAuth } = require('~/server/services/PluginService');
@@ -21,6 +22,10 @@ const { verifyEmail, resendVerificationEmail } = require('~/server/services/Auth
const { getMCPManager } = require('~/config');
const { maybeUninstallOAuthMCP } = require('~/server/services/MCP/oauthCleanup');
const { invalidateCachedTools } = require('~/server/services/Config/getCachedTools');
+const {
+ clearMCPAuthorizationFenceRetry,
+ persistMCPAuthorizationFenceRetry,
+} = require('~/server/services/MCPAuthorizationFenceRetry');
const { processDeleteRequest } = require('~/server/services/Files/process');
const subagentThreadTaskStore = require('~/server/services/Endpoints/agents/subagentThreadStore');
const {
@@ -252,6 +257,18 @@ const updateUserPluginsController = async (req, res) => {
let message;
/** @type {IPluginAuth | Error} */
let authService;
+ const mcpCredentialMutationResults = [];
+ let mcpTeardown = false;
+ const mcpScope = pluginKey.startsWith(Constants.mcp_prefix)
+ ? {
+ userId: user.id,
+ serverName: pluginKey.replace(Constants.mcp_prefix, ''),
+ }
+ : null;
+ /** Write durable fence intent before the first credential write. A crash or retry-marker
+ * outage therefore cannot commit credentials that other replicas continue to authorize. */
+ const publicationRetryVersion =
+ mcpScope == null ? undefined : await persistMCPAuthorizationFenceRetry(mcpScope);
if (pluginKey === Tools.web_search) {
/** @type {TCustomConfig['webSearch']} */
@@ -275,6 +292,9 @@ const updateUserPluginsController = async (req, res) => {
break;
}
}
+ if (isMCPTool) {
+ mcpCredentialMutationResults.push(authService);
+ }
}
} else if (action === 'uninstall') {
// const isMCPTool was defined earlier
@@ -289,34 +309,8 @@ const updateUserPluginsController = async (req, res) => {
);
({ status, message } = normalizeHttpError(authService));
}
- const serverName = pluginKey.replace(Constants.mcp_prefix, '');
- try {
- await invalidateCachedTools({ userId: user.id, serverName });
- } catch (error) {
- logger.error(
- `[updateUserPluginsController] Error fencing MCP connection before OAuth teardown for user ${user.id}:`,
- error,
- );
- }
- try {
- await getMCPManager()?.disconnectUserConnection(user.id, serverName);
- } catch (error) {
- logger.error(
- `[updateUserPluginsController] Error disconnecting MCP connection before OAuth teardown for user ${user.id}:`,
- error,
- );
- }
- try {
- // if the MCP server uses OAuth, perform a full cleanup and token revocation
- await maybeUninstallOAuthMCP(user.id, pluginKey, appConfig);
- } catch (error) {
- logger.error(
- `[updateUserPluginsController] Error uninstalling OAuth MCP for ${pluginKey}:`,
- error,
- );
- status = 503;
- message = 'OAuth credential cleanup is temporarily unavailable';
- }
+ mcpCredentialMutationResults.push(authService);
+ mcpTeardown = true;
} else {
// This handles:
// 1. Web_search uninstall (entries include every configured field).
@@ -328,48 +322,66 @@ const updateUserPluginsController = async (req, res) => {
logger.error('[authService] Error deleting specific auth key:', authService);
({ status, message } = normalizeHttpError(authService));
}
+ if (isMCPTool) {
+ mcpCredentialMutationResults.push(authService);
+ }
}
}
}
- if (status === 200) {
- // If auth was updated successfully, disconnect MCP sessions as they might use these credentials
- if (pluginKey.startsWith(Constants.mcp_prefix)) {
- try {
- const mcpManager = getMCPManager();
- // Extract server name from pluginKey (format: "mcp_<serverName>")
- const serverName = pluginKey.replace(Constants.mcp_prefix, '');
- if (mcpManager) {
- logger.info(
- `[updateUserPluginsController] Attempting disconnect of MCP server "${serverName}" for user ${user.id} after plugin auth update.`,
- );
- }
- let invalidationError;
- try {
- await invalidateCachedTools({ userId: user.id, serverName });
- } catch (error) {
- invalidationError = error;
- }
- try {
- await mcpManager?.disconnectUserConnection(user.id, serverName);
- } catch (error) {
- logger.error(
- `[updateUserPluginsController] Error disconnecting MCP connection for user ${user.id} after plugin auth update:`,
- error,
- );
- }
- if (invalidationError) {
- throw invalidationError;
- }
- } catch (disconnectError) {
- logger.error(
- `[updateUserPluginsController] Error fencing MCP connection for user ${user.id} after plugin auth update:`,
- disconnectError,
- );
- // A credential mutation is not safely published until the shared generation fence moves.
- throw disconnectError;
- }
+ // Every committed MCP credential write advances the fence, including a partial batch whose
+ // later field failed. Otherwise another worker can retain a stale authorization decision.
+ if (mcpScope != null) {
+ try {
+ const mcpManager = getMCPManager();
+ await finalizeMCPAuthorizationMutation(
+ {
+ scope: mcpScope,
+ mutationResults: mcpCredentialMutationResults,
+ publicationRetryVersion,
+ teardown: mcpTeardown,
+ },
+ {
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ clearLocalRecovery: (changedUserId, changedServerName) =>
+ mcpManager?.clearCatalogRecoveryState?.(changedUserId, changedServerName),
+ disconnectUserConnection: (changedUserId, changedServerName) =>
+ mcpManager?.disconnectUserConnection(changedUserId, changedServerName),
+ retryDelaysMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryMs,
+ attemptTimeoutMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceTimeoutMs,
+ onDisconnectError: (error) =>
+ logger.error(
+ `[updateUserPluginsController] Error disconnecting MCP connection for user ${user.id} after plugin auth update:`,
+ error,
+ ),
+ ...(mcpTeardown && {
+ afterDisconnect: async () => {
+ try {
+ await maybeUninstallOAuthMCP(user.id, pluginKey, appConfig);
+ } catch (error) {
+ logger.error(
+ `[updateUserPluginsController] Error uninstalling OAuth MCP for ${pluginKey}:`,
+ error,
+ );
+ status = 503;
+ message = 'OAuth credential cleanup is temporarily unavailable';
+ }
+ },
+ }),
+ },
+ );
+ } catch (disconnectError) {
+ logger.error(
+ `[updateUserPluginsController] Error fencing MCP connection for user ${user.id} after plugin auth update:`,
+ disconnectError,
+ );
+ // A credential mutation is not safely published until the shared generation fence moves.
+ throw disconnectError;
}
+ }
+ if (status === 200) {
return res.status(status).send();
}
diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
index a869113e22..a7676324cf 100644
--- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
+++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
@@ -7,6 +7,8 @@ const mockGetLogStores = jest.fn();
const mockGetMCPManager = jest.fn();
const mockGetFlowStateManager = jest.fn();
const mockGetMCPServersRegistry = jest.fn();
+const mockPersistMCPAuthorizationFenceRetry = jest.fn();
+const mockClearMCPAuthorizationFenceRetry = jest.fn();
jest.mock('@librechat/data-schemas', () => ({
...jest.requireActual('@librechat/data-schemas'),
@@ -88,6 +90,11 @@ jest.mock('~/server/services/Config/getCachedTools', () => ({
invalidateCachedTools: (...args) => mockInvalidateCachedTools(...args),
}));
+jest.mock('~/server/services/MCPAuthorizationFenceRetry', () => ({
+ persistMCPAuthorizationFenceRetry: (...args) => mockPersistMCPAuthorizationFenceRetry(...args),
+ clearMCPAuthorizationFenceRetry: (...args) => mockClearMCPAuthorizationFenceRetry(...args),
+}));
+
jest.mock('~/server/services/Files/process', () => ({
processDeleteRequest: jest.fn().mockResolvedValue({ deletedFileIds: [], failedFileIds: [] }),
}));
@@ -187,6 +194,8 @@ const storedOAuthBinding = {
beforeEach(() => {
jest.clearAllMocks();
+ mockPersistMCPAuthorizationFenceRetry.mockResolvedValue('retry-v1');
+ mockClearMCPAuthorizationFenceRetry.mockResolvedValue(undefined);
getTenantId.mockReturnValue(undefined);
mockFindToken.mockImplementation(async ({ type }) => ({
token: `encrypted-${type}`,
@@ -195,6 +204,55 @@ beforeEach(() => {
});
describe('updateUserPluginsController MCP OAuth cleanup', () => {
+ it('does not mutate credentials when durable fence preparation fails', async () => {
+ setupMCPMocks();
+ const { updateUserPluginAuth } = require('~/server/services/PluginService');
+ const error = new Error('retry storage unavailable');
+ mockPersistMCPAuthorizationFenceRetry.mockRejectedValueOnce(error);
+ const req = createRequest();
+ req.body = {
+ pluginKey: 'mcp_test-server',
+ action: 'install',
+ auth: { API_KEY: 'new-key' },
+ };
+
+ const res = createResponse();
+ await updateUserPluginsController(req, res);
+
+ expect(updateUserPluginAuth).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(logger.error).toHaveBeenCalledWith('[updateUserPluginsController]', error);
+ });
+
+ it('advances the fence after a partial MCP credential batch commits', async () => {
+ setupMCPMocks();
+ const { updateUserPluginAuth } = require('~/server/services/PluginService');
+ const laterFailure = Object.assign(new Error('second field failed'), { status: 400 });
+ updateUserPluginAuth.mockResolvedValueOnce({}).mockResolvedValueOnce(laterFailure);
+ const req = createRequest();
+ req.body = {
+ pluginKey: 'mcp_test-server',
+ action: 'install',
+ auth: { API_KEY: 'new-key', ACCOUNT: 'new-account' },
+ };
+
+ const res = createResponse();
+ await updateUserPluginsController(req, res);
+
+ expect(mockPersistMCPAuthorizationFenceRetry.mock.invocationCallOrder[0]).toBeLessThan(
+ updateUserPluginAuth.mock.invocationCallOrder[0],
+ );
+ expect(mockInvalidateCachedTools).toHaveBeenCalledWith({
+ userId: 'user-1',
+ serverName: 'test-server',
+ });
+ expect(mockClearMCPAuthorizationFenceRetry).toHaveBeenCalledWith(
+ { userId: 'user-1', serverName: 'test-server' },
+ 'retry-v1',
+ );
+ expect(res.status).toHaveBeenCalledWith(400);
+ });
+
it('invalidates the shared tool generation even when local disconnect fails', async () => {
const { mcpManager } = setupMCPMocks();
mcpManager.disconnectUserConnection.mockRejectedValue(new Error('local dispose failed'));
diff --git a/api/server/controllers/__tests__/deleteUser.spec.js b/api/server/controllers/__tests__/deleteUser.spec.js
index 10a031bbbe..f625311d49 100644
--- a/api/server/controllers/__tests__/deleteUser.spec.js
+++ b/api/server/controllers/__tests__/deleteUser.spec.js
@@ -138,6 +138,11 @@ jest.mock('~/server/services/Config/getCachedTools', () => ({
invalidateCachedTools: jest.fn(),
}));
+jest.mock('~/server/services/MCPAuthorizationFenceRetry', () => ({
+ clearMCPAuthorizationFenceRetry: jest.fn(),
+ persistMCPAuthorizationFenceRetry: jest.fn(),
+}));
+
jest.mock('~/server/services/Files/process', () => ({
processDeleteRequest: (...args) => mockProcessDeleteRequest(...args),
}));
diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.js
index af66d8d4ce..657c13220f 100644
--- a/api/server/controllers/mcp.js
+++ b/api/server/controllers/mcp.js
@@ -230,11 +230,14 @@ const getMCPTools = async (req, res) => {
}),
oboIdentityContext,
signal: catalogAbortController.signal,
+ recoveryPolicy: req.config?.mcpSettings?.catalogRecovery,
});
} finally {
res.off('close', abortCatalogLoad);
}
const { serverTools: serverToolsMap, serversWithoutTools } = catalogResult;
+ const reauthRequiredServers = catalogResult.reauthRequiredServers ?? new Set();
+ const reauthRequiredGenerations = catalogResult.reauthRequiredGenerations ?? new Map();
if (serversWithoutTools.length > 0) {
logger.debug(
`[getMCPTools] No tools (${serversWithoutTools.length}): ${serversWithoutTools.join(', ')}`,
@@ -251,7 +254,11 @@ const getMCPTools = async (req, res) => {
const server = {
name: serverName,
icon: serverConfig?.iconPath || '',
- authenticated: true,
+ authenticated: !reauthRequiredServers.has(serverName),
+ ...(reauthRequiredServers.has(serverName) && {
+ authorizationState: 'reauth_required',
+ authorizationGeneration: reauthRequiredGenerations.get(serverName),
+ }),
authConfig: [],
tools: [],
};
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js
index dcdf7d8888..94e8a0693c 100644
--- a/api/server/routes/__tests__/mcp.spec.js
+++ b/api/server/routes/__tests__/mcp.spec.js
@@ -33,6 +33,7 @@ const mockRegistryInstance = {
}),
};
let mockMCPUseAllowed = true;
+let mockRequestConfig = {};
const mockLoadMCPServerCatalogs = jest.fn().mockResolvedValue({
serverTools: new Map(),
serversWithoutTools: [],
@@ -168,6 +169,11 @@ jest.mock('~/server/services/MCP/oauthCleanup', () => ({
maybeUninstallOAuthMCP: jest.fn().mockResolvedValue(undefined),
}));
+jest.mock('~/server/services/MCPAuthorizationFenceRetry', () => ({
+ persistMCPAuthorizationFenceRetry: jest.fn().mockResolvedValue(undefined),
+ clearMCPAuthorizationFenceRetry: jest.fn().mockResolvedValue(undefined),
+}));
+
jest.mock('~/config', () => ({
getMCPManager: jest.fn(),
getFlowStateManager: jest.fn(),
@@ -181,6 +187,10 @@ jest.mock('~/cache', () => ({
jest.mock('~/server/middleware', () => ({
requireJwtAuth: (req, res, next) => next(),
+ configMiddleware: (req, res, next) => {
+ req.config = mockRequestConfig;
+ next();
+ },
canAccessMCPServerResource: () => (req, res, next) => next(),
}));
@@ -193,14 +203,22 @@ const mockOAuthCompletion = (tokens) => {
const { MCPOAuthHandler } = require('@librechat/api');
MCPOAuthHandler.completeOAuthFlow.mockImplementation(
async (flowId, _code, flowManager, _headers, persistBeforeComplete) => {
- const storedTokens = await persistBeforeComplete(tokens);
- await flowManager.completeFlow(flowId, 'mcp_oauth', storedTokens);
+ let completed = false;
+ const completePersistedFlow = async (storedTokens) => {
+ await flowManager.completeFlow(flowId, 'mcp_oauth', storedTokens);
+ completed = true;
+ };
+ const storedTokens = await persistBeforeComplete(tokens, completePersistedFlow);
+ if (!completed) {
+ await completePersistedFlow(storedTokens);
+ }
return storedTokens;
},
);
};
const createLeasedMcpManager = (connection, overrides = {}) => ({
+ clearCatalogRecoveryState: jest.fn(),
...overrides,
withUserConnectionLease: jest.fn((_options, useConnection) => useConnection(connection)),
});
@@ -245,6 +263,7 @@ describe('MCP Routes', () => {
currentUser = undefined;
mockResolveAllMcpConfigs.mockResolvedValue({});
mockResolveMcpConfigNames.mockResolvedValue([]);
+ mockRequestConfig = {};
// `clearAllMocks` preserves queued `mockReturnValueOnce` entries. A callback
// test can legitimately leave one unconsumed, which then masks a later test's
// default implementation when this file shares a CI shard with other suites.
@@ -595,6 +614,13 @@ describe('MCP Routes', () => {
describe('GET /:serverName/oauth/callback', () => {
const { MCPOAuthHandler, MCPTokenStorage } = require('@librechat/api');
const { getLogStores } = require('~/cache');
+ const mockTokenStorageCommit = (storedTokens) => {
+ MCPTokenStorage.storeTokens.mockImplementation(async (params) => {
+ const committedTokens = storedTokens ?? params.tokens;
+ await params.onStoreCommitted?.(committedTokens);
+ return committedTokens;
+ });
+ };
beforeEach(() => {
mockRegistryInstance.getServerConfig.mockResolvedValue({});
@@ -895,7 +921,7 @@ describe('MCP Routes', () => {
codeVerifier: 'current-verifier',
});
mockOAuthCompletion({ access_token: 'test-token' });
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
const mockMcpManager = createLeasedMcpManager({
@@ -932,12 +958,15 @@ describe('MCP Routes', () => {
describe('CSRF fallback via active PENDING flow', () => {
it('should proceed when a fresh PENDING flow exists and no cookies are present', async () => {
const flowId = 'test-user-id:test-server';
+ const pendingCreatedAt = Date.now();
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
+ type: 'mcp_get_tokens',
status: 'PENDING',
- createdAt: Date.now(),
+ createdAt: pendingCreatedAt,
}),
completeFlow: jest.fn().mockResolvedValue(true),
+ settleFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
deleteFlow: jest.fn().mockResolvedValue(true),
};
const mockFlowState = {
@@ -956,7 +985,11 @@ describe('MCP Routes', () => {
mockOAuthCompletion({
access_token: 'test-token',
});
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ MCPTokenStorage.storeTokens.mockImplementation(async (params) => {
+ const storedTokens = { ...params.tokens, credential_set_id: 'callback-generation' };
+ await params.onStoreCommitted(storedTokens);
+ return storedTokens;
+ });
mockRegistryInstance.getServerConfig.mockResolvedValue({
url: 'https://override.example.com/{{LIBRECHAT_BODY_CONVERSATIONID}}/mcp',
});
@@ -977,6 +1010,21 @@ describe('MCP Routes', () => {
const basePath = getBasePath();
expect(response.status).toBe(302);
expect(response.headers.location).toContain(`${basePath}/oauth/success`);
+ expect(mockMcpManager.clearCatalogRecoveryState).toHaveBeenCalledWith(
+ 'test-user-id',
+ 'test-server',
+ );
+ expect(require('~/server/services/Config').invalidateCachedTools).toHaveBeenCalledWith({
+ userId: 'test-user-id',
+ serverName: 'test-server',
+ });
+ const oauthCompletionIndex = mockFlowManager.completeFlow.mock.calls.findIndex(
+ ([, type]) => type === 'mcp_oauth',
+ );
+ expect(oauthCompletionIndex).toBeGreaterThanOrEqual(0);
+ expect(
+ mockFlowManager.completeFlow.mock.invocationCallOrder[oauthCompletionIndex],
+ ).toBeLessThan(mockFlowManager.settleFlowIfCurrent.mock.invocationCallOrder[0]);
});
it('should use the merged server config to defer request-scoped post-OAuth reconnect', async () => {
@@ -1009,7 +1057,7 @@ describe('MCP Routes', () => {
mockOAuthCompletion({
access_token: 'test-token',
});
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': mergedServerConfig });
@@ -1077,7 +1125,7 @@ describe('MCP Routes', () => {
mockOAuthCompletion({
access_token: 'test-token',
});
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': mergedServerConfig });
require('@librechat/api').getUserMCPAuthMap.mockResolvedValueOnce({
@@ -1142,7 +1190,7 @@ describe('MCP Routes', () => {
mockOAuthCompletion({
access_token: 'test-token',
});
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': mergedServerConfig });
require('@librechat/api').getUserMCPAuthMap.mockClear();
@@ -1321,7 +1369,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({
url: 'https://mcp.example.com/mcp',
});
@@ -1429,7 +1477,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
require('~/config').getOAuthReconnectionManager.mockReturnValue({
@@ -1477,11 +1525,13 @@ describe('MCP Routes', () => {
return Promise.resolve({
type: 'mcp_get_tokens',
status: 'PENDING',
+ createdAt: 123,
});
}
return Promise.resolve({ status: 'PENDING', createdAt: Date.now() });
}),
completeFlow: jest.fn().mockResolvedValue(true),
+ settleFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
deleteFlow: jest.fn().mockResolvedValue(true),
};
const mockFlowState = {
@@ -1504,7 +1554,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue(storedTokens);
+ mockTokenStorageCommit(storedTokens);
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
require('~/config').getOAuthReconnectionManager.mockReturnValue({
@@ -1531,9 +1581,11 @@ describe('MCP Routes', () => {
});
expect(response.status).toBe(302);
- expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
+ expect(mockFlowManager.settleFlowIfCurrent).toHaveBeenCalledWith(
'tenant:tenant-a:test-user-id:test-server',
'mcp_get_tokens',
+ 123,
+ '',
storedTokens,
);
expect(mockFlowManager.deleteFlow).not.toHaveBeenCalledWith(
@@ -1563,7 +1615,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockResolveAllMcpConfigs.mockResolvedValue({
'test-server': { url: 'https://mcp.example.com/mcp' },
});
@@ -1620,7 +1672,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({
url: 'https://mcp.example.com/mcp',
oauth_headers: { 'X-Registry-Header': 'from-registry' },
@@ -1703,7 +1755,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -1747,7 +1799,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -1809,7 +1861,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue(mockTokens);
+ mockTokenStorageCommit(mockTokens);
mockResolveAllMcpConfigs.mockResolvedValue({
'test-server': {
type: 'streamable-http',
@@ -1904,6 +1956,52 @@ describe('MCP Routes', () => {
expect(mockMcpManager.withUserConnectionLease).not.toHaveBeenCalled();
});
+ it('keeps generation publication inside the token-store rollback boundary', async () => {
+ const flowId = 'test-user-id:test-server';
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING', createdAt: Date.now() }),
+ completeFlow: jest.fn().mockResolvedValue(),
+ deleteFlow: jest.fn().mockResolvedValue(true),
+ };
+ const storedTokens = {
+ access_token: 'stored-access-token',
+ credential_set_id: 'credential-set-new',
+ };
+ MCPOAuthHandler.getFlowState.mockResolvedValue({
+ state: flowId,
+ serverName: 'test-server',
+ userId: 'test-user-id',
+ serverUrl: 'https://mcp.example.com/mcp',
+ metadata: {},
+ clientInfo: {},
+ codeVerifier: 'test-verifier',
+ });
+ mockOAuthCompletion(storedTokens);
+ MCPTokenStorage.storeTokens.mockImplementation(async (params) => {
+ await params.onStoreCommitted(storedTokens);
+ return storedTokens;
+ });
+ mockRegistryInstance.getServerConfig.mockResolvedValue({
+ url: 'https://mcp.example.com/mcp',
+ });
+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
+ require('~/server/services/Config').invalidateCachedTools.mockRejectedValue(
+ new Error('generation unavailable'),
+ );
+
+ const response = await request(app)
+ .get('/api/mcp/test-server/oauth/callback')
+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`])
+ .query({ code: 'test-auth-code', state: flowId });
+
+ expect(response.status).toBe(302);
+ expect(response.headers.location).toContain('/oauth/error?error=callback_failed');
+ expect(MCPTokenStorage.storeTokens).toHaveBeenCalledWith(
+ expect.objectContaining({ onStoreCommitted: expect.any(Function) }),
+ );
+ expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();
+ });
+
it('should use original flow state credentials when storing tokens', async () => {
// mockRegistryInstance is defined at the top of the file
const mockFlowManager = {
@@ -1940,7 +2038,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(flowState);
mockOAuthCompletion(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockTokenStorageCommit();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -2790,16 +2888,21 @@ describe('MCP Routes', () => {
connectionState: 'connected',
requiresOAuth: false,
authorizationState: 'not_required',
+ authorizationGeneration: 'test-generation',
},
server2: {
connectionState: 'disconnected',
requiresOAuth: true,
authorizationState: 'needs_authorization',
+ authorizationGeneration: 'test-generation',
},
},
});
- expect(getMCPSetupData).toHaveBeenCalledWith('test-user-id', expect.any(Object));
+ expect(getMCPSetupData).toHaveBeenCalledWith(
+ 'test-user-id',
+ expect.objectContaining({ appConfig: mockRequestConfig }),
+ );
expect(getServerConnectionStatus).toHaveBeenCalledTimes(2);
});
@@ -2982,6 +3085,38 @@ describe('MCP Routes', () => {
requiresOAuth: true,
authorizationState: 'needs_authorization',
});
+ require('~/server/services/Config').getMCPToolsCacheGeneration.mockResolvedValue(
+ 'generation-2',
+ );
+
+ const response = await request(app).get('/api/mcp/connection/status/oauth-server');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({
+ success: true,
+ serverName: 'oauth-server',
+ connectionStatus: 'requires_auth',
+ requiresOAuth: true,
+ authorizationState: 'needs_authorization',
+ authorizationGeneration: 'generation-2',
+ });
+ });
+
+ it('keeps connection status available when the shared generation cache is unavailable', async () => {
+ getMCPSetupData.mockResolvedValue({
+ mcpConfig: { 'oauth-server': { endpoint: 'http://oauth-server.com' } },
+ appConnections: {},
+ userConnections: {},
+ oauthServers: new Set(['oauth-server']),
+ });
+ getServerConnectionStatus.mockResolvedValue({
+ connectionState: 'requires_auth',
+ requiresOAuth: true,
+ authorizationState: 'needs_authorization',
+ });
+ require('~/server/services/Config').getMCPToolsCacheGeneration.mockRejectedValueOnce(
+ new Error('cache unavailable'),
+ );
const response = await request(app).get('/api/mcp/connection/status/oauth-server');
@@ -3434,6 +3569,8 @@ describe('MCP Routes', () => {
},
};
const serverConfig = { type: 'sse', url: 'https://user.example.com/sse' };
+ const recoveryPolicy = { discoveryBackoffMs: [125, 250] };
+ mockRequestConfig = { mcpSettings: { catalogRecovery: recoveryPolicy } };
mockResolveAllMcpConfigs.mockResolvedValueOnce({ 'user-server': serverConfig });
mockLoadMCPServerCatalogs.mockResolvedValueOnce({
serverTools: new Map([['user-server', serverTools]]),
@@ -3452,6 +3589,7 @@ describe('MCP Routes', () => {
upstreamTokenProvider: expect.any(Function),
oboIdentityContext: expect.any(Object),
signal: expect.any(AbortSignal),
+ recoveryPolicy,
});
});
@@ -3508,6 +3646,24 @@ describe('MCP Routes', () => {
});
});
+ it('reports a stable reauthorization state from passive discovery', async () => {
+ const serverConfig = { type: 'sse', url: 'https://oauth.example.com/sse' };
+ mockResolveAllMcpConfigs.mockResolvedValueOnce({ oauth: serverConfig });
+ mockLoadMCPServerCatalogs.mockResolvedValueOnce({
+ serverTools: new Map([['oauth', {}]]),
+ serversWithoutTools: [],
+ reauthRequiredServers: new Set(['oauth']),
+ });
+
+ const response = await request(app).get('/api/mcp/tools');
+
+ expect(response.status).toBe(200);
+ expect(response.body.servers.oauth).toMatchObject({
+ authenticated: false,
+ authorizationState: 'reauth_required',
+ });
+ });
+
it('continues rendering available tools when another server has no catalog', async () => {
const { Constants } = require('librechat-data-provider');
const configs = {
diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.js
index 7c904af969..9b28db1f90 100644
--- a/api/server/routes/mcp.js
+++ b/api/server/routes/mcp.js
@@ -30,6 +30,9 @@ const {
MCPAuthenticationRejectedError,
MCPAuthenticationRefreshError,
OpenIDReauthRequiredError,
+ readMCPRecoveryGenerationAround,
+ prepareMCPAuthorizationMutation,
+ persistMCPAuthorizationTransaction,
} = require('@librechat/api');
const {
createMCPServerController,
@@ -51,12 +54,24 @@ const {
resolveConfigServers,
getMCPSetupData,
} = require('~/server/services/MCP');
-const { requireJwtAuth, canAccessMCPServerResource } = require('~/server/middleware');
+const {
+ requireJwtAuth,
+ configMiddleware,
+ canAccessMCPServerResource,
+} = require('~/server/middleware');
const { getUserPluginAuthValue } = require('~/server/services/PluginService');
const { maybeUninstallOAuthMCP } = require('~/server/services/MCP/oauthCleanup');
-const { invalidateCachedTools, getAppConfig } = require('~/server/services/Config');
+const {
+ invalidateCachedTools,
+ getAppConfig,
+ getMCPToolsCacheGeneration,
+} = require('~/server/services/Config');
const { updateMCPServerTools } = require('~/server/services/Config/mcp');
const { reinitMCPServer } = require('~/server/services/Tools/mcp');
+const {
+ clearMCPAuthorizationFenceRetry,
+ persistMCPAuthorizationFenceRetry,
+} = require('~/server/services/MCPAuthorizationFenceRetry');
const { createOpenIDSessionTokenProvider } = require('~/server/services/OpenIDSessionRefresh');
const { getLogStores } = require('~/cache');
const db = require('~/models');
@@ -79,15 +94,6 @@ const canAccessOAuthFlow = (flowId, userId) => {
return parsed.userId === userId || parsed.userId === 'system';
};
-const clearGetTokensFlow = async ({ flowManager, flowId, tokens }) => {
- const state = await flowManager.getFlowState(flowId, 'mcp_get_tokens');
- if (state?.type === 'mcp_get_tokens' && state.status === 'PENDING') {
- await flowManager.completeFlow(flowId, 'mcp_get_tokens', tokens);
- return;
- }
- await flowManager.deleteFlow(flowId, 'mcp_get_tokens');
-};
-
const checkMCPUsePermissions = generateCheckAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permissions: [Permissions.USE],
@@ -104,7 +110,7 @@ const checkMCPCreate = generateCheckAccess({
* Get all MCP tools available to the user
* Returns only MCP tools, completely decoupled from regular LibreChat tools
*/
-router.get('/tools', requireJwtAuth, checkMCPUsePermissions, async (req, res) => {
+router.get('/tools', requireJwtAuth, configMiddleware, checkMCPUsePermissions, async (req, res) => {
return getMCPTools(req, res);
});
@@ -430,11 +436,13 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
await runWithTenant(async () => {
const oauthHeaders =
flowState.oauthHeaders ?? (await getOAuthHeaders(serverName, flowState.userId));
+ let recoveryPolicy;
const resolveActiveServer = async () => {
const [configs, appConfig] = await Promise.all([
resolveAllMcpConfigs(flowState.userId),
getAppConfig({ userId: flowState.userId, tenantId: getTenantId() }),
]);
+ recoveryPolicy = appConfig?.mcpSettings?.catalogRecovery;
const activeConfig =
configs?.[serverName] ??
appConfig?.mcpConfig?.[serverName] ??
@@ -505,34 +513,64 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
code,
flowManager,
oauthHeaders,
- async (exchangedTokens) => {
+ async (exchangedTokens, completePersistedFlow) => {
if (!flowState?.userId) {
return exchangedTokens;
}
let storedTokens;
try {
- storedTokens =
- (await MCPTokenStorage.storeTokens({
- userId: flowState.userId,
- serverName,
+ const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(
+ flowState.userId,
+ serverName,
+ flowState.tenantId,
+ );
+ storedTokens = await persistMCPAuthorizationTransaction(
+ {
+ scope: { userId: flowState.userId, serverName },
+ flowIds: [tokenFlowId, flowId],
tokens: exchangedTokens,
- createToken: db.createToken,
- updateToken: db.updateToken,
- deleteTokens: db.deleteTokens,
- findToken: db.findToken,
- clientInfo: flowState.clientInfo,
- metadata: MCPOAuthHandler.buildStoredClientMetadata(
- flowState.metadata,
- flowState.resourceMetadata,
- flowState.serverUrl,
- flowState.clientSource,
- ),
- })) ?? exchangedTokens;
- if (!(await resolveActiveServer())) {
- await rollbackStoredTokens(storedTokens);
- throw new Error(`MCP server ${serverName} was deleted during OAuth authorization`);
- }
+ completeAuthorization: completePersistedFlow,
+ persistTokens: async (candidateTokens, onStoreCommitted) =>
+ (await MCPTokenStorage.storeTokens({
+ userId: flowState.userId,
+ serverName,
+ tokens: candidateTokens,
+ createToken: db.createToken,
+ updateToken: db.updateToken,
+ deleteTokens: db.deleteTokens,
+ findToken: db.findToken,
+ clientInfo: flowState.clientInfo,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ flowState.metadata,
+ flowState.resourceMetadata,
+ flowState.serverUrl,
+ flowState.clientSource,
+ ),
+ onStoreCommitted,
+ })) ?? candidateTokens,
+ },
+ {
+ ensureServerActive: resolveActiveServer,
+ inactiveServerError: () =>
+ new Error(`MCP server ${serverName} was deleted during OAuth authorization`),
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ clearLocalRecovery: (userId, changedServerName) =>
+ getMCPManager()?.clearCatalogRecoveryState?.(userId, changedServerName),
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
+ attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
+ flowManager,
+ onTokenFlowError: (phase, error) =>
+ logger.warn(
+ phase === 'prepare'
+ ? '[MCP OAuth] Failed to clear cached token flow state'
+ : '[MCP OAuth] Failed to wake a pending token flow',
+ error,
+ ),
+ },
+ );
logger.debug('[MCP OAuth] Stored OAuth tokens before completing callback flow', {
serverName,
userId: flowState.userId,
@@ -542,34 +580,6 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
throw error;
}
- /**
- * Clear any cached `mcp_get_tokens` flow result before the OAuth flow wakes its
- * waiters, so they cannot observe stale credentials after completion.
- */
- if (typeof flowManager?.deleteFlow === 'function') {
- try {
- const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(
- flowState.userId,
- serverName,
- flowState.tenantId,
- );
- await clearGetTokensFlow({
- flowManager,
- flowId: tokenFlowId,
- tokens: storedTokens,
- });
- if (tokenFlowId !== flowId) {
- await clearGetTokensFlow({
- flowManager,
- flowId,
- tokens: storedTokens,
- });
- }
- } catch (error) {
- logger.warn('[MCP OAuth] Failed to clear cached token flow state', error);
- }
- }
-
return storedTokens;
},
rollbackStoredTokens,
@@ -646,6 +656,16 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
createToken: db.createToken,
deleteTokens: db.deleteTokens,
},
+ onOAuthCredentialsChanging: (scope) =>
+ prepareMCPAuthorizationMutation(scope, {
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ clearLocalRecovery: (userId, changedServerName) =>
+ getMCPManager()?.clearCatalogRecoveryState?.(userId, changedServerName),
+ retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
+ attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
+ }),
},
async (userConnection) => {
logger.info(
@@ -900,6 +920,7 @@ function getMCPReinitializeOAuthTimeout(oauthExpiresAt) {
router.post(
'/:serverName/reinitialize',
requireJwtAuth,
+ configMiddleware,
checkMCPUsePermissions,
setOAuthSession,
async (req, res, next) => {
@@ -963,6 +984,7 @@ router.post(
tokenPreference: 'access_token',
}),
oboIdentityContext,
+ recoveryPolicy: req.config?.mcpSettings?.catalogRecovery,
});
if (!result) {
@@ -1016,7 +1038,7 @@ router.post(
* Get connection status for all MCP servers
* This endpoint returns all app level and user-scoped connection statuses from MCPManager without disconnecting idle connections
*/
-router.get('/connection/status', requireJwtAuth, async (req, res) => {
+router.get('/connection/status', requireJwtAuth, configMiddleware, async (req, res) => {
try {
const user = req.user;
@@ -1026,23 +1048,32 @@ router.get('/connection/status', requireJwtAuth, async (req, res) => {
const { mcpConfig, appConnections, userConnections, oauthServers } = await getMCPSetupData(
user.id,
- { role: user.role, tenantId: getTenantId() },
+ { role: user.role, tenantId: getTenantId(), appConfig: req.config },
);
const runtimeContext = createMCPStatusRuntimeContext(user, mcpConfig, Object.keys(mcpConfig));
const connectionStatus = Object.fromEntries(
await Promise.all(
Object.entries(mcpConfig).map(async ([serverName, config]) => {
try {
- const status = await getServerConnectionStatus(
- user.id,
- serverName,
- config,
- appConnections,
- userConnections,
- oauthServers,
- runtimeContext,
- );
- return [serverName, status];
+ const { value: status, generation: authorizationGeneration } =
+ await readMCPRecoveryGenerationAround(
+ { userId: user.id, serverName },
+ getMCPToolsCacheGeneration,
+ () =>
+ getServerConnectionStatus(
+ user.id,
+ serverName,
+ config,
+ appConnections,
+ userConnections,
+ oauthServers,
+ runtimeContext,
+ ),
+ {
+ timeoutMs: req.config?.mcpSettings?.catalogRecovery?.generationReadTimeoutMs,
+ },
+ );
+ return [serverName, { ...status, authorizationGeneration }];
} catch (error) {
const message = `Failed to get status for server "${serverName}"`;
logger.error(`[MCP Connection Status] ${message},`, error);
@@ -1078,7 +1109,7 @@ router.get('/connection/status', requireJwtAuth, async (req, res) => {
* Get connection status for a single MCP server
* This endpoint returns the connection status for a specific server for a given user
*/
-router.get('/connection/status/:serverName', requireJwtAuth, async (req, res) => {
+router.get('/connection/status/:serverName', requireJwtAuth, configMiddleware, async (req, res) => {
try {
const user = req.user;
const { serverName } = req.params;
@@ -1089,7 +1120,7 @@ router.get('/connection/status/:serverName', requireJwtAuth, async (req, res) =>
const { mcpConfig, appConnections, userConnections, oauthServers } = await getMCPSetupData(
user.id,
- { role: user.role, tenantId: getTenantId() },
+ { role: user.role, tenantId: getTenantId(), appConfig: req.config },
);
if (!mcpConfig[serverName]) {
@@ -1100,15 +1131,24 @@ router.get('/connection/status/:serverName', requireJwtAuth, async (req, res) =>
const runtimeContext = createMCPStatusRuntimeContext(user, mcpConfig, [serverName]);
- const serverStatus = await getServerConnectionStatus(
- user.id,
- serverName,
- mcpConfig[serverName],
- appConnections,
- userConnections,
- oauthServers,
- runtimeContext,
- );
+ const { value: serverStatus, generation: authorizationGeneration } =
+ await readMCPRecoveryGenerationAround(
+ { userId: user.id, serverName },
+ getMCPToolsCacheGeneration,
+ () =>
+ getServerConnectionStatus(
+ user.id,
+ serverName,
+ mcpConfig[serverName],
+ appConnections,
+ userConnections,
+ oauthServers,
+ runtimeContext,
+ ),
+ {
+ timeoutMs: req.config?.mcpSettings?.catalogRecovery?.generationReadTimeoutMs,
+ },
+ );
res.json({
success: true,
@@ -1118,6 +1158,7 @@ router.get('/connection/status/:serverName', requireJwtAuth, async (req, res) =>
requestScoped: serverStatus.requestScoped,
configurationState: serverStatus.configurationState,
authorizationState: serverStatus.authorizationState,
+ authorizationGeneration,
});
} catch (error) {
logger.error(
diff --git a/api/server/services/MCP.js b/api/server/services/MCP.js
index cd30328e2c..baf11c268c 100644
--- a/api/server/services/MCP.js
+++ b/api/server/services/MCP.js
@@ -45,6 +45,7 @@ const {
OpenIDReauthRequiredError,
MCPAuthenticationRefreshError,
MCPAuthenticationRejectedError,
+ prepareMCPAuthorizationMutation,
} = require('@librechat/api');
const {
Time,
@@ -72,8 +73,13 @@ const {
getCachedTools,
getMCPServerTools,
cacheMCPServerTools,
+ invalidateCachedTools,
} = require('./Config');
const { getLogStores } = require('~/cache');
+const {
+ clearMCPAuthorizationFenceRetry,
+ persistMCPAuthorizationFenceRetry,
+} = require('./MCPAuthorizationFenceRetry');
const MAX_CACHE_SIZE = 1000;
const lastReconnectAttempts = new Map();
@@ -425,6 +431,7 @@ async function getAssistantToolDefinitions({ req, res, tools }) {
userMCPAuthMap,
upstreamTokenProvider,
oboIdentityContext,
+ recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,
});
return result?.availableTools ?? null;
},
@@ -757,6 +764,7 @@ async function reconnectServer({
oboIdentityContext,
streamId = null,
jobCreatedAt,
+ recoveryPolicy,
}) {
logger.debug('[MCP][reconnectServer] Starting reconnect', {
userId: user?.id,
@@ -821,6 +829,7 @@ async function reconnectServer({
requestBody,
requestScopedConnections,
upstreamTokenProvider,
+ recoveryPolicy,
oboIdentityContext,
forceNew: true,
returnOnOAuth: false,
@@ -871,6 +880,7 @@ async function createMCPTools({
streamId = null,
jobCreatedAt,
}) {
+ let recoveryPolicy;
const serverConfig =
config ?? (await getMCPServersRegistry().getServerConfig(serverName, user?.id, configServers));
@@ -880,6 +890,7 @@ async function createMCPTools({
tenantId: user?.tenantId,
userId: user?.id,
});
+ recoveryPolicy = appConfig?.mcpSettings?.catalogRecovery;
const allowedDomains = appConfig?.mcpSettings?.allowedDomains;
const allowedAddresses = appConfig?.mcpSettings?.allowedAddresses;
const isDomainAllowed = await isEarlyDomainAllowed({
@@ -912,6 +923,7 @@ async function createMCPTools({
oboIdentityContext,
streamId,
jobCreatedAt,
+ recoveryPolicy,
});
if (result === null) {
logger.debug('[MCP] Reconnect throttled; skipping tool creation');
@@ -938,6 +950,7 @@ async function createMCPTools({
configServers,
streamId,
jobCreatedAt,
+ recoveryPolicy,
availableTools: result.availableTools,
serverName,
/** Model-facing key: matches the normalized `availableTools` keys and
@@ -1001,6 +1014,7 @@ async function createMCPTool({
onAvailableTools,
streamId = null,
jobCreatedAt,
+ recoveryPolicy,
}) {
/** `loadTools` already resolved the server for this key; parsing is the fallback. */
const [parsedToolName, parsedServerName] = splitMCPToolKey(
@@ -1045,6 +1059,7 @@ async function createMCPTool({
tenantId: user?.tenantId,
userId: user?.id,
});
+ recoveryPolicy ??= appConfig?.mcpSettings?.catalogRecovery;
const allowedDomains = appConfig?.mcpSettings?.allowedDomains;
const allowedAddresses = appConfig?.mcpSettings?.allowedAddresses;
const isDomainAllowed = await isEarlyDomainAllowed({
@@ -1129,6 +1144,7 @@ async function createMCPTool({
oboIdentityContext,
streamId,
jobCreatedAt,
+ ...(recoveryPolicy && { recoveryPolicy }),
});
if (result?.availableTools) {
onAvailableTools?.(result.availableTools);
@@ -1173,6 +1189,7 @@ async function createMCPTool({
oboIdentityContext,
streamId,
jobCreatedAt,
+ recoveryPolicy,
});
}
@@ -1193,6 +1210,7 @@ function createToolInstance({
oboIdentityContext: capturedOboIdentityContext = null,
streamId = null,
jobCreatedAt,
+ recoveryPolicy,
}) {
/** @type {LCTool} */
const { description, parameters } = toolDefinition;
@@ -1303,6 +1321,16 @@ function createToolInstance({
updateToken,
deleteTokens,
},
+ onOAuthCredentialsChanging: (scope) =>
+ prepareMCPAuthorizationMutation(scope, {
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ clearLocalRecovery: (userId, changedServerName) =>
+ mcpManager.clearCatalogRecoveryState?.(userId, changedServerName),
+ retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
+ attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
+ }),
oauthStart,
oauthEnd,
graphTokenResolver: getGraphApiToken,
@@ -1410,14 +1438,14 @@ function createToolInstance({
* Get MCP setup data including config, connections, and OAuth servers.
* Resolves config-source servers from admin Config overrides when tenant context is available.
* @param {string} userId - The user ID
- * @param {{ role?: string, tenantId?: string }} [options] - Optional role/tenant context
+ * @param {{ role?: string, tenantId?: string, appConfig?: object }} [options] - Optional request context
* @returns {Object} Object containing mcpConfig, appConnections, userConnections, and oauthServers
*/
async function getMCPSetupData(userId, options = {}) {
const registry = getMCPServersRegistry();
const { role, tenantId } = options;
- const appConfig = await getAppConfig({ role, tenantId, userId });
+ const appConfig = options.appConfig ?? (await getAppConfig({ role, tenantId, userId }));
const configServers = await registry.ensureConfigServers(appConfig?.mcpConfig || {});
const mcpConfig = role
? await registry.getAllServerConfigs(userId, configServers, role)
diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.js
index b79190eda0..8df6e52594 100644
--- a/api/server/services/MCP.spec.js
+++ b/api/server/services/MCP.spec.js
@@ -258,6 +258,16 @@ describe('tests for the new helper functions used by the MCP connection status e
expect(result.oauthServers).toEqual(new Set());
});
+ it('reuses request-loaded app configuration', async () => {
+ const appConfig = { mcpConfig: { server1: { type: 'stdio' } } };
+ mockGetAppConfig.mockClear();
+
+ await getMCPSetupData(mockUserId, { role: 'user', appConfig });
+
+ expect(mockGetAppConfig).not.toHaveBeenCalled();
+ expect(mockRegistryInstance.ensureConfigServers).toHaveBeenCalledWith(appConfig.mcpConfig);
+ });
+
it('should handle null values from MCP manager gracefully', async () => {
mockRegistryInstance.getAllServerConfigs.mockResolvedValue(mockConfig);
diff --git a/api/server/services/MCPAuthorizationFenceRetry.js b/api/server/services/MCPAuthorizationFenceRetry.js
new file mode 100644
index 0000000000..4ad53bc506
--- /dev/null
+++ b/api/server/services/MCPAuthorizationFenceRetry.js
@@ -0,0 +1,34 @@
+const mongoose = require('mongoose');
+const {
+ createMCPAuthorizationFenceRetryStorage,
+ getTenantId,
+ tenantStorage,
+} = require('@librechat/data-schemas');
+const { createMCPAuthorizationFenceRetryService } = require('@librechat/api');
+
+let retryService;
+
+function getRetryService() {
+ retryService ??= createMCPAuthorizationFenceRetryService({
+ getTenantId,
+ storage: createMCPAuthorizationFenceRetryStorage(mongoose),
+ runInRetryScope: (retry, operation) =>
+ tenantStorage.run(
+ {
+ ...(typeof retry.tenantId === 'string' && retry.tenantId
+ ? { tenantId: retry.tenantId }
+ : {}),
+ userId: String(retry.userId),
+ },
+ operation,
+ ),
+ });
+ return retryService;
+}
+
+module.exports = {
+ clearMCPAuthorizationFenceRetry: (...args) => getRetryService().clear(...args),
+ drainMCPAuthorizationFenceRetries: (...args) => getRetryService().drain(...args),
+ persistMCPAuthorizationFenceRetry: (...args) => getRetryService().persist(...args),
+ startMCPAuthorizationFenceRetryWorker: (...args) => getRetryService().start(...args),
+};
diff --git a/api/server/services/MCPAuthorizationFenceRetry.spec.js b/api/server/services/MCPAuthorizationFenceRetry.spec.js
new file mode 100644
index 0000000000..980eefb79f
--- /dev/null
+++ b/api/server/services/MCPAuthorizationFenceRetry.spec.js
@@ -0,0 +1,63 @@
+const mockStorage = {
+ upsert: jest.fn(),
+ deleteVersion: jest.fn(),
+ deferVersion: jest.fn(),
+ list: jest.fn(),
+};
+const mockGetTenantId = jest.fn();
+const mockTenantRun = jest.fn((_context, fn) => fn());
+const mockRetryService = {
+ clear: jest.fn(),
+ drain: jest.fn(),
+ persist: jest.fn(),
+ start: jest.fn(),
+};
+let capturedDeps;
+
+jest.mock('mongoose', () => ({}));
+jest.mock('@librechat/data-schemas', () => ({
+ createMCPAuthorizationFenceRetryStorage: jest.fn(() => mockStorage),
+ getTenantId: (...args) => mockGetTenantId(...args),
+ tenantStorage: { run: (...args) => mockTenantRun(...args) },
+}));
+jest.mock('@librechat/api', () => ({
+ createMCPAuthorizationFenceRetryService: (deps) => {
+ capturedDeps = deps;
+ return mockRetryService;
+ },
+}));
+
+const retryAdapter = require('./MCPAuthorizationFenceRetry');
+
+describe('MCPAuthorizationFenceRetry adapter', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('exports the package-owned retry lifecycle', () => {
+ expect(Object.keys(retryAdapter).sort()).toEqual([
+ 'clearMCPAuthorizationFenceRetry',
+ 'drainMCPAuthorizationFenceRetries',
+ 'persistMCPAuthorizationFenceRetry',
+ 'startMCPAuthorizationFenceRetryWorker',
+ ]);
+ });
+
+ it('restores tenant context for replay', async () => {
+ const retry = {
+ tenantId: 'tenant-a',
+ userId: 'user-1',
+ serverName: 'github',
+ version: 'v1',
+ };
+ retryAdapter.startMCPAuthorizationFenceRetryWorker();
+ expect(capturedDeps.storage).toBe(mockStorage);
+ const operation = jest.fn().mockResolvedValue(undefined);
+ await capturedDeps.runInRetryScope(retry, operation);
+
+ expect(mockTenantRun).toHaveBeenCalledWith(
+ { tenantId: 'tenant-a', userId: 'user-1' },
+ operation,
+ );
+ });
+});
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index 011d79f475..88dae404c5 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -1183,6 +1183,7 @@ async function loadToolDefinitionsWrapper({
requestScopedConnections,
upstreamTokenProvider,
oboIdentityContext,
+ recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,
});
rememberMCPAvailableTools(serverName, result?.availableTools);
@@ -1212,6 +1213,7 @@ async function loadToolDefinitionsWrapper({
requestScopedConnections,
upstreamTokenProvider,
oboIdentityContext,
+ recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,
});
rememberMCPAvailableTools(serverName, result?.availableTools);
@@ -1362,6 +1364,7 @@ async function loadToolDefinitionsWrapper({
connectionTimeout: Time.TWO_MINUTES,
upstreamTokenProvider,
oboIdentityContext,
+ recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,
});
if (result?.availableTools && Object.keys(result.availableTools).length > 0) {
diff --git a/api/server/services/Tools/mcp.js b/api/server/services/Tools/mcp.js
index 69c55fbc72..0070b65c0a 100644
--- a/api/server/services/Tools/mcp.js
+++ b/api/server/services/Tools/mcp.js
@@ -9,6 +9,7 @@ const {
MCPAuthenticationRejectedError,
MCPAuthenticationRefreshError,
OpenIDReauthRequiredError,
+ prepareMCPAuthorizationMutation,
} = require('@librechat/api');
const { CacheKeys, Constants } = require('librechat-data-provider');
const { getMCPManager, getMCPServersRegistry, getFlowStateManager } = require('~/config');
@@ -27,8 +28,13 @@ const {
cacheMCPServerTools,
getMCPToolsCacheGeneration,
updateMCPServerTools,
+ invalidateCachedTools,
} = require('~/server/services/Config');
const { getLogStores } = require('~/cache');
+const {
+ clearMCPAuthorizationFenceRetry,
+ persistMCPAuthorizationFenceRetry,
+} = require('~/server/services/MCPAuthorizationFenceRetry');
const MCP_REINITIALIZE_FAILURE_REASONS = {
UNREACHABLE: 'unreachable',
@@ -49,6 +55,7 @@ const isMCPReauthenticationError = (error) =>
* @param {import('@librechat/api').UpstreamTokenProvider} [params.upstreamTokenProvider] - Live upstream-token closure for OBO discovery, built at the request boundary so this layer never receives the raw Express request.
* @param {import('@librechat/api').AuthIdentityContext} [params.oboIdentityContext] - Non-template-visible OBO identity context built from the real request user.
* @param {AbortSignal} [params.signal] - Cancels queued and in-flight catalog reads when the request ends.
+ * @param {import('@librechat/api').MCPServerCatalogRecoveryPolicy} [params.recoveryPolicy]
*/
async function loadMCPServerCatalogs({
user,
@@ -56,12 +63,23 @@ async function loadMCPServerCatalogs({
upstreamTokenProvider,
oboIdentityContext,
signal,
+ recoveryPolicy,
}) {
const flowManager = getFlowStateManager(getLogStores(CacheKeys.FLOWS));
const tokenMethods = { findToken, updateToken, createToken, deleteTokens };
const mcpManager = getMCPManager();
+ const onOAuthCredentialsChanging = (scope) =>
+ prepareMCPAuthorizationMutation(scope, {
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ clearLocalRecovery: (userId, serverName) =>
+ mcpManager.clearCatalogRecoveryState?.(userId, serverName),
+ retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
+ attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
+ });
return loadCatalogs(
- { user, servers, signal },
+ { user, servers, signal, recoveryPolicy },
{
loadUserMCPAuthMap: (userId, serverNames) =>
getUserMCPAuthMap({
@@ -79,8 +97,11 @@ async function loadMCPServerCatalogs({
oboTrustChecker: createOboTrustChecker(),
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanging,
}),
formatServerTools: formatMCPServerTools,
+ recoveryTracker: mcpManager.getCatalogRecoveryTracker?.(),
+ getRecoveryGeneration: getMCPToolsCacheGeneration,
getCachedServerTools: getMCPServerTools,
getServerToolFunctionsSnapshot: (userId, serverName, serverConfig, options) =>
mcpManager.getServerToolFunctionsSnapshot(userId, serverName, serverConfig, options),
@@ -108,6 +129,7 @@ async function loadMCPServerCatalogs({
* @param {import('@librechat/api').RequestBody} [params.requestBody]
* @param {import('@librechat/api').RequestScopedMCPConnectionStore} [params.requestScopedConnections]
* @param {Record<string, Record<string, string>>} [params.userMCPAuthMap]
+ * @param {import('@librechat/api').MCPServerCatalogRecoveryPolicy} [params.recoveryPolicy]
*/
async function reinitMCPServer({
user,
@@ -126,6 +148,7 @@ async function reinitMCPServer({
upstreamTokenProvider,
oboIdentityContext,
oauthEnd,
+ recoveryPolicy,
}) {
/** @type {MCPConnection | null} */
let connection = null;
@@ -232,6 +255,16 @@ async function reinitMCPServer({
const flowManager = _flowManager ?? getFlowStateManager(getLogStores(CacheKeys.FLOWS));
const mcpManager = getMCPManager();
+ const onOAuthCredentialsChanging = (scope) =>
+ prepareMCPAuthorizationMutation(scope, {
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ clearLocalRecovery: (userId, changedServerName) =>
+ mcpManager.clearCatalogRecoveryState?.(userId, changedServerName),
+ retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
+ attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
+ });
const tokenMethods = { findToken, updateToken, createToken, deleteTokens };
if (!ephemeralServer) {
@@ -264,6 +297,7 @@ async function reinitMCPServer({
serverName,
flowManager,
tokenMethods,
+ onOAuthCredentialsChanging,
returnOnOAuth,
oauthEnd,
customUserVars,
@@ -306,6 +340,7 @@ async function reinitMCPServer({
serverName,
flowManager,
tokenMethods,
+ onOAuthCredentialsChanging,
oauthStart,
customUserVars,
requestBody,
diff --git a/api/server/services/Tools/mcp.spec.js b/api/server/services/Tools/mcp.spec.js
index e2e7d5bcf7..e0f54659d7 100644
--- a/api/server/services/Tools/mcp.spec.js
+++ b/api/server/services/Tools/mcp.spec.js
@@ -88,6 +88,7 @@ describe('loadMCPServerCatalogs', () => {
await deps.getServerToolFunctionsSnapshot(user.id, 'config-only', servers[0].serverConfig, {
deadlineMs: 123,
});
+ await deps.getRecoveryGeneration({ userId: user.id, serverName: 'config-only' });
await deps.cacheServerTools({ serverName: 'config-only' });
return { serverTools: new Map([['config-only', {}]]), serversWithoutTools: [] };
});
@@ -102,6 +103,10 @@ describe('loadMCPServerCatalogs', () => {
});
expect(mockGetUserMCPAuthMap).toHaveBeenCalledTimes(1);
+ expect(mockGetMCPToolsCacheGeneration).toHaveBeenCalledWith({
+ userId: user.id,
+ serverName: 'config-only',
+ });
expect(mockGetUserMCPAuthMap).toHaveBeenCalledWith({
userId: user.id,
servers: ['config-only', 'user-server'],
diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.js
index e2b8ebca36..5e27a91236 100644
--- a/api/server/services/__tests__/MCP.spec.js
+++ b/api/server/services/__tests__/MCP.spec.js
@@ -751,4 +751,32 @@ describe('createMCPTool', () => {
expect(toolInstance.name).toBe(canonicalToolKey);
expect(reinitMCPServer).not.toHaveBeenCalled();
});
+
+ it('forwards the configured recovery policy when a missing tool reconnects', async () => {
+ const recoveryPolicy = {
+ authorizationFenceRetryMs: [0, 25, 100],
+ authorizationFenceTimeoutMs: 750,
+ };
+ getAppConfig.mockResolvedValue({ mcpSettings: { catalogRecovery: recoveryPolicy } });
+ require('@librechat/api').isMCPDomainAllowed.mockResolvedValue(true);
+ require('~/config').getFlowStateManager.mockReturnValue({});
+ require('~/cache').getLogStores.mockReturnValue({});
+ reinitMCPServer.mockResolvedValue({
+ availableTools: { [canonicalToolKey]: { type: 'function', function: toolFunction } },
+ });
+
+ const toolInstance = await createMCPTool({
+ user: { id: 'user-1' },
+ toolKey: canonicalToolKey,
+ serverName: rawServerName,
+ availableTools: {},
+ config: { type: 'streamable-http', url: 'https://mcp.example.com' },
+ provider: 'openAI',
+ });
+
+ expect(toolInstance).toBeDefined();
+ expect(reinitMCPServer).toHaveBeenCalledWith(
+ expect.objectContaining({ serverName: rawServerName, recoveryPolicy }),
+ );
+ });
});
diff --git a/api/server/services/initializeMCPs.js b/api/server/services/initializeMCPs.js
index d8bac4b91f..4796f38e95 100644
--- a/api/server/services/initializeMCPs.js
+++ b/api/server/services/initializeMCPs.js
@@ -8,7 +8,8 @@ const {
setMCPToolsChangedGenerationRenewalHandler,
setMCPToolsChangedRevisionHandler,
} = require('@librechat/api');
-const { syncStaticTools, mergeAppTools, getAppConfig } = require('./Config');
+const { syncStaticTools, mergeAppTools, getAppConfig, invalidateCachedTools } = require('./Config');
+const { startMCPAuthorizationFenceRetryWorker } = require('./MCPAuthorizationFenceRetry');
const {
getMCPToolsCacheGeneration,
renewMCPToolsCacheGeneration,
@@ -113,7 +114,14 @@ async function initializeMCPs() {
}
try {
- const mcpManager = await createMCPManager(mcpServers || {});
+ const mcpManager = await createMCPManager(mcpServers || {}, {
+ catalogRecoveryMaxStateEntries: appConfig?.mcpSettings?.catalogRecovery?.maxStateEntries,
+ });
+ startMCPAuthorizationFenceRetryWorker(invalidateCachedTools, {
+ intervalMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryIntervalMs,
+ batchSize: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryBatchSize,
+ attemptTimeoutMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceTimeoutMs,
+ });
setMCPToolsChangedHandler(refreshChangedServerTools);
setMCPToolsChangedGenerationHandler(getMCPToolsCacheGeneration);
setMCPToolsChangedGenerationRenewalHandler(renewMCPToolsCacheGeneration);
diff --git a/api/server/services/initializeMCPs.plugins.spec.js b/api/server/services/initializeMCPs.plugins.spec.js
index 265ad38006..c462d8fde0 100644
--- a/api/server/services/initializeMCPs.plugins.spec.js
+++ b/api/server/services/initializeMCPs.plugins.spec.js
@@ -51,6 +51,10 @@ jest.mock('./Config/mcp', () => ({
updateMCPServerTools: jest.fn(),
}));
+jest.mock('./MCPAuthorizationFenceRetry', () => ({
+ startMCPAuthorizationFenceRetryWorker: jest.fn(),
+}));
+
const mockGetAppConfig = jest.fn();
const mockMergeAppTools = jest.fn();
const mockSyncStaticTools = jest.fn();
diff --git a/api/server/services/initializeMCPs.spec.js b/api/server/services/initializeMCPs.spec.js
index 87f40e47db..d1b17bff2d 100644
--- a/api/server/services/initializeMCPs.spec.js
+++ b/api/server/services/initializeMCPs.spec.js
@@ -29,6 +29,14 @@ jest.mock('@librechat/data-schemas', () => ({
const mockGetAppConfig = jest.fn();
const mockSyncStaticTools = jest.fn();
const mockMergeAppTools = jest.fn();
+const mockInvalidateCachedTools = jest.fn();
+const mockStartMCPAuthorizationFenceRetryWorker = jest.fn();
+
+jest.mock('./MCPAuthorizationFenceRetry', () => ({
+ get startMCPAuthorizationFenceRetryWorker() {
+ return mockStartMCPAuthorizationFenceRetryWorker;
+ },
+}));
jest.mock('./Config', () => ({
get getAppConfig() {
@@ -40,6 +48,9 @@ jest.mock('./Config', () => ({
get syncStaticTools() {
return mockSyncStaticTools;
},
+ get invalidateCachedTools() {
+ return mockInvalidateCachedTools;
+ },
}));
// Mock MCP singletons
@@ -224,7 +235,12 @@ describe('initializeMCPs', () => {
// MCPManager should be created with empty object when no configured servers
expect(mockCreateMCPManager).toHaveBeenCalledTimes(1);
- expect(mockCreateMCPManager).toHaveBeenCalledWith({});
+ expect(mockCreateMCPManager).toHaveBeenCalledWith(
+ {},
+ {
+ catalogRecoveryMaxStateEntries: undefined,
+ },
+ );
});
it('should initialize MCPManager with configured servers when provided', async () => {
@@ -236,7 +252,36 @@ describe('initializeMCPs', () => {
await initializeMCPs();
- expect(mockCreateMCPManager).toHaveBeenCalledWith(mcpServers);
+ expect(mockCreateMCPManager).toHaveBeenCalledWith(mcpServers, {
+ catalogRecoveryMaxStateEntries: undefined,
+ });
+ });
+
+ it('sets process-wide recovery capacity from the base config', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ mcpConfig: {},
+ mcpSettings: {
+ catalogRecovery: {
+ maxStateEntries: 2500,
+ authorizationFenceRetryIntervalMs: 15_000,
+ authorizationFenceRetryBatchSize: 250,
+ authorizationFenceTimeoutMs: 750,
+ },
+ },
+ });
+
+ await initializeMCPs();
+
+ expect(mockCreateMCPManager).toHaveBeenCalledWith(
+ {},
+ {
+ catalogRecoveryMaxStateEntries: 2500,
+ },
+ );
+ expect(mockStartMCPAuthorizationFenceRetryWorker).toHaveBeenCalledWith(
+ mockInvalidateCachedTools,
+ { intervalMs: 15_000, batchSize: 250, attemptTimeoutMs: 750 },
+ );
});
it('should register app connections for graceful shutdown', async () => {
@@ -416,7 +461,12 @@ describe('initializeMCPs', () => {
expect(mockCreateMCPManager).toHaveBeenCalledTimes(1);
// Verify manager was created with empty config (not null/undefined)
- expect(mockCreateMCPManager).toHaveBeenCalledWith({});
+ expect(mockCreateMCPManager).toHaveBeenCalledWith(
+ {},
+ {
+ catalogRecoveryMaxStateEntries: undefined,
+ },
+ );
});
});
});
diff --git a/api/server/services/initializeOAuthReconnectManager.js b/api/server/services/initializeOAuthReconnectManager.js
index a3af3a736a..f60fe58c7f 100644
--- a/api/server/services/initializeOAuthReconnectManager.js
+++ b/api/server/services/initializeOAuthReconnectManager.js
@@ -1,8 +1,14 @@
-const { logger } = require('@librechat/data-schemas');
+const { logger, getTenantId } = require('@librechat/data-schemas');
+const { prepareMCPAuthorizationMutation } = require('@librechat/api');
const { CacheKeys } = require('librechat-data-provider');
-const { createOAuthReconnectionManager, getFlowStateManager } = require('~/config');
+const { createOAuthReconnectionManager, getFlowStateManager, getMCPManager } = require('~/config');
const { findToken, updateToken, createToken, deleteTokens } = require('~/models');
const { getLogStores } = require('~/cache');
+const { getAppConfig, invalidateCachedTools } = require('~/server/services/Config');
+const {
+ clearMCPAuthorizationFenceRetry,
+ persistMCPAuthorizationFenceRetry,
+} = require('~/server/services/MCPAuthorizationFenceRetry');
/**
* Initialize OAuth reconnect manager
@@ -16,7 +22,24 @@ async function initializeOAuthReconnectManager() {
createToken,
deleteTokens,
};
- await createOAuthReconnectionManager(flowManager, tokenMethods);
+ await createOAuthReconnectionManager(
+ flowManager,
+ tokenMethods,
+ undefined,
+ undefined,
+ async (scope) => {
+ const appConfig = await getAppConfig({ tenantId: getTenantId(), userId: scope.userId });
+ return prepareMCPAuthorizationMutation(scope, {
+ invalidateRecoveryGeneration: invalidateCachedTools,
+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,
+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,
+ clearLocalRecovery: (userId, serverName) =>
+ getMCPManager()?.clearCatalogRecoveryState?.(userId, serverName),
+ retryDelaysMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryMs,
+ attemptTimeoutMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceTimeoutMs,
+ });
+ },
+ );
logger.info(`OAuth reconnect manager initialized successfully.`);
} catch (error) {
logger.error('Failed to initialize OAuth reconnect manager:', error);
diff --git a/api/server/services/initializeOAuthReconnectManager.spec.js b/api/server/services/initializeOAuthReconnectManager.spec.js
new file mode 100644
index 0000000000..aae1cd837e
--- /dev/null
+++ b/api/server/services/initializeOAuthReconnectManager.spec.js
@@ -0,0 +1,74 @@
+const mockCreateOAuthReconnectionManager = jest.fn();
+const mockGetAppConfig = jest.fn();
+const mockPrepareMCPAuthorizationMutation = jest.fn();
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: { info: jest.fn(), error: jest.fn() },
+ getTenantId: jest.fn(() => 'tenant-a'),
+}));
+
+jest.mock('@librechat/api', () => ({
+ prepareMCPAuthorizationMutation: (...args) => mockPrepareMCPAuthorizationMutation(...args),
+}));
+
+jest.mock('librechat-data-provider', () => ({
+ CacheKeys: { FLOWS: 'flows' },
+}));
+
+jest.mock('~/config', () => ({
+ createOAuthReconnectionManager: (...args) => mockCreateOAuthReconnectionManager(...args),
+ getFlowStateManager: jest.fn(() => ({ type: 'flow-manager' })),
+ getMCPManager: jest.fn(() => ({ clearCatalogRecoveryState: jest.fn() })),
+}));
+
+jest.mock('~/models', () => ({
+ findToken: jest.fn(),
+ updateToken: jest.fn(),
+ createToken: jest.fn(),
+ deleteTokens: jest.fn(),
+}));
+
+jest.mock('~/cache', () => ({ getLogStores: jest.fn(() => ({})) }));
+
+jest.mock('~/server/services/Config', () => ({
+ getAppConfig: (...args) => mockGetAppConfig(...args),
+ invalidateCachedTools: jest.fn(),
+}));
+
+jest.mock('~/server/services/MCPAuthorizationFenceRetry', () => ({
+ clearMCPAuthorizationFenceRetry: jest.fn(),
+ persistMCPAuthorizationFenceRetry: jest.fn(),
+}));
+
+const initializeOAuthReconnectManager = require('./initializeOAuthReconnectManager');
+
+describe('initializeOAuthReconnectManager', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockCreateOAuthReconnectionManager.mockResolvedValue(undefined);
+ mockGetAppConfig.mockResolvedValue({
+ mcpSettings: {
+ catalogRecovery: {
+ authorizationFenceRetryMs: [0, 25],
+ authorizationFenceTimeoutMs: 750,
+ },
+ },
+ });
+ mockPrepareMCPAuthorizationMutation.mockResolvedValue(jest.fn());
+ });
+
+ it('resolves the effective user policy when a reconnect refresh prepares its write', async () => {
+ await initializeOAuthReconnectManager();
+
+ expect(mockGetAppConfig).not.toHaveBeenCalled();
+ const prepareRefresh = mockCreateOAuthReconnectionManager.mock.calls[0][4];
+ const scope = { userId: 'user-1', serverName: 'github' };
+ await prepareRefresh(scope);
+
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ tenantId: 'tenant-a', userId: 'user-1' });
+ expect(mockPrepareMCPAuthorizationMutation).toHaveBeenCalledWith(
+ scope,
+ expect.objectContaining({ retryDelaysMs: [0, 25], attemptTimeoutMs: 750 }),
+ );
+ });
+});
diff --git a/client/src/Providers/AgentPanelContext.tsx b/client/src/Providers/AgentPanelContext.tsx
index 62f0a396d8..3cb2e7c1a2 100644
--- a/client/src/Providers/AgentPanelContext.tsx
+++ b/client/src/Providers/AgentPanelContext.tsx
@@ -5,22 +5,21 @@ import { EModelEndpoint } from 'librechat-data-provider';
import type { MCP, Action, TPlugin } from 'librechat-data-provider';
import type { AgentPanelContextType, MCPServerInfo } from '~/common';
import {
- useMCPConnectionStatus,
+ useAvailableToolsQuery,
+ useGetActionsQuery,
+ useGetStartupConfig,
+ useMCPToolsQuery,
+} from '~/data-provider';
+import {
useMCPServerManager,
useGetAgentsConfig,
activateCatalog,
useCatalogReady,
useLocalize,
} from '~/hooks';
-import {
- useAvailableToolsQuery,
- useGetActionsQuery,
- useGetStartupConfig,
- useMCPToolsQuery,
-} from '~/data-provider';
import { isMCPServerReadyForAgent } from '~/components/MCP/mcpServerUtils';
import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
-import { Panel, isEphemeralAgent } from '~/common';
+import { Panel } from '~/common';
import store from '~/store';
const AgentPanelContext = createContext<AgentPanelContextType | undefined>(undefined);
@@ -34,7 +33,13 @@ export function useAgentPanelContext() {
}
/** Houses relevant state for the Agent Form Panels (formerly 'commonProps') */
-export function AgentPanelProvider({ children }: { children: React.ReactNode }) {
+export function AgentPanelProvider({
+ children,
+ observeToolAuthorization = true,
+}: {
+ children: React.ReactNode;
+ observeToolAuthorization?: boolean;
+}) {
const localize = useLocalize();
const location = useLocation();
/** The panel stays mounted while the sidebar is hidden (collapsed, mobile
@@ -53,10 +58,11 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
const [action, setAction] = useState<Action | undefined>(undefined);
const [activePanel, setActivePanel] = useState<Panel>(Panel.builder);
const [agent_id, setCurrentAgentId] = useState<string | undefined>(undefined);
- const { availableMCPServers, isLoading, availableMCPServersMap } = useMCPServerManager();
+ const { availableMCPServers, isLoading, availableMCPServersMap, connectionStatus } =
+ useMCPServerManager({ observeToolAuthorization });
const { data: startupConfig } = useGetStartupConfig();
const { data: actions } = useGetActionsQuery(EModelEndpoint.agents, {
- enabled: !isEphemeralAgent(agent_id),
+ enabled: observeToolAuthorization,
});
const { data: regularTools } = useAvailableToolsQuery(EModelEndpoint.agents);
@@ -68,7 +74,7 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
enabled:
panelVisible &&
mcpToolsReady &&
- !isEphemeralAgent(agent_id) &&
+ observeToolAuthorization &&
!isLoading &&
availableMCPServers.length > 0,
tools: true,
@@ -76,7 +82,7 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
const { data: mcpData, isFetching: mcpToolsFetching } = useMCPToolsQuery({
enabled:
mcpToolsReady &&
- !isEphemeralAgent(agent_id) &&
+ observeToolAuthorization &&
!isLoading &&
availableMCPServers != null &&
availableMCPServers.length > 0,
@@ -91,9 +97,6 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
[availableMCPServers],
);
- const { connectionStatus } = useMCPConnectionStatus({
- enabled: !isEphemeralAgent(agent_id) && mcpServerNames.length > 0,
- });
//TODO to refactor when tools come from tool box
const mcpServersMap = useMemo(() => {
const configuredServers = new Set(mcpServerNames);
diff --git a/client/src/Providers/BadgeRowContext.tsx b/client/src/Providers/BadgeRowContext.tsx
index 0f9647f8f8..59388825a2 100644
--- a/client/src/Providers/BadgeRowContext.tsx
+++ b/client/src/Providers/BadgeRowContext.tsx
@@ -37,6 +37,7 @@ interface BadgeRowProviderProps {
isSubmitting?: boolean;
conversationId?: string | null;
specName?: string | null;
+ observeToolAuthorization?: boolean;
}
export default function BadgeRowProvider({
@@ -44,6 +45,7 @@ export default function BadgeRowProvider({
isSubmitting,
conversationId,
specName,
+ observeToolAuthorization = false,
}: BadgeRowProviderProps) {
const lastContextKeyRef = useRef<string>('');
const hasInitializedRef = useRef(false);
@@ -275,6 +277,7 @@ export default function BadgeRowProvider({
storageContextKey,
specName,
ownsChatSelection: true,
+ observeToolAuthorization,
});
const value: BadgeRowContextType = {
diff --git a/client/src/components/Chat/Input/BadgeRow.tsx b/client/src/components/Chat/Input/BadgeRow.tsx
index 0964926a23..2a0e010012 100644
--- a/client/src/components/Chat/Input/BadgeRow.tsx
+++ b/client/src/components/Chat/Input/BadgeRow.tsx
@@ -328,6 +328,7 @@ function BadgeRow({
conversationId={conversationId}
specName={specName}
isSubmitting={isSubmitting}
+ observeToolAuthorization={showEphemeralBadges === true}
>
<div ref={containerRef} className="relative flex flex-wrap items-center gap-2">
{showEphemeralBadges === true && <ToolsDropdown />}
diff --git a/client/src/components/MCP/ServerInitializationSection.spec.tsx b/client/src/components/MCP/ServerInitializationSection.spec.tsx
index 24404dca63..f5ec3d6eb5 100644
--- a/client/src/components/MCP/ServerInitializationSection.spec.tsx
+++ b/client/src/components/MCP/ServerInitializationSection.spec.tsx
@@ -15,9 +15,6 @@ jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
- useMCPConnectionStatus: () => ({
- connectionStatus: { server: mockConnectionStatus() },
- }),
useMCPServerManager: () => ({
getOAuthUrl: () => undefined,
isCancellable: () => false,
@@ -26,6 +23,7 @@ jest.mock('~/hooks', () => ({
initializeServer: mockInitializeServer,
availableMCPServers: [{ serverName: 'server' }],
availableMCPServersMap: { server: { requestScoped: true } },
+ connectionStatus: { server: mockConnectionStatus() },
revokeOAuthForServer: jest.fn(),
}),
}));
diff --git a/client/src/components/MCP/ServerInitializationSection.tsx b/client/src/components/MCP/ServerInitializationSection.tsx
index 6786af1f65..9890d901f4 100644
--- a/client/src/components/MCP/ServerInitializationSection.tsx
+++ b/client/src/components/MCP/ServerInitializationSection.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { RefreshCw, Trash2 } from 'lucide-react';
import { Button, Spinner } from '@librechat/client';
-import { useLocalize, useMCPServerManager, useMCPConnectionStatus } from '~/hooks';
+import { useLocalize, useMCPServerManager } from '~/hooks';
import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
interface ServerInitializationSectionProps {
@@ -31,11 +31,12 @@ export default function ServerInitializationSection({
initializeServer,
availableMCPServers,
availableMCPServersMap,
+ connectionStatus,
revokeOAuthForServer,
- } = useMCPServerManager({ conversationId, storageContextKey });
-
- const { connectionStatus } = useMCPConnectionStatus({
- enabled: !!availableMCPServers && availableMCPServers.length > 0,
+ } = useMCPServerManager({
+ conversationId,
+ storageContextKey,
+ observeToolAuthorization: true,
});
useMCPRefresh({ enabled: availableMCPServers.length > 0 });
diff --git a/client/src/components/SidePanel/Agents/AgentPanelSwitch.spec.tsx b/client/src/components/SidePanel/Agents/AgentPanelSwitch.spec.tsx
new file mode 100644
index 0000000000..1c4fc6947d
--- /dev/null
+++ b/client/src/components/SidePanel/Agents/AgentPanelSwitch.spec.tsx
@@ -0,0 +1,71 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { render } from '@testing-library/react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { TConversation } from 'librechat-data-provider';
+import store from '~/store';
+
+const mockObserveToolAuthorization = jest.fn();
+const mockSetCurrentAgentId = jest.fn();
+
+jest.mock('~/Providers/AgentPanelContext', () => ({
+ AgentPanelProvider: ({
+ children,
+ observeToolAuthorization,
+ }: {
+ children: React.ReactNode;
+ observeToolAuthorization: boolean;
+ }) => {
+ mockObserveToolAuthorization(observeToolAuthorization);
+ return children;
+ },
+ useAgentPanelContext: () => ({
+ activePanel: 'builder',
+ setCurrentAgentId: mockSetCurrentAgentId,
+ }),
+}));
+jest.mock('./AgentPanel', () => () => null);
+jest.mock('./Version/VersionPanel', () => () => null);
+
+import AgentPanelSwitch from './AgentPanelSwitch';
+
+function renderWithConversation(conversation?: TConversation) {
+ return render(
+ <RecoilRoot
+ initializeState={({ set }) => {
+ if (conversation != null) {
+ set(store.conversationByIndex(0), conversation);
+ }
+ }}
+ >
+ <AgentPanelSwitch />
+ </RecoilRoot>,
+ );
+}
+
+describe('AgentPanelSwitch authorization observers', () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ it('holds observers until the conversation is hydrated', () => {
+ renderWithConversation();
+ expect(mockObserveToolAuthorization).toHaveBeenLastCalledWith(false);
+ });
+
+ it('enables observers for a hydrated persistent agent', () => {
+ renderWithConversation({
+ conversationId: 'new',
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_1',
+ } as TConversation);
+ expect(mockObserveToolAuthorization).toHaveBeenLastCalledWith(true);
+ });
+
+ it('keeps observers disabled for a hydrated ephemeral agent', () => {
+ renderWithConversation({
+ conversationId: 'new',
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'ephemeral',
+ } as TConversation);
+ expect(mockObserveToolAuthorization).toHaveBeenLastCalledWith(false);
+ });
+});
diff --git a/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx b/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx
index dfb2a27996..da67bae3a5 100644
--- a/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx
+++ b/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx
@@ -7,16 +7,19 @@ import AgentPanel from './AgentPanel';
import store from '~/store';
export default function AgentPanelSwitch() {
+ const conversation = useRecoilValue(store.conversationByIndex(0));
+ const agentId = conversation?.agent_id ?? null;
return (
- <AgentPanelProvider>
- <AgentPanelSwitchWithContext />
+ <AgentPanelProvider
+ observeToolAuthorization={conversation != null && !isEphemeralAgent(agentId)}
+ >
+ <AgentPanelSwitchWithContext agentId={agentId} />
</AgentPanelProvider>
);
}
-function AgentPanelSwitchWithContext() {
+function AgentPanelSwitchWithContext({ agentId }: { agentId?: string | null }) {
const { activePanel, setCurrentAgentId } = useAgentPanelContext();
- const agentId = useRecoilValue(store.conversationAgentIdByIndex(0));
useEffect(() => {
const agent_id = agentId ?? '';
diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx
index 4b1cb8cdf0..e52b62a286 100644
--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx
+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx
@@ -26,7 +26,6 @@ import { getStatusColor, getStatusTextKey } from '~/components/MCP/mcpServerUtil
import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
import McpOAuthDialog from '~/components/MCP/McpOAuthDialog';
-import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
import { useAgentPanelContext } from '~/Providers';
import { getIconForItem } from '../../items/icons';
import OptionToggle from '../../../OptionToggle';
@@ -80,7 +79,6 @@ export default function McpSection({ item }: Props) {
const [prevReadyForAgent, setPrevReadyForAgent] = useState(false);
const [autoSelectPending, setAutoSelectPending] = useState(false);
const { mcpServersMap, mcpToolsLoading } = useAgentPanelContext();
- useMCPRefresh({ enabled: true, tools: true });
const { agentsConfig } = useGetAgentsConfig();
const {
codeEnabled,
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx b/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
index 85f641118b..002855d154 100644
--- a/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
+++ b/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
@@ -35,7 +35,7 @@ export default function MCPBuilderPanel() {
}, [panelVisible]);
const { user } = useAuthContext();
const { availableMCPServers, isLoading, getServerStatusIconProps, getConfigDialogProps } =
- useMCPServerManager();
+ useMCPServerManager({ observeToolAuthorization: panelVisible });
useMCPRefresh({ enabled: panelVisible && !isLoading && availableMCPServers.length > 0 });
const hasCreateAccess = useHasAccess({
diff --git a/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx b/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx
index 8a82141d45..a45be858b3 100644
--- a/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx
+++ b/client/src/hooks/Config/__tests__/useAppStartup.spec.tsx
@@ -72,7 +72,6 @@ const mockUser = {
const wrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
<RecoilRoot>{children}</RecoilRoot>
);
-
describe('useAppStartup: MCP permission gating', () => {
beforeEach(() => {
mockInstallCloudFrontImageRetry.mockClear();
@@ -84,7 +83,12 @@ describe('useAppStartup: MCP permission gating', () => {
it('checks the MCP_SERVERS.USE permission via useHasAccess', () => {
mockUseHasAccess.mockReturnValue(false);
- renderHook(() => useAppStartup({ startupConfig: undefined, user: mockUser }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: true }),
+ {
+ wrapper,
+ },
+ );
expect(mockUseHasAccess).toHaveBeenCalledWith({
permissionType: PermissionTypes.MCP_SERVERS,
@@ -95,7 +99,10 @@ describe('useAppStartup: MCP permission gating', () => {
it('suppresses all MCP queries when user lacks MCP_SERVERS.USE', () => {
mockUseHasAccess.mockReturnValue(false);
- renderHook(() => useAppStartup({ startupConfig: undefined, user: mockUser }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: true }),
+ { wrapper },
+ );
expect(mockUseMCPServersQuery).toHaveBeenCalledWith({ enabled: false });
expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: false });
@@ -105,7 +112,10 @@ describe('useAppStartup: MCP permission gating', () => {
mockUseHasAccess.mockReturnValue(true);
mockUseCatalogReady.mockReturnValue(false);
- renderHook(() => useAppStartup({ startupConfig: undefined, user: mockUser }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: true }),
+ { wrapper },
+ );
expect(mockUseCatalogReady).toHaveBeenCalledWith('mcpServers');
expect(mockUseCatalogReady).toHaveBeenCalledWith('mcpTools');
@@ -120,12 +130,49 @@ describe('useAppStartup: MCP permission gating', () => {
isLoading: false,
});
- renderHook(() => useAppStartup({ startupConfig: undefined, user: mockUser }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: true }),
+ {
+ wrapper,
+ },
+ );
expect(mockUseMCPServersQuery).toHaveBeenCalledWith({ enabled: true });
expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: true });
});
+ it('waits for the host to allow MCP warmup', () => {
+ mockUseHasAccess.mockReturnValue(true);
+ mockUseMCPServersQuery.mockReturnValue({
+ data: { 'test-server': { url: 'http://test' } },
+ isLoading: false,
+ });
+
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: false }),
+ { wrapper },
+ );
+
+ expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: false });
+ });
+
+ it('suppresses background tool discovery for an ephemeral agent conversation', () => {
+ mockUseHasAccess.mockReturnValue(true);
+ mockUseMCPServersQuery.mockReturnValue({
+ data: { 'test-server': { url: 'http://test' } },
+ isLoading: false,
+ });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: false }),
+ {
+ wrapper,
+ },
+ );
+
+ expect(mockUseMCPServersQuery).toHaveBeenCalledWith({ enabled: true });
+ expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: false });
+ });
+
it('suppresses tools query when permission granted but user prop is undefined', () => {
mockUseHasAccess.mockReturnValue(true);
mockUseMCPServersQuery.mockReturnValue({
@@ -133,7 +180,10 @@ describe('useAppStartup: MCP permission gating', () => {
isLoading: false,
});
- renderHook(() => useAppStartup({ startupConfig: undefined, user: undefined }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: undefined, mcpWarmupAllowed: true }),
+ { wrapper },
+ );
expect(mockUseMCPServersQuery).toHaveBeenCalledWith({ enabled: true });
expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: false });
@@ -143,7 +193,10 @@ describe('useAppStartup: MCP permission gating', () => {
mockUseHasAccess.mockReturnValue(true);
mockUseMCPServersQuery.mockReturnValue({ data: {}, isLoading: false });
- renderHook(() => useAppStartup({ startupConfig: undefined, user: mockUser }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: true }),
+ { wrapper },
+ );
expect(mockUseMCPServersQuery).toHaveBeenCalledWith({ enabled: true });
expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: false });
@@ -153,7 +206,10 @@ describe('useAppStartup: MCP permission gating', () => {
mockUseHasAccess.mockReturnValue(true);
mockUseMCPServersQuery.mockReturnValue({ data: undefined, isLoading: true });
- renderHook(() => useAppStartup({ startupConfig: undefined, user: mockUser }), { wrapper });
+ renderHook(
+ () => useAppStartup({ startupConfig: undefined, user: mockUser, mcpWarmupAllowed: true }),
+ { wrapper },
+ );
expect(mockUseMCPToolsQuery).toHaveBeenCalledWith({ enabled: false });
});
@@ -169,7 +225,9 @@ describe('useAppStartup: MCP permission gating', () => {
},
} as never;
- renderHook(() => useAppStartup({ startupConfig, user: mockUser }), { wrapper });
+ renderHook(() => useAppStartup({ startupConfig, user: mockUser, mcpWarmupAllowed: true }), {
+ wrapper,
+ });
expect(mockInstallCloudFrontImageRetry).toHaveBeenCalledWith(startupConfig, {
getAuthorizationHeader: expect.any(Function),
diff --git a/client/src/hooks/Config/useAppStartup.ts b/client/src/hooks/Config/useAppStartup.ts
index bf644ed9df..4c9cd134e0 100644
--- a/client/src/hooks/Config/useAppStartup.ts
+++ b/client/src/hooks/Config/useAppStartup.ts
@@ -19,9 +19,11 @@ import store from '~/store';
export default function useAppStartup({
startupConfig,
user,
+ mcpWarmupAllowed,
}: {
startupConfig?: TStartupConfig;
user?: TUser;
+ mcpWarmupAllowed: boolean;
}) {
const [defaultPreset, setDefaultPreset] = useRecoilState(store.defaultPreset);
const canUseMcp = useHasAccess({
@@ -45,6 +47,7 @@ export default function useAppStartup({
!serversLoading &&
!!loadedServers &&
Object.keys(loadedServers).length > 0 &&
+ mcpWarmupAllowed &&
!!user,
});
diff --git a/client/src/hooks/MCP/__tests__/polling.spec.ts b/client/src/hooks/MCP/__tests__/polling.spec.ts
index 8b9ccec481..f4e6a931c7 100644
--- a/client/src/hooks/MCP/__tests__/polling.spec.ts
+++ b/client/src/hooks/MCP/__tests__/polling.spec.ts
@@ -1,4 +1,5 @@
import {
+ applyMCPDiscoveryAuthorizationState,
getMCPOAuthTimeout,
getMCPOAuthPollingOutcome,
isMCPReadyAfterOAuth,
@@ -7,6 +8,122 @@ import {
shouldUseMCPConnectionStatus,
} from '../polling';
+describe('applyMCPDiscoveryAuthorizationState', () => {
+ it('overrides stale connected status when catalog discovery requires reauthorization', () => {
+ const result = applyMCPDiscoveryAuthorizationState(
+ {
+ oauth: {
+ requiresOAuth: true,
+ connectionState: 'connected',
+ authorizationState: 'authorized',
+ authorizationGeneration: 'generation-1',
+ },
+ },
+ {
+ servers: {
+ oauth: {
+ name: 'oauth',
+ icon: '',
+ authenticated: false,
+ authorizationState: 'reauth_required',
+ authorizationGeneration: 'generation-1',
+ authConfig: [],
+ tools: [],
+ },
+ },
+ },
+ );
+
+ expect(result?.oauth).toEqual({
+ requiresOAuth: true,
+ connectionState: 'disconnected',
+ authorizationState: 'needs_authorization',
+ authorizationGeneration: 'generation-1',
+ });
+ });
+
+ it('keeps status from a newer shared authorization generation', () => {
+ const currentStatus = {
+ oauth: {
+ requiresOAuth: true,
+ connectionState: 'connected' as const,
+ authorizationState: 'authorized' as const,
+ authorizationGeneration: 'generation-2',
+ },
+ };
+ const result = applyMCPDiscoveryAuthorizationState(currentStatus, {
+ servers: {
+ oauth: {
+ name: 'oauth',
+ icon: '',
+ authenticated: false,
+ authorizationState: 'reauth_required',
+ authorizationGeneration: 'generation-1',
+ authConfig: [],
+ tools: [],
+ },
+ },
+ });
+
+ expect(result).toBe(currentStatus);
+ });
+
+ it.each([
+ ['missing discovery generation', undefined, 'generation-2'],
+ ['missing status generation', 'generation-1', undefined],
+ ])('keeps authorized status with %s', (_label, discoveryGeneration, statusGeneration) => {
+ const currentStatus = {
+ oauth: {
+ requiresOAuth: true,
+ connectionState: 'connected' as const,
+ authorizationState: 'authorized' as const,
+ authorizationGeneration: statusGeneration,
+ },
+ };
+ const result = applyMCPDiscoveryAuthorizationState(currentStatus, {
+ servers: {
+ oauth: {
+ name: 'oauth',
+ icon: '',
+ authenticated: false,
+ authorizationState: 'reauth_required',
+ authorizationGeneration: discoveryGeneration,
+ authConfig: [],
+ tools: [],
+ },
+ },
+ });
+
+ expect(result).toBe(currentStatus);
+ });
+
+ it('preserves an active OAuth flow over cached reauthorization state', () => {
+ const currentStatus = {
+ oauth: {
+ requiresOAuth: true,
+ connectionState: 'connecting' as const,
+ authorizationState: 'authorizing' as const,
+ authorizationGeneration: 'generation-1',
+ },
+ };
+ const result = applyMCPDiscoveryAuthorizationState(currentStatus, {
+ servers: {
+ oauth: {
+ name: 'oauth',
+ icon: '',
+ authenticated: false,
+ authorizationState: 'reauth_required',
+ authorizationGeneration: 'generation-1',
+ authConfig: [],
+ tools: [],
+ },
+ },
+ });
+
+ expect(result).toBe(currentStatus);
+ });
+});
+
describe('getMCPOAuthTimeout', () => {
it('preserves the remaining timeout of a reused flow over the global server window', () => {
expect(getMCPOAuthTimeout(45_000, 600_000)).toBe(45_000);
diff --git a/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx b/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx
index 6704435a0b..263382214b 100644
--- a/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx
+++ b/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx
@@ -9,6 +9,8 @@ import { useMCPServerManager } from '../useMCPServerManager';
const mockShowToast = jest.fn();
const mockSetMCPValues = jest.fn();
const mockReinitialize = jest.fn();
+const mockUseMCPToolsQuery = jest.fn((_options?: unknown) => ({ data: undefined }));
+const mockUseMCPConnectionStatus = jest.fn((_options?: unknown) => ({ connectionStatus: {} }));
jest.mock('@librechat/client', () => ({
useToastContext: () => ({ showToast: mockShowToast }),
@@ -19,12 +21,13 @@ jest.mock('~/hooks', () => ({
useHasAccess: () => true,
useCatalogReady: () => true,
useMCPSelect: () => ({ mcpValues: [], setMCPValues: mockSetMCPValues }),
- useMCPConnectionStatus: () => ({ connectionStatus: {} }),
+ useMCPConnectionStatus: (options: unknown) => mockUseMCPConnectionStatus(options),
}));
jest.mock('~/data-provider', () => ({
useGetStartupConfig: () => ({ data: {} }),
useMCPServersQuery: () => ({ data: {}, isLoading: false }),
+ useMCPToolsQuery: (options: unknown) => mockUseMCPToolsQuery(options),
}));
jest.mock('librechat-data-provider/react-query', () => ({
@@ -45,6 +48,22 @@ function deferred<T>() {
}
describe('useMCPServerManager initialization', () => {
+ it('keeps passive authorization observers opt-in for shared hook callers', () => {
+ const queryClient = new QueryClient();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider>
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ </Provider>
+ );
+
+ const { unmount } = renderHook(() => useMCPServerManager(), { wrapper });
+
+ expect(mockUseMCPToolsQuery).toHaveBeenLastCalledWith({ enabled: false });
+ expect(mockUseMCPConnectionStatus).toHaveBeenLastCalledWith({ enabled: false });
+ unmount();
+ queryClient.clear();
+ });
+
it.each(['success', 'error'])(
'finishes before a slow catalog refetch ends in %s',
async (outcome) => {
diff --git a/client/src/hooks/MCP/polling.ts b/client/src/hooks/MCP/polling.ts
index 325b3bb666..1014ac731c 100644
--- a/client/src/hooks/MCP/polling.ts
+++ b/client/src/hooks/MCP/polling.ts
@@ -1,9 +1,55 @@
import type {
MCPServerStatus,
+ MCPServersResponse,
MCPOAuthStatusResponse,
MCPReinitializeResponse,
} from 'librechat-data-provider';
+export function applyMCPDiscoveryAuthorizationState(
+ connectionStatus: Record<string, MCPServerStatus> | undefined,
+ discoveredTools: MCPServersResponse | undefined,
+): Record<string, MCPServerStatus> | undefined {
+ const reauthRequired = Object.entries(discoveredTools?.servers ?? {})
+ .filter(([, server]) => server.authorizationState === 'reauth_required')
+ .map(([serverName]) => serverName);
+ if (reauthRequired.length === 0) {
+ return connectionStatus;
+ }
+
+ const nextStatus = { ...(connectionStatus ?? {}) };
+ let changed = false;
+ for (const serverName of reauthRequired) {
+ const discoveryGeneration = discoveredTools?.servers[serverName]?.authorizationGeneration;
+ const current = nextStatus?.[serverName];
+ const statusGeneration = current?.authorizationGeneration;
+ const statusIsActive =
+ current?.connectionState === 'connecting' || current?.authorizationState === 'authorizing';
+ if (statusIsActive) {
+ continue;
+ }
+ const statusAuthorizes =
+ current?.connectionState === 'connected' || current?.authorizationState === 'authorized';
+ if (statusAuthorizes && (discoveryGeneration == null || statusGeneration == null)) {
+ continue;
+ }
+ if (
+ discoveryGeneration != null &&
+ statusGeneration != null &&
+ discoveryGeneration !== statusGeneration
+ ) {
+ continue;
+ }
+ changed = true;
+ nextStatus[serverName] = {
+ ...current,
+ requiresOAuth: true,
+ connectionState: 'disconnected',
+ authorizationState: 'needs_authorization',
+ };
+ }
+ return changed ? nextStatus : connectionStatus;
+}
+
export type MCPOAuthPollingOutcome = 'pending' | 'completed' | 'failed';
export function getMCPOAuthTimeout(
diff --git a/client/src/hooks/MCP/useMCPServerManager.ts b/client/src/hooks/MCP/useMCPServerManager.ts
index 1a2b82fa95..682fef7a4d 100644
--- a/client/src/hooks/MCP/useMCPServerManager.ts
+++ b/client/src/hooks/MCP/useMCPServerManager.ts
@@ -33,6 +33,7 @@ import {
shouldFailMCPOAuthFallback,
isTerminalMCPOAuthPollingError,
shouldUseMCPConnectionStatus,
+ applyMCPDiscoveryAuthorizationState,
} from './polling';
import {
useLocalize,
@@ -41,7 +42,7 @@ import {
useCatalogReady,
useMCPConnectionStatus,
} from '~/hooks';
-import { useGetStartupConfig, useMCPServersQuery } from '~/data-provider';
+import { useGetStartupConfig, useMCPServersQuery, useMCPToolsQuery } from '~/data-provider';
import { mcpServerInitStatesAtom, getServerInitState } from '~/store/mcp';
import { getMCPReinitializeErrorMessage } from './errors';
@@ -64,6 +65,7 @@ export function useMCPServerManager({
storageContextKey,
specName,
ownsChatSelection = false,
+ observeToolAuthorization = false,
}: {
conversationId?: string | null;
storageContextKey?: string;
@@ -76,6 +78,8 @@ export function useMCPServerManager({
* needed to prune it correctly.
*/
ownsChatSelection?: boolean;
+ /** Allows hosts that suppress MCP catalog work (such as ephemeral agents) to reuse the manager. */
+ observeToolAuthorization?: boolean;
} = {}) {
const localize = useLocalize();
const queryClient = useQueryClient();
@@ -92,6 +96,14 @@ export function useMCPServerManager({
const mcpEnabled = canUseMcp && mcpServersReady;
const { data: loadedServers, isLoading } = useMCPServersQuery({ enabled: mcpEnabled });
+ const mcpToolsReady = useCatalogReady('mcpTools');
+ const { data: discoveredMCPTools } = useMCPToolsQuery({
+ enabled:
+ observeToolAuthorization &&
+ mcpEnabled &&
+ mcpToolsReady &&
+ Object.keys(loadedServers ?? {}).length > 0,
+ });
// Fetch effective permissions for all MCP servers
const { data: permissionsMap } = useGetAllEffectivePermissionsQuery(ResourceType.MCPSERVER, {
@@ -197,11 +209,11 @@ export function useMCPServerManager({
const pollIntervalsRef = useRef<PollIntervals>({});
const { connectionStatus: polledConnectionStatus } = useMCPConnectionStatus({
- enabled: !isLoading && availableMCPServers.length > 0,
+ enabled: observeToolAuthorization && !isLoading && availableMCPServers.length > 0,
});
const connectionStatus = useMemo(() => {
if (!polledConnectionStatus) {
- return polledConnectionStatus;
+ return applyMCPDiscoveryAuthorizationState(polledConnectionStatus, discoveredMCPTools);
}
let changed = false;
@@ -214,8 +226,9 @@ export function useMCPServerManager({
changed = true;
nextStatus[serverName] = { ...status, requestScoped: true };
}
- return changed ? nextStatus : polledConnectionStatus;
- }, [polledConnectionStatus, loadedServers]);
+ const normalizedStatus = changed ? nextStatus : polledConnectionStatus;
+ return applyMCPDiscoveryAuthorizationState(normalizedStatus, discoveredMCPTools);
+ }, [polledConnectionStatus, loadedServers, discoveredMCPTools]);
const updateServerInitState = useCallback(
(serverName: string, updates: Partial<MCPServerInitState>) => {
diff --git a/client/src/routes/ChatRoute.tsx b/client/src/routes/ChatRoute.tsx
index 94797e6f5b..837227bc35 100644
--- a/client/src/routes/ChatRoute.tsx
+++ b/client/src/routes/ChatRoute.tsx
@@ -4,7 +4,13 @@ import { useRecoilCallback, useRecoilValue } from 'recoil';
import { Spinner, useToastContext } from '@librechat/client';
import { useParams, useSearchParams } from 'react-router-dom';
import { useGetModelsQuery } from 'librechat-data-provider/react-query';
-import { Constants, EModelEndpoint, PermissionBits } from 'librechat-data-provider';
+import {
+ Constants,
+ EModelEndpoint,
+ PermissionBits,
+ isAgentsEndpoint,
+ isEphemeralAgentId,
+} from 'librechat-data-provider';
import type { TPreset, TAgentsMap } from 'librechat-data-provider';
import {
defaultSpecAwaitsAgents,
@@ -55,8 +61,6 @@ export default function ChatRoute() {
},
[],
);
- useAppStartup({ startupConfig, user });
-
const index = 0;
const [searchParams, setSearchParams] = useSearchParams();
const { conversationId = '' } = useParams();
@@ -64,6 +68,10 @@ export default function ChatRoute() {
const chatProjectId = isValidChatProjectId(projectIdParam) ? projectIdParam : null;
useIdChangeEffect(conversationId);
const { hasSetConversation, conversation } = store.useCreateConversationAtom(index);
+ const mcpWarmupAllowed =
+ conversation != null &&
+ !(isAgentsEndpoint(conversation.endpoint) && isEphemeralAgentId(conversation.agent_id ?? ''));
+ useAppStartup({ startupConfig, user, mcpWarmupAllowed });
const { newConversation } = useNewConvo();
const { showToast } = useToastContext();
const localize = useLocalize();
diff --git a/packages/api/src/flow/manager.test.ts b/packages/api/src/flow/manager.test.ts
index 3b90f2b87a..04c2aacad4 100644
--- a/packages/api/src/flow/manager.test.ts
+++ b/packages/api/src/flow/manager.test.ts
@@ -149,6 +149,60 @@ describe('FlowStateManager', () => {
});
});
+ it('settles a fresher result over a completion from the same observed attempt', async () => {
+ await flowManager.initFlow('token-flow', 'mcp_get_tokens');
+ const flow = await flowManager.getFlowState('token-flow', 'mcp_get_tokens');
+ await flowManager.completeFlow('token-flow', 'mcp_get_tokens', 'old-token');
+
+ await expect(
+ flowManager.settleFlowIfCurrent(
+ 'token-flow',
+ 'mcp_get_tokens',
+ flow!.createdAt,
+ '',
+ 'fresh-token',
+ ),
+ ).resolves.toBe('updated');
+
+ expect(await flowManager.getFlowState('token-flow', 'mcp_get_tokens')).toMatchObject({
+ status: 'COMPLETED',
+ result: 'fresh-token',
+ });
+ });
+
+ it('settles a fresher result over a failure from the same observed attempt', async () => {
+ await flowManager.initFlow('token-flow', 'mcp_get_tokens');
+ const flow = await flowManager.getFlowState('token-flow', 'mcp_get_tokens');
+ await flowManager.failFlow('token-flow', 'mcp_get_tokens', new Error('stale failure'));
+
+ await expect(
+ flowManager.settleFlowIfCurrent(
+ 'token-flow',
+ 'mcp_get_tokens',
+ flow!.createdAt,
+ '',
+ 'fresh-token',
+ ),
+ ).resolves.toBe('updated');
+
+ expect(await flowManager.getFlowState('token-flow', 'mcp_get_tokens')).toMatchObject({
+ status: 'COMPLETED',
+ result: 'fresh-token',
+ });
+ });
+
+ it('does not settle a replacement token-flow attempt', async () => {
+ await flowManager.initFlow('token-flow', 'mcp_get_tokens');
+
+ await expect(
+ flowManager.settleFlowIfCurrent('token-flow', 'mcp_get_tokens', 1, '', 'old-token'),
+ ).resolves.toBe('stale');
+
+ expect(await flowManager.getFlowState('token-flow', 'mcp_get_tokens')).toMatchObject({
+ status: 'PENDING',
+ });
+ });
+
it('fails only the observed OAuth attempt', async () => {
await flowManager.initFlow('oauth-flow', 'mcp_oauth', { state: 'expected-state' });
const flow = await flowManager.getFlowState('oauth-flow', 'mcp_oauth');
@@ -210,6 +264,35 @@ describe('FlowStateManager', () => {
);
});
+ it('should return the externally completed result when handler loses failure race', async () => {
+ const flowId = 'failure-race-flow';
+ const type = 'test-type';
+
+ const result = await flowManager.createFlowWithHandler(flowId, type, async () => {
+ await flowManager.completeFlow(flowId, type, 'fresh-result');
+ throw new Error('stale failure');
+ });
+
+ expect(result).toBe('fresh-result');
+ });
+
+ it('should re-read completion that wins after its guarded failure write', async () => {
+ const flowId = 'post-failure-race-flow';
+ const type = 'test-type';
+ const originalFail = flowManager.failFlowIfCurrent.bind(flowManager);
+ jest.spyOn(flowManager, 'failFlowIfCurrent').mockImplementation(async (...args) => {
+ const failureResult = await originalFail(...args);
+ await flowManager.settleFlowIfCurrent(flowId, type, args[2], args[3], 'fresh-result');
+ return failureResult;
+ });
+
+ const result = await flowManager.createFlowWithHandler(flowId, type, async () => {
+ throw new Error('stale failure');
+ });
+
+ expect(result).toBe('fresh-result');
+ });
+
it('should handle flow timeout correctly', async () => {
const flowId = 'timeout-flow';
const type = 'test-type';
diff --git a/packages/api/src/flow/manager.ts b/packages/api/src/flow/manager.ts
index cffc521c9b..6abfa24eaf 100644
--- a/packages/api/src/flow/manager.ts
+++ b/packages/api/src/flow/manager.ts
@@ -76,6 +76,24 @@ redis.call('SET', KEYS[1], cjson.encode(data), 'PX', ARGV[5])
return 1
`;
+/** Replaces either a pending or completed result for the exact observed attempt. This is used
+ * when a fresher durable credential must win a race with the handler that loaded the old one. */
+const GUARDED_SETTLE_FLOW = `
+local raw = redis.call('GET', KEYS[1])
+if not raw then return 0 end
+local data = cjson.decode(raw)
+local flow = data.value
+if flow.createdAt ~= tonumber(ARGV[1]) then return -1 end
+local state = flow.metadata and flow.metadata.state or ''
+if state ~= ARGV[2] then return -1 end
+flow.status = 'COMPLETED'
+flow.result = cjson.decode(ARGV[3])
+flow.completedAt = tonumber(ARGV[4])
+data.expires = tonumber(ARGV[4]) + tonumber(ARGV[5])
+redis.call('SET', KEYS[1], cjson.encode(data), 'PX', ARGV[5])
+return 1
+`;
+
const READ_LEASE_GENERATION = `
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
@@ -521,6 +539,59 @@ export class FlowStateManager<T = unknown> {
return 'updated';
}
+ /** Publishes an authoritative result for the exact observed attempt even if its handler settled
+ * while the caller was committing a fresher durable value. A replacement attempt is untouched. */
+ async settleFlowIfCurrent(
+ flowId: string,
+ type: string,
+ expectedCreatedAt: number,
+ expectedState: string,
+ result: T,
+ ): Promise<GuardedMutationResult> {
+ const flowKey = this.getFlowKey(flowId, type);
+ const completedAt = Date.now();
+ const redisKey = this.getRedisKey(flowKey);
+ if (redisKey) {
+ const guardedResult = await this.evalRedisScript(GUARDED_SETTLE_FLOW, redisKey, [
+ String(expectedCreatedAt),
+ expectedState,
+ JSON.stringify(result) ?? 'null',
+ String(completedAt),
+ String(this.ttl),
+ ]);
+ return FlowStateManager.guardedResult(guardedResult);
+ }
+
+ const settle = (current: FlowState<T>): FlowState<T> | null => {
+ if (!FlowStateManager.isCurrentAttempt(current, expectedCreatedAt, expectedState)) {
+ return null;
+ }
+ return { ...current, status: 'COMPLETED', result, completedAt };
+ };
+ const memoryEntry = this.getInMemoryEntry(flowKey);
+ if (memoryEntry) {
+ const updated = settle(memoryEntry.envelope.value);
+ if (updated == null) {
+ return 'stale';
+ }
+ memoryEntry.envelope.value = updated;
+ memoryEntry.envelope.expires = completedAt + this.ttl;
+ memoryEntry.store.set(memoryEntry.key, JSON.stringify(memoryEntry.envelope));
+ return 'updated';
+ }
+
+ const current = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;
+ if (!current) {
+ return 'missing';
+ }
+ const updated = settle(current);
+ if (updated == null) {
+ return 'stale';
+ }
+ await this.keyv.set(flowKey, updated, this.ttl);
+ return 'updated';
+ }
+
private isTokenExpired(flowState: FlowState<T> | undefined): boolean {
if (!flowState?.result || typeof flowState.result !== 'object') {
return false;
@@ -893,14 +964,28 @@ export class FlowStateManager<T = unknown> {
try {
const result = await handler();
- await this.completeFlow(flowId, type, result);
+ await this.completeFlowIfCurrent(flowId, type, initialState.createdAt, '', result);
const completedState = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;
if (completedState?.status === 'COMPLETED' && completedState.result !== undefined) {
return completedState.result;
}
return result;
} catch (error) {
- await this.failFlow(flowId, type, error instanceof Error ? error : new Error(String(error)));
+ await this.failFlowIfCurrent(
+ flowId,
+ type,
+ initialState.createdAt,
+ '',
+ error instanceof Error ? error : new Error(String(error)),
+ );
+ const settledState = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;
+ if (
+ settledState?.status === 'COMPLETED' &&
+ settledState.result !== undefined &&
+ FlowStateManager.isCurrentAttempt(settledState, initialState.createdAt, '')
+ ) {
+ return settledState.result;
+ }
throw error;
}
}
diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts
index 3262c4dade..f2dfa931c2 100644
--- a/packages/api/src/index.ts
+++ b/packages/api/src/index.ts
@@ -29,6 +29,8 @@ export * from './mcp/cache';
export * from './mcp/tools';
export * from './mcp/catalog/store';
export * from './mcp/catalog/recovery';
+export * from './mcp/authorization';
+export * from './mcp/authorizationRetry';
export * from './mcp/assistants';
export * from './mcp/request';
export * from './mcp/icons';
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index bc15f82667..8d470d1d87 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -17,6 +17,8 @@ import type { FlowStateManager } from '~/flow/manager';
import type * as t from './types';
import {
MCPTokenStorage,
+ MCPTokenRefreshUnavailableError,
+ MCPTokenStorageUnavailableError,
MCPOAuthHandler,
getMCPServerGeneration,
getMCPOAuthLeaseId,
@@ -88,6 +90,8 @@ export class MCPConnectionFactory {
protected returnOnOAuth?: boolean;
protected readonly connectionTimeout?: number;
protected readonly deadlineMs?: number;
+ protected readonly onOAuthCredentialsChanged?: t.UserConnectionContext['onOAuthCredentialsChanged'];
+ protected readonly onOAuthCredentialsChanging?: t.UserConnectionContext['onOAuthCredentialsChanging'];
protected readonly oboTokenResolver?: OboTokenResolver;
protected readonly oboTrustChecker?: OboTrustChecker;
protected upstreamTokenProvider?: UpstreamTokenProvider;
@@ -575,6 +579,8 @@ export class MCPConnectionFactory {
);
this.connectionTimeout = options?.connectionTimeout;
this.deadlineMs = options?.deadlineMs;
+ this.onOAuthCredentialsChanged = options?.onOAuthCredentialsChanged;
+ this.onOAuthCredentialsChanging = options?.onOAuthCredentialsChanging;
this.signal = options?.signal;
this.tenantContext = tenantStorage?.getStore?.();
this.tenantId = this.tenantContext?.tenantId ?? getTenantId();
@@ -891,6 +897,8 @@ export class MCPConnectionFactory {
refreshTokens: this.createRefreshTokensFunction(),
singleFlightScope: this.getOAuthBindingDigest(),
flowManager: this.flowManager,
+ onRefreshSuccess: (refreshed) => this.handleOAuthRefreshSuccess(refreshed),
+ onRefreshPreparing: () => this.prepareOAuthRefreshSuccess(),
}),
);
},
@@ -937,6 +945,16 @@ export class MCPConnectionFactory {
logger.info(`${this.logPrefix} Reauthentication required; triggering OAuth flow`);
return null;
}
+ if (
+ error instanceof MCPTokenStorageUnavailableError ||
+ error instanceof MCPTokenRefreshUnavailableError ||
+ (error instanceof Error &&
+ (error.name === 'MCPTokenStorageUnavailableError' ||
+ error.name === 'MCPTokenRefreshUnavailableError'))
+ ) {
+ logger.warn(`${this.logPrefix} OAuth token loading failed; deferring connection recovery`);
+ throw error;
+ }
logger.debug(`${this.logPrefix} No existing tokens found or token loading failed`);
return null;
}
@@ -1080,9 +1098,8 @@ export class MCPConnectionFactory {
* (not this waiter) so a refresh that completes after this caller's
* timeout still invalidates the cache.
*/
- onRefreshSuccess: async (refreshed) => {
- await this.invalidateGetTokensFlow(refreshed);
- },
+ onRefreshSuccess: (refreshed) => this.handleOAuthRefreshSuccess(refreshed),
+ onRefreshPreparing: () => this.prepareOAuthRefreshSuccess(),
flowManager: this.flowManager,
}),
);
@@ -1112,6 +1129,46 @@ export class MCPConnectionFactory {
* entries are deleted; PENDING entries are completed with fresh tokens so
* concurrent waiters do not fail or later publish server-rejected tokens.
*/
+ private async handleOAuthRefreshSuccess(freshTokens: MCPOAuthTokens): Promise<void> {
+ if (this.userId != null) {
+ await this.onOAuthCredentialsChanged?.({
+ userId: this.userId,
+ serverName: this.serverName,
+ });
+ }
+ await this.invalidateGetTokensFlow(freshTokens);
+ }
+
+ private async prepareOAuthRefreshSuccess(): Promise<
+ (freshTokens?: MCPOAuthTokens) => Promise<void>
+ > {
+ const publishPreparedMutation =
+ this.userId == null
+ ? undefined
+ : await this.onOAuthCredentialsChanging?.({
+ userId: this.userId,
+ serverName: this.serverName,
+ });
+ return async (freshTokens) => {
+ if (publishPreparedMutation != null) {
+ await publishPreparedMutation();
+ await this.invalidateGetTokensFlow(freshTokens);
+ return;
+ }
+ if (freshTokens != null) {
+ await this.handleOAuthRefreshSuccess(freshTokens);
+ } else {
+ if (this.userId != null) {
+ await this.onOAuthCredentialsChanged?.({
+ userId: this.userId,
+ serverName: this.serverName,
+ });
+ }
+ await this.invalidateGetTokensFlow();
+ }
+ };
+ }
+
protected async invalidateGetTokensFlow(freshTokens?: MCPOAuthTokens): Promise<void> {
if (!this.flowManager || !this.userId) {
return;
diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.ts
index 5a126fe7b1..fcc0e76e39 100644
--- a/packages/api/src/mcp/MCPManager.ts
+++ b/packages/api/src/mcp/MCPManager.ts
@@ -27,6 +27,7 @@ import { MCPAuthenticationRejectedError, isMCPTransportAuthenticationError } fro
import { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from './openid';
import { MCPServersInitializer } from './registry/MCPServersInitializer';
import { OboTokenResolutionError, resolveOboToken } from '~/mcp/oauth';
+import { MCPServerCatalogRecoveryTracker } from './catalog/recovery';
import { MCPServerInspector } from './registry/MCPServerInspector';
import { MCPServersRegistry } from './registry/MCPServersRegistry';
import { UserConnectionManager } from './UserConnectionManager';
@@ -72,12 +73,26 @@ type OAuthReconnectResult =
const OAUTH_RECOVERY_RECONNECT_ATTEMPTS = 3;
const OAUTH_RECOVERY_RECONNECT_DELAY_MS = 2000;
+function getDiscoveryAuthenticationKind(
+ serverConfig: t.ParsedServerConfig,
+ observedOAuthRequired = false,
+): 'oauth' | 'obo' | 'server' {
+ if (serverConfig.obo != null) {
+ return 'obo';
+ }
+ return isOAuthServer(serverConfig) ||
+ (observedOAuthRequired && serverConfig.requiresOAuth !== false)
+ ? 'oauth'
+ : 'server';
+}
+
/**
* Centralized manager for MCP server connections and tool execution.
* Extends UserConnectionManager to handle both app-level and user-specific connections.
*/
export class MCPManager extends UserConnectionManager {
private static instance: MCPManager | null;
+ private readonly catalogRecoveryTracker: MCPServerCatalogRecoveryTracker;
private readonly recoveryCancellation = new WeakMap<
Promise<void>,
{ controller: AbortController; waiters: number; connection: MCPConnection }
@@ -95,10 +110,20 @@ export class MCPManager extends UserConnectionManager {
}
>();
+ constructor(catalogRecoveryMaxStateEntries?: number) {
+ super();
+ this.catalogRecoveryTracker = new MCPServerCatalogRecoveryTracker(
+ catalogRecoveryMaxStateEntries,
+ );
+ }
+
/** Creates and initializes the singleton MCPManager instance */
- public static async createInstance(configs: t.MCPServers): Promise<MCPManager> {
+ public static async createInstance(
+ configs: t.MCPServers,
+ options?: { catalogRecoveryMaxStateEntries?: number },
+ ): Promise<MCPManager> {
if (MCPManager.instance) throw new Error('MCPManager has already been initialized.');
- MCPManager.instance = new MCPManager();
+ MCPManager.instance = new MCPManager(options?.catalogRecoveryMaxStateEntries);
await MCPManager.instance.initialize(configs);
return MCPManager.instance;
}
@@ -115,6 +140,25 @@ export class MCPManager extends UserConnectionManager {
this.appConnections = new ConnectionsRepository(undefined);
}
+ public getCatalogRecoveryTracker(): MCPServerCatalogRecoveryTracker {
+ return this.catalogRecoveryTracker;
+ }
+
+ public clearCatalogRecoveryState(userId: string, serverName?: string): void {
+ this.catalogRecoveryTracker.clear(userId, serverName);
+ }
+
+ public override async disconnectUserConnection(
+ userId: string,
+ serverName: string,
+ options?: Parameters<UserConnectionManager['disconnectUserConnection']>[2],
+ ): Promise<void> {
+ if ((options?.reason ?? 'mutation') === 'mutation') {
+ this.clearCatalogRecoveryState(userId, serverName);
+ }
+ await super.disconnectUserConnection(userId, serverName, options);
+ }
+
public override async getUserConnection(
opts: t.UserMCPConnectionOptions,
): Promise<MCPConnection> {
@@ -433,6 +477,9 @@ export class MCPManager extends UserConnectionManager {
tools: result.tools,
oauthRequired: result.oauthRequired,
oauthUrl: result.oauthUrl,
+ ...(result.oauthRequired && {
+ authenticationKind: getDiscoveryAuthenticationKind(serverConfig, true),
+ }),
};
};
@@ -452,7 +499,12 @@ export class MCPManager extends UserConnectionManager {
if (!user || !args.flowManager) {
logger.warn('[MCP][Discovery] OAuth server requires a user and flow manager');
- return { tools: null, oauthRequired: true, oauthUrl: null };
+ return {
+ tools: null,
+ oauthRequired: true,
+ oauthUrl: null,
+ authenticationKind: getDiscoveryAuthenticationKind(serverConfig),
+ };
}
const result = await MCPConnectionFactory.discoverTools(basic, {
@@ -467,6 +519,8 @@ export class MCPManager extends UserConnectionManager {
graphTokenResolver: args.graphTokenResolver,
connectionTimeout: args.connectionTimeout,
deadlineMs: args.deadlineMs,
+ onOAuthCredentialsChanged: args.onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging: args.onOAuthCredentialsChanging,
oboTokenResolver: args.oboTokenResolver,
oboTrustChecker: args.oboTrustChecker,
upstreamTokenProvider: args.upstreamTokenProvider,
@@ -777,6 +831,8 @@ Please follow these instructions when using tools from the respective MCP server
graphTokenResolver,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
signal,
directBearerRecoveryState = { attempted: true },
}: {
@@ -794,6 +850,8 @@ Please follow these instructions when using tools from the respective MCP server
graphTokenResolver?: GraphTokenResolver;
upstreamTokenProvider?: UpstreamTokenProvider;
oboIdentityContext?: AuthIdentityContext;
+ onOAuthCredentialsChanged?: t.UserConnectionContext['onOAuthCredentialsChanged'];
+ onOAuthCredentialsChanging?: t.UserConnectionContext['onOAuthCredentialsChanging'];
signal?: AbortSignal;
directBearerRecoveryState?: t.DirectBearerRecoveryState;
}): Promise<void> {
@@ -851,6 +909,8 @@ Please follow these instructions when using tools from the respective MCP server
graphTokenResolver,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
directBearerRecoveryState,
directBearerResolvedConfig: refreshedConfig,
signal: recoverySignal,
@@ -1023,6 +1083,8 @@ Please follow these instructions when using tools from the respective MCP server
oboTrustChecker,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
}: {
user?: IUser;
serverName: string;
@@ -1044,6 +1106,8 @@ Please follow these instructions when using tools from the respective MCP server
oboTrustChecker?: OboTrustChecker;
upstreamTokenProvider?: UpstreamTokenProvider;
oboIdentityContext?: AuthIdentityContext;
+ onOAuthCredentialsChanged?: t.UserConnectionContext['onOAuthCredentialsChanged'];
+ onOAuthCredentialsChanging?: t.UserConnectionContext['onOAuthCredentialsChanging'];
}): Promise<t.FormattedToolResponse> {
const userId = user?.id;
const logPrefix = userId ? `[MCP][User: ${userId}][${serverName}]` : `[MCP][${serverName}]`;
@@ -1106,6 +1170,8 @@ Please follow these instructions when using tools from the respective MCP server
oboTrustChecker,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
graphTokenResolver,
signal: options?.signal,
customUserVars,
@@ -1298,6 +1364,8 @@ Please follow these instructions when using tools from the respective MCP server
oauthEnd: relay.end,
customUserVars,
requestBody,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
},
connection!,
);
@@ -1347,6 +1415,8 @@ Please follow these instructions when using tools from the respective MCP server
graphTokenResolver,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
signal: options?.signal,
directBearerRecoveryState,
});
@@ -1435,6 +1505,8 @@ Please follow these instructions when using tools from the respective MCP server
graphTokenResolver,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
signal: options?.signal,
directBearerRecoveryState,
});
diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.ts
index a38c27bce4..9fa5537578 100644
--- a/packages/api/src/mcp/UserConnectionManager.ts
+++ b/packages/api/src/mcp/UserConnectionManager.ts
@@ -584,6 +584,8 @@ export abstract class UserConnectionManager {
oboTrustChecker,
upstreamTokenProvider,
oboIdentityContext,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
signal,
returnOnOAuth = false,
connectionTimeout,
@@ -823,6 +825,8 @@ export abstract class UserConnectionManager {
returnOnOAuth: returnOnOAuth,
requestBody: requestBody,
connectionTimeout: connectionTimeout,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
};
} else {
connectionOptions = {
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
index d77dc30d41..eb00688506 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -3,7 +3,12 @@ import type { TokenMethods, IUser } from '@librechat/data-schemas';
import type { FlowStateManager } from '~/flow/manager';
import type { MCPOAuthTokens } from '~/mcp/oauth';
import type * as t from '~/mcp/types';
-import { MCPOAuthHandler, MCPTokenStorage, OboTokenResolutionError } from '~/mcp/oauth';
+import {
+ MCPOAuthHandler,
+ MCPTokenStorage,
+ OboTokenResolutionError,
+ ReauthenticationRequiredError,
+} from '~/mcp/oauth';
import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';
import { MCPAuthenticationRejectedError } from '~/mcp/errors';
import { preProcessGraphTokens } from '~/utils/graph';
@@ -659,7 +664,7 @@ describe('MCPConnectionFactory', () => {
mockMCPTokenStorage.assertCredentialSetBinding.mockImplementationOnce(
(_serverName, tokenCredentialSetId, clientMetadata) => {
if (tokenCredentialSetId !== clientMetadata?.credential_set_id) {
- throw new Error('mixed OAuth credential generations');
+ throw new ReauthenticationRequiredError('test-server', 'binding');
}
},
);
@@ -852,7 +857,7 @@ describe('MCPConnectionFactory', () => {
},
);
- it('should handle token retrieval errors gracefully', async () => {
+ it('does not misclassify token storage failures as missing authorization', async () => {
const basicOptions = {
serverName: 'test-server',
serverConfig: mockServerConfig,
@@ -870,25 +875,44 @@ describe('MCPConnectionFactory', () => {
},
};
- mockFlowManager.createFlowWithHandler.mockRejectedValue(new Error('Token fetch failed'));
- mockConnectionInstance.isConnected.mockResolvedValue(true);
-
- const connection = await MCPConnectionFactory.create(basicOptions, oauthOptions);
+ const storageError = new Error('OAuth token storage is unavailable for "test-server"');
+ storageError.name = 'MCPTokenStorageUnavailableError';
+ mockFlowManager.createFlowWithHandler.mockRejectedValue(storageError);
+ await expect(MCPConnectionFactory.create(basicOptions, oauthOptions)).rejects.toThrow(
+ 'OAuth token storage is unavailable',
+ );
+ expect(mockMCPConnection).not.toHaveBeenCalled();
+ expect(mockLogger.warn).toHaveBeenCalledWith(
+ '[MCP][User: user123] OAuth token loading failed; deferring connection recovery',
+ );
+ });
- expect(connection).toBe(mockConnectionInstance);
- expect(mockMCPConnection).toHaveBeenCalledWith({
+ it('does not misclassify transient refresh failures as missing authorization', async () => {
+ const basicOptions = {
serverName: 'test-server',
serverConfig: mockServerConfig,
- userId: 'user123',
- oauthTokens: null,
- useSSRFProtection: false,
- allowedAddresses: undefined,
- ephemeralConnection: false,
- });
- expect(mockLogger.debug).toHaveBeenCalledWith(
- '[MCP][User: user123] No existing tokens found or token loading failed',
+ };
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+ const refreshError = new Error(
+ 'OAuth token refresh is temporarily unavailable for "test-server"',
+ );
+ refreshError.name = 'MCPTokenRefreshUnavailableError';
+ mockFlowManager.createFlowWithHandler.mockRejectedValue(refreshError);
+
+ await expect(MCPConnectionFactory.create(basicOptions, oauthOptions)).rejects.toThrow(
+ 'OAuth token refresh is temporarily unavailable',
);
- expect(JSON.stringify(mockLogger.debug.mock.calls)).not.toContain('Token fetch failed');
+ expect(mockMCPConnection).not.toHaveBeenCalled();
});
});
@@ -1818,11 +1842,13 @@ describe('MCPConnectionFactory', () => {
serverConfig: sseConfig,
};
+ const onOAuthCredentialsChanged = jest.fn().mockResolvedValue(undefined);
const oauthOptions = {
useOAuth: true as const,
user: mockUser,
flowManager: mockFlowManager,
oauthStart: jest.fn(),
+ onOAuthCredentialsChanged,
tokenMethods: {
findToken: jest.fn(),
createToken: jest.fn(),
@@ -1903,6 +1929,10 @@ describe('MCPConnectionFactory', () => {
// The connection receives the FRESHLY refreshed tokens, NOT the stale
// cached ones — that's the whole point of the fix.
expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(freshlyRefreshedTokens);
+ expect(onOAuthCredentialsChanged).toHaveBeenCalledWith({
+ userId: mockUser!.id,
+ serverName: 'test-server',
+ });
expect(mockConnectionInstance.setOAuthTokens).not.toHaveBeenCalledWith(staleCachedTokens);
expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled', 'silent-refresh');
// The cached `mcp_get_tokens` flow state is dropped so the next
diff --git a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
index 4dfe5f26a2..d57f6e0afe 100644
--- a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
+++ b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
@@ -104,4 +104,44 @@ describe('MCP OAuth flow state across Redis-backed instances', () => {
expect.objectContaining({ status: 'FAILED', error: 'cancelled' }),
);
});
+
+ it('settles a fresher result over a completion from the same attempt across pods', async () => {
+ const flowId = createFlowId();
+ await podA.initFlow(flowId, FLOW_TYPE, { state: 'observed-state' });
+ const flow = await podB.getFlowState(flowId, FLOW_TYPE);
+
+ await podA.completeFlow(flowId, FLOW_TYPE, 'stale-result');
+ await expect(
+ podB.settleFlowIfCurrent(
+ flowId,
+ FLOW_TYPE,
+ flow!.createdAt,
+ 'observed-state',
+ 'fresh-result',
+ ),
+ ).resolves.toBe('updated');
+ await expect(podA.getFlowState(flowId, FLOW_TYPE)).resolves.toEqual(
+ expect.objectContaining({ status: 'COMPLETED', result: 'fresh-result' }),
+ );
+ });
+
+ 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' });
+ const flow = await podB.getFlowState(flowId, FLOW_TYPE);
+
+ await podA.failFlow(flowId, FLOW_TYPE, new Error('stale failure'));
+ await expect(
+ podB.settleFlowIfCurrent(
+ flowId,
+ FLOW_TYPE,
+ flow!.createdAt,
+ 'observed-state',
+ 'fresh-result',
+ ),
+ ).resolves.toBe('updated');
+ await expect(podA.getFlowState(flowId, FLOW_TYPE)).resolves.toEqual(
+ expect.objectContaining({ status: 'COMPLETED', result: 'fresh-result' }),
+ );
+ });
});
diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.ts
index 116ae00e4f..09474c1cac 100644
--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts
@@ -2312,6 +2312,37 @@ describe('MCPManager', () => {
requiresOAuth: false,
};
+ it('forwards the OAuth credential mutation callback to the connection factory', async () => {
+ mockAppConnections({
+ has: jest.fn().mockResolvedValue(false),
+ });
+ const connection = {
+ isConnected: jest.fn().mockResolvedValue(true),
+ refreshToolList: jest.fn().mockResolvedValue({ tools: [] }),
+ on: jest.fn(),
+ } as unknown as MCPConnection;
+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(connection);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const onOAuthCredentialsChanged = jest.fn().mockResolvedValue(undefined);
+ const oauthConfig = { ...serverConfig, requiresOAuth: true };
+
+ await manager.getUserConnection({
+ serverName,
+ user: mockUser,
+ serverConfig: oauthConfig,
+ flowManager: {} as Parameters<typeof manager.getUserConnection>[0]['flowManager'],
+ onOAuthCredentialsChanged,
+ });
+
+ expect(MCPConnectionFactory.create).toHaveBeenCalledWith(
+ expect.objectContaining({ serverName }),
+ expect.objectContaining({
+ useOAuth: true,
+ onOAuthCredentialsChanged,
+ }),
+ );
+ });
+
it('waits for an active recovery before reusing a cached connection', async () => {
mockAppConnections({
has: jest.fn().mockResolvedValue(false),
@@ -4068,6 +4099,51 @@ describe('MCPManager', () => {
expect(discoveryConnection.dispose).toHaveBeenCalledTimes(1);
});
+ it('classifies a dynamically detected authentication challenge as OAuth', async () => {
+ mockAppConnections({
+ get: jest.fn().mockResolvedValue(null),
+ });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://api.example.com/mcp',
+ });
+ (MCPConnectionFactory.discoverTools as jest.Mock).mockResolvedValue({
+ tools: null,
+ connection: null,
+ oauthRequired: true,
+ oauthUrl: null,
+ });
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const result = await manager.discoverServerTools({ serverName });
+
+ expect(result.oauthRequired).toBe(true);
+ expect(result.authenticationKind).toBe('oauth');
+ });
+
+ it('keeps an authentication challenge server-managed when OAuth is explicitly disabled', async () => {
+ mockAppConnections({
+ get: jest.fn().mockResolvedValue(null),
+ });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
+ type: 'streamable-http',
+ url: 'https://api.example.com/mcp',
+ requiresOAuth: false,
+ });
+ (MCPConnectionFactory.discoverTools as jest.Mock).mockResolvedValue({
+ tools: null,
+ connection: null,
+ oauthRequired: true,
+ oauthUrl: null,
+ });
+
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const result = await manager.discoverServerTools({ serverName });
+
+ expect(result.oauthRequired).toBe(true);
+ expect(result.authenticationKind).toBe('server');
+ });
+
it('should forward runtime context to discoverTools in the non-OAuth path', async () => {
const mockUser = { id: 'user123', email: '[email protected]' } as unknown as IUser;
const customUserVars = { MY_CUSTOM_KEY: 'c527bd0abc123' };
@@ -4176,6 +4252,7 @@ describe('MCPManager', () => {
expect(result.tools).toBeNull();
expect(result.oauthRequired).toBe(true);
+ expect(result.authenticationKind).toBe('oauth');
expect(MCPConnectionFactory.discoverTools).not.toHaveBeenCalled();
});
@@ -4195,6 +4272,7 @@ describe('MCPManager', () => {
expect(result.tools).toBeNull();
expect(result.oauthRequired).toBe(true);
+ expect(result.authenticationKind).toBe('oauth');
expect(mockLogger.warn).toHaveBeenCalledWith(
'[MCP][Discovery] OAuth server requires a user and flow manager',
);
@@ -4236,6 +4314,7 @@ describe('MCPManager', () => {
expect(result.tools).toEqual(mockTools);
expect(result.oauthRequired).toBe(true);
expect(result.oauthUrl).toBe('https://auth.example.com/authorize');
+ expect(result.authenticationKind).toBe('oauth');
expect(MCPConnectionFactory.discoverTools).toHaveBeenCalledWith(
expect.objectContaining({ serverName }),
expect.objectContaining({
@@ -4962,6 +5041,17 @@ describe('MCPManager', () => {
}
});
+ it('clears catalog recovery suppression for mutations but preserves it for lifecycle cleanup', async () => {
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const clearRecoveryState = jest.spyOn(manager.getCatalogRecoveryTracker(), 'clear');
+
+ await manager.disconnectUserConnection(userId, serverName, { reason: 'lifecycle' });
+ expect(clearRecoveryState).not.toHaveBeenCalled();
+
+ await manager.disconnectUserConnection(userId, serverName);
+ expect(clearRecoveryState).toHaveBeenCalledWith(userId, serverName);
+ });
+
it('fails a creation that a lifecycle teardown keeps cancelling on every attempt', async () => {
mockAppConnections({ has: jest.fn().mockResolvedValue(false) });
(mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue({
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
index d5a89d4190..6cc2215ab2 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
@@ -7,7 +7,12 @@
import type { TokenMethods } from '@librechat/data-schemas';
import type { MCPOAuthTokens } from '~/mcp/oauth';
-import { MCPTokenStorage, ReauthenticationRequiredError } from '~/mcp/oauth';
+import {
+ MCPTokenStorage,
+ MCPTokenRefreshUnavailableError,
+ MCPTokenStorageUnavailableError,
+ ReauthenticationRequiredError,
+} from '~/mcp/oauth';
import { InMemoryTokenStore } from './helpers/oauthTestServer';
const credentialSetId = 'credential-set-a';
@@ -275,6 +280,23 @@ describe('MCPTokenStorage', () => {
});
describe('storeTokens', () => {
+ it('persists fence intent before writing the first token row', async () => {
+ const onStorePreparing = jest.fn().mockResolvedValue(undefined);
+ const createToken = jest.fn(store.createToken);
+
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: { access_token: 'at1', token_type: 'Bearer' },
+ createToken,
+ onStorePreparing,
+ });
+
+ expect(onStorePreparing.mock.invocationCallOrder[0]).toBeLessThan(
+ createToken.mock.invocationCallOrder[0],
+ );
+ });
+
it('keeps the trusted flow generation when provider metadata supplies a conflicting ID', async () => {
const result = await MCPTokenStorage.storeTokens({
userId: 'u1',
@@ -975,6 +997,21 @@ describe('MCPTokenStorage', () => {
expect(result!.token_type).toBe('Bearer');
});
+ it('reports token-store outages separately from reauthentication', async () => {
+ const storageError = new Error('database unavailable');
+
+ await expect(
+ MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: jest.fn().mockRejectedValue(storageError),
+ }),
+ ).rejects.toMatchObject({
+ name: 'MCPTokenStorageUnavailableError',
+ cause: storageError,
+ } satisfies Partial<MCPTokenStorageUnavailableError>);
+ });
+
it('rejects an access token read before a concurrent client generation replacement', async () => {
await createBoundToken(store, {
userId: 'u1',
@@ -1133,7 +1170,7 @@ describe('MCPTokenStorage', () => {
);
});
- it('should return null when refresh fails', async () => {
+ it('reports transient refresh failures separately from reauthentication', async () => {
await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
@@ -1151,16 +1188,18 @@ describe('MCPTokenStorage', () => {
const refreshTokens = jest.fn().mockRejectedValue(new Error('refresh failed'));
- const result = await MCPTokenStorage.getTokens({
- userId: 'u1',
- serverName: 'srv1',
- findToken: store.findToken,
- createToken: store.createToken,
- updateToken: store.updateToken,
- refreshTokens,
- });
-
- expect(result).toBeNull();
+ await expect(
+ MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ refreshTokens,
+ }),
+ ).rejects.toMatchObject({
+ name: 'MCPTokenRefreshUnavailableError',
+ } satisfies Partial<MCPTokenRefreshUnavailableError>);
});
it('should return null when no refreshTokens callback provided', async () => {
@@ -1893,7 +1932,7 @@ describe('MCPTokenStorage', () => {
expect(refreshTokens).not.toHaveBeenCalled();
});
- it('should return null when refresh callback throws non-client-rejection error', async () => {
+ it('should throw a retryable error when refresh callback fails transiently', async () => {
await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
@@ -1904,15 +1943,17 @@ describe('MCPTokenStorage', () => {
const refreshTokens = jest.fn().mockRejectedValue(new Error('network blew up'));
- const result = await MCPTokenStorage.forceRefreshTokens({
- userId: 'u1',
- serverName: 'srv1',
- findToken: store.findToken,
- createToken: store.createToken,
- refreshTokens,
- });
-
- expect(result).toBeNull();
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ createToken: store.createToken,
+ refreshTokens,
+ }),
+ ).rejects.toMatchObject({
+ name: 'MCPTokenRefreshUnavailableError',
+ } satisfies Partial<MCPTokenRefreshUnavailableError>);
});
it('should throw ReauthenticationRequiredError when refresh fails with invalid_client', async () => {
@@ -2440,8 +2481,8 @@ describe('MCPTokenStorage', () => {
await waitFor(() => refreshTokens.mock.calls.length === 1);
rejectRefresh(new Error('network blew up'));
- await expect(first).resolves.toBeNull();
- await expect(second).resolves.toBeNull();
+ await expect(first).rejects.toThrow(MCPTokenRefreshUnavailableError);
+ await expect(second).rejects.toThrow(MCPTokenRefreshUnavailableError);
refreshTokens.mockResolvedValueOnce(rotatedTokens(2));
const third = await MCPTokenStorage.forceRefreshTokens(params);
@@ -2472,7 +2513,7 @@ describe('MCPTokenStorage', () => {
jest.advanceTimersByTime(MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS + 1);
/** The stale abort settles the stalled execution, which frees the slot. */
- await expect(stalled).resolves.toBeNull();
+ await expect(stalled).rejects.toThrow(MCPTokenRefreshUnavailableError);
const fresh = await MCPTokenStorage.forceRefreshTokens(params);
expect(fresh!.access_token).toBe('at-2');
@@ -2510,7 +2551,7 @@ describe('MCPTokenStorage', () => {
jest.advanceTimersByTime(MCPTokenStorage.INFLIGHT_REFRESH_STALE_MS + 1);
releaseRead();
- await expect(stalled).resolves.toBeNull();
+ await expect(stalled).rejects.toThrow(MCPTokenRefreshUnavailableError);
expect(refreshTokens).not.toHaveBeenCalled();
} finally {
jest.useRealTimers();
@@ -2561,6 +2602,65 @@ describe('MCPTokenStorage', () => {
expect(callbackTokens.credential_set_id).not.toBe(credentialSetId);
});
+ it('prepares a durable fence before persisting refreshed token rows', async () => {
+ await seedRefreshableTokens('prepared-srv');
+ const events: string[] = [];
+ const updateToken: TokenMethods['updateToken'] = async (...args) => {
+ events.push('write');
+ return store.updateToken(...args);
+ };
+ const onRefreshPreparing = jest.fn(async () => {
+ events.push('prepare');
+ return async () => {
+ events.push('publish');
+ };
+ });
+
+ await MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(jest.fn().mockResolvedValue(rotatedTokens(2)), 'prepared-srv'),
+ updateToken,
+ onRefreshPreparing,
+ });
+
+ expect(events[0]).toBe('prepare');
+ expect(events[events.length - 1]).toBe('publish');
+ expect(events).toContain('write');
+ expect(onRefreshPreparing).toHaveBeenCalledTimes(1);
+ });
+
+ 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'));
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ ...refreshParams(jest.fn().mockResolvedValue(rotatedTokens(2)), 'unfenced-srv'),
+ onRefreshSuccess,
+ }),
+ ).rejects.toThrow(MCPTokenRefreshUnavailableError);
+
+ expect(onRefreshSuccess).toHaveBeenCalledTimes(1);
+ const rejectedCredentialSetId = onRefreshSuccess.mock.calls[0][0].credential_set_id;
+ expect(
+ store.getAll().some((token) => {
+ const storedId =
+ token.metadata instanceof Map
+ ? token.metadata.get('credential_set_id')
+ : token.metadata?.credential_set_id;
+ return storedId === rejectedCredentialSetId;
+ }),
+ ).toBe(false);
+ expect(
+ store.getAll().some((token) => {
+ const storedId =
+ token.metadata instanceof Map
+ ? token.metadata.get('credential_set_id')
+ : token.metadata?.credential_set_id;
+ return token.type === 'mcp_oauth' && storedId === credentialSetId;
+ }),
+ ).toBe(true);
+ });
+
it("an initiator's abort resolves only its own wait, not the shared redemption", async () => {
await seedRefreshableTokens('abort-srv');
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.ts
index 116d7b7edd..8b9e822aeb 100644
--- a/packages/api/src/mcp/__tests__/handler.test.ts
+++ b/packages/api/src/mcp/__tests__/handler.test.ts
@@ -1851,6 +1851,51 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
);
});
+ it('lets persistence settle the flow inside its rollback boundary', async () => {
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: 123,
+ metadata: {
+ serverName: 'test-server',
+ codeVerifier: 'test-verifier',
+ clientInfo: {},
+ metadata: {},
+ } as MCPOAuthFlowMetadata,
+ }),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
+ } as unknown as FlowStateManager<MCPOAuthTokens>;
+ mockExchangeAuthorization.mockResolvedValue({
+ access_token: 'test-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+ const persistBeforeComplete = jest.fn(
+ async (
+ tokens: MCPOAuthTokens,
+ completePersistedFlow: (tokens: MCPOAuthTokens) => Promise<void>,
+ ) => {
+ const storedTokens = { ...tokens, expires_at: 123456 };
+ await completePersistedFlow(storedTokens);
+ return storedTokens;
+ },
+ );
+ const rollbackPersistedTokens = jest.fn(async () => undefined);
+
+ const result = await MCPOAuthHandler.completeOAuthFlow(
+ 'test-flow-id',
+ 'test-auth-code',
+ mockFlowManager,
+ {},
+ persistBeforeComplete,
+ rollbackPersistedTokens,
+ );
+
+ expect(result.expires_at).toBe(123456);
+ expect(mockFlowManager.completeFlowIfCurrent).toHaveBeenCalledTimes(1);
+ expect(rollbackPersistedTokens).not.toHaveBeenCalled();
+ });
+
it('rejects a replaced callback attempt before exchanging its authorization code', async () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
diff --git a/packages/api/src/mcp/authorization.spec.ts b/packages/api/src/mcp/authorization.spec.ts
new file mode 100644
index 0000000000..af2ac6069d
--- /dev/null
+++ b/packages/api/src/mcp/authorization.spec.ts
@@ -0,0 +1,252 @@
+import {
+ completeMCPAuthorizationWithTokenWaiters,
+ finalizeMCPAuthorizationMutation,
+ persistMCPAuthorizationTransaction,
+} from './authorization';
+
+const scope = { userId: 'user-1', serverName: 'server-1' };
+
+describe('completeMCPAuthorizationWithTokenWaiters', () => {
+ it('removes stale results and wakes pending waiters only after guarded completion', async () => {
+ const tokens = { access_token: 'fresh' };
+ const completeAuthorization = jest.fn().mockResolvedValue(undefined);
+ const flowManager = {
+ getFlowState: jest.fn(async (flowId: string) =>
+ flowId === 'pending'
+ ? { type: 'mcp_get_tokens', status: 'PENDING', createdAt: 123, metadata: {} }
+ : { type: 'mcp_get_tokens', status: 'COMPLETED' },
+ ),
+ deleteFlow: jest.fn().mockResolvedValue(undefined),
+ settleFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
+ };
+
+ await completeMCPAuthorizationWithTokenWaiters(
+ { flowIds: ['pending', 'stale', 'pending'], tokens, completeAuthorization },
+ { flowManager },
+ );
+
+ expect(flowManager.deleteFlow).toHaveBeenCalledWith('stale', 'mcp_get_tokens');
+ expect(flowManager.settleFlowIfCurrent).toHaveBeenCalledWith(
+ 'pending',
+ 'mcp_get_tokens',
+ 123,
+ '',
+ tokens,
+ );
+ expect(completeAuthorization.mock.invocationCallOrder[0]).toBeLessThan(
+ flowManager.settleFlowIfCurrent.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('does not expose tokens when guarded authorization completion fails', async () => {
+ const error = new Error('cancelled');
+ const flowManager = {
+ getFlowState: jest
+ .fn()
+ .mockResolvedValue({ type: 'mcp_get_tokens', status: 'PENDING', createdAt: 123 }),
+ deleteFlow: jest.fn(),
+ settleFlowIfCurrent: jest.fn(),
+ };
+
+ await expect(
+ completeMCPAuthorizationWithTokenWaiters(
+ {
+ flowIds: ['pending'],
+ tokens: { access_token: 'rolled-back' },
+ completeAuthorization: jest.fn().mockRejectedValue(error),
+ },
+ { flowManager },
+ ),
+ ).rejects.toBe(error);
+
+ expect(flowManager.settleFlowIfCurrent).not.toHaveBeenCalled();
+ });
+
+ it('does not commit authorization when stale token-flow cleanup is unavailable', async () => {
+ const error = new Error('flow store unavailable');
+ const completeAuthorization = jest.fn();
+ const onTokenFlowError = jest.fn();
+ const flowManager = {
+ getFlowState: jest.fn().mockRejectedValue(error),
+ deleteFlow: jest.fn(),
+ settleFlowIfCurrent: jest.fn(),
+ };
+
+ await expect(
+ completeMCPAuthorizationWithTokenWaiters(
+ { flowIds: ['token-flow'], tokens: { access_token: 'fresh' }, completeAuthorization },
+ { flowManager, onTokenFlowError },
+ ),
+ ).rejects.toBe(error);
+
+ expect(onTokenFlowError).toHaveBeenCalledWith('prepare', error);
+ expect(completeAuthorization).not.toHaveBeenCalled();
+ });
+});
+
+describe('persistMCPAuthorizationTransaction', () => {
+ it('keeps validation, publication, OAuth settlement, and token-waiter settlement in one boundary', 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 invalidateRecoveryGeneration = jest.fn().mockResolvedValue(undefined);
+ const ensureServerActive = jest.fn().mockResolvedValue(true);
+ const persistPublicationRetry = jest.fn().mockResolvedValue('prepared-v1');
+ const clearPublicationRetry = jest.fn().mockResolvedValue(undefined);
+ const flowManager = {
+ getFlowState: jest.fn().mockResolvedValue(null),
+ deleteFlow: jest.fn().mockResolvedValue(true),
+ settleFlowIfCurrent: jest.fn(),
+ };
+
+ await expect(
+ persistMCPAuthorizationTransaction(
+ {
+ scope,
+ flowIds: ['token-flow'],
+ tokens,
+ completeAuthorization,
+ persistTokens,
+ },
+ {
+ ensureServerActive,
+ inactiveServerError: () => new Error('deleted'),
+ invalidateRecoveryGeneration,
+ persistPublicationRetry,
+ clearPublicationRetry,
+ flowManager,
+ retryDelaysMs: [0],
+ },
+ ),
+ ).resolves.toBe(tokens);
+
+ expect(persistPublicationRetry.mock.invocationCallOrder[0]).toBeLessThan(
+ persistTokens.mock.invocationCallOrder[0],
+ );
+ expect(ensureServerActive.mock.invocationCallOrder[0]).toBeLessThan(
+ invalidateRecoveryGeneration.mock.invocationCallOrder[0],
+ );
+ expect(invalidateRecoveryGeneration.mock.invocationCallOrder[0]).toBeLessThan(
+ completeAuthorization.mock.invocationCallOrder[0],
+ );
+ });
+});
+
+describe('finalizeMCPAuthorizationMutation', () => {
+ it('publishes and disconnects after any write in a partial batch commits', async () => {
+ const invalidateRecoveryGeneration = jest.fn().mockResolvedValue(undefined);
+ const persistPublicationRetry = jest.fn();
+ const clearPublicationRetry = jest.fn().mockResolvedValue(undefined);
+ const clearLocalRecovery = jest.fn();
+ const disconnectUserConnection = jest.fn().mockResolvedValue(undefined);
+
+ await expect(
+ finalizeMCPAuthorizationMutation(
+ {
+ scope,
+ mutationResults: [{ id: 'saved' }, new Error('later field failed')],
+ publicationRetryVersion: 'prepared-v1',
+ },
+ {
+ invalidateRecoveryGeneration,
+ persistPublicationRetry,
+ clearPublicationRetry,
+ clearLocalRecovery,
+ disconnectUserConnection,
+ retryDelaysMs: [0],
+ },
+ ),
+ ).resolves.toBe(true);
+
+ expect(invalidateRecoveryGeneration).toHaveBeenCalledWith(scope);
+ expect(persistPublicationRetry).not.toHaveBeenCalled();
+ expect(clearPublicationRetry).toHaveBeenCalledWith(scope, 'prepared-v1');
+ expect(clearLocalRecovery).toHaveBeenCalledWith(scope.userId, scope.serverName);
+ expect(disconnectUserConnection).toHaveBeenCalledWith(scope.userId, scope.serverName);
+ });
+
+ it('disconnects and completes teardown before surfacing a publication failure', async () => {
+ const error = new Error('cache unavailable');
+ const disconnectUserConnection = jest.fn().mockRejectedValue(new Error('disconnect failed'));
+ const onDisconnectError = jest.fn();
+ const afterDisconnect = jest.fn().mockResolvedValue(undefined);
+
+ await expect(
+ finalizeMCPAuthorizationMutation(
+ { scope, mutationResults: [error], teardown: true },
+ {
+ invalidateRecoveryGeneration: jest.fn().mockRejectedValue(error),
+ disconnectUserConnection,
+ retryDelaysMs: [0],
+ onDisconnectError,
+ afterDisconnect,
+ },
+ ),
+ ).rejects.toBe(error);
+
+ expect(onDisconnectError).toHaveBeenCalledWith(expect.any(Error));
+ expect(afterDisconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('writes a second durable intent before teardown token cleanup and fences it afterward', async () => {
+ const invalidateRecoveryGeneration = jest.fn().mockResolvedValue(undefined);
+ const persistPublicationRetry = jest.fn().mockResolvedValue('cleanup-v2');
+ const clearPublicationRetry = jest.fn().mockResolvedValue(undefined);
+ const disconnectUserConnection = jest.fn().mockResolvedValue(undefined);
+ const afterDisconnect = jest.fn().mockResolvedValue(undefined);
+
+ await finalizeMCPAuthorizationMutation(
+ {
+ scope,
+ mutationResults: [{}],
+ publicationRetryVersion: 'credentials-v1',
+ teardown: true,
+ },
+ {
+ invalidateRecoveryGeneration,
+ persistPublicationRetry,
+ clearPublicationRetry,
+ disconnectUserConnection,
+ afterDisconnect,
+ retryDelaysMs: [0],
+ },
+ );
+
+ expect(invalidateRecoveryGeneration).toHaveBeenCalledTimes(2);
+ expect(disconnectUserConnection.mock.invocationCallOrder[0]).toBeLessThan(
+ persistPublicationRetry.mock.invocationCallOrder[0],
+ );
+ expect(persistPublicationRetry.mock.invocationCallOrder[0]).toBeLessThan(
+ afterDisconnect.mock.invocationCallOrder[0],
+ );
+ expect(afterDisconnect.mock.invocationCallOrder[0]).toBeLessThan(
+ invalidateRecoveryGeneration.mock.invocationCallOrder[1],
+ );
+ expect(clearPublicationRetry).toHaveBeenNthCalledWith(1, scope, 'credentials-v1');
+ expect(clearPublicationRetry).toHaveBeenNthCalledWith(2, scope, 'cleanup-v2');
+ });
+
+ it('does nothing when every ordinary credential mutation failed', async () => {
+ const invalidateRecoveryGeneration = jest.fn();
+ const disconnectUserConnection = jest.fn();
+ const clearPublicationRetry = jest.fn().mockResolvedValue(undefined);
+
+ await expect(
+ finalizeMCPAuthorizationMutation(
+ {
+ scope,
+ mutationResults: [new Error('failed')],
+ publicationRetryVersion: 'prepared-v1',
+ },
+ { invalidateRecoveryGeneration, disconnectUserConnection, clearPublicationRetry },
+ ),
+ ).resolves.toBe(false);
+
+ expect(invalidateRecoveryGeneration).not.toHaveBeenCalled();
+ expect(disconnectUserConnection).not.toHaveBeenCalled();
+ expect(clearPublicationRetry).toHaveBeenCalledWith(scope, 'prepared-v1');
+ });
+});
diff --git a/packages/api/src/mcp/authorization.ts b/packages/api/src/mcp/authorization.ts
new file mode 100644
index 0000000000..dc4d5feed3
--- /dev/null
+++ b/packages/api/src/mcp/authorization.ts
@@ -0,0 +1,237 @@
+import type { MCPRecoveryGenerationScope } from './catalog/recovery';
+import { publishMCPAuthorizationMutation } from './catalog/recovery';
+
+export interface MCPAuthorizationPublicationDeps {
+ invalidateRecoveryGeneration: (scope: MCPRecoveryGenerationScope) => Promise<unknown>;
+ clearLocalRecovery?: (userId: string, serverName: string) => void;
+ persistPublicationRetry?: (scope: MCPRecoveryGenerationScope) => Promise<string>;
+ clearPublicationRetry?: (scope: MCPRecoveryGenerationScope, version: string) => Promise<void>;
+ retryDelaysMs?: readonly number[];
+ attemptTimeoutMs?: number;
+}
+
+export interface FinalizeMCPAuthorizationMutationParams {
+ scope: MCPRecoveryGenerationScope;
+ mutationResults: readonly unknown[];
+ /** Durable intent written before the first credential mutation. */
+ publicationRetryVersion?: string;
+ /** Teardown also fences when the credential delete itself was a no-op or failed. */
+ teardown?: boolean;
+}
+
+export interface FinalizeMCPAuthorizationMutationDeps extends MCPAuthorizationPublicationDeps {
+ disconnectUserConnection: (userId: string, serverName: string) => Promise<void>;
+ retryDelaysMs?: readonly number[];
+ attemptTimeoutMs?: number;
+ afterDisconnect?: () => Promise<void>;
+ onDisconnectError?: (error: unknown) => void;
+}
+
+export interface CompleteMCPAuthorizationWithTokenWaitersParams<TTokens> {
+ flowIds: readonly string[];
+ tokens: TTokens;
+ completeAuthorization: (tokens: TTokens) => Promise<void>;
+}
+
+export interface CompleteMCPAuthorizationWithTokenWaitersDeps<TTokens> {
+ flowManager: {
+ getFlowState?: (flowId: string, type: 'mcp_get_tokens') => Promise<unknown>;
+ deleteFlow?: (flowId: string, type: 'mcp_get_tokens') => Promise<unknown>;
+ settleFlowIfCurrent?: (
+ flowId: string,
+ type: 'mcp_get_tokens',
+ expectedCreatedAt: number,
+ expectedState: string,
+ tokens: TTokens,
+ ) => Promise<'updated' | 'stale' | 'missing'>;
+ };
+ onTokenFlowError?: (phase: 'prepare' | 'complete', error: unknown) => void;
+}
+
+interface PendingTokenFlowAttempt {
+ flowId: string;
+ createdAt: number;
+ state: string;
+}
+
+/**
+ * Settles the guarded OAuth flow before exposing its tokens to connection-factory waiters. Stale
+ * token-flow results are removed before settlement, while live waiters are retained and woken only
+ * after the authorization completion can no longer roll the credential write back.
+ */
+export async function completeMCPAuthorizationWithTokenWaiters<TTokens>(
+ params: CompleteMCPAuthorizationWithTokenWaitersParams<TTokens>,
+ deps: CompleteMCPAuthorizationWithTokenWaitersDeps<TTokens>,
+): Promise<void> {
+ const pendingFlows: PendingTokenFlowAttempt[] = [];
+ const { flowManager } = deps;
+ if (
+ typeof flowManager.getFlowState === 'function' &&
+ typeof flowManager.deleteFlow === 'function'
+ ) {
+ for (const flowId of new Set(params.flowIds)) {
+ try {
+ const state = (await flowManager.getFlowState(flowId, 'mcp_get_tokens')) as
+ | { type?: string; status?: string; createdAt?: number; metadata?: { state?: unknown } }
+ | null
+ | undefined;
+ if (
+ state?.type === 'mcp_get_tokens' &&
+ state.status === 'PENDING' &&
+ typeof state.createdAt === 'number' &&
+ typeof flowManager.settleFlowIfCurrent === 'function'
+ ) {
+ pendingFlows.push({
+ flowId,
+ createdAt: state.createdAt,
+ state: typeof state.metadata?.state === 'string' ? state.metadata.state : '',
+ });
+ } else {
+ await flowManager.deleteFlow(flowId, 'mcp_get_tokens');
+ }
+ } catch (error) {
+ deps.onTokenFlowError?.('prepare', error);
+ throw error;
+ }
+ }
+ }
+
+ await params.completeAuthorization(params.tokens);
+
+ for (const pending of pendingFlows) {
+ try {
+ const result = await flowManager.settleFlowIfCurrent?.(
+ pending.flowId,
+ 'mcp_get_tokens',
+ pending.createdAt,
+ pending.state,
+ params.tokens,
+ );
+ if (result !== 'updated') {
+ throw new Error(`Pending MCP token flow was ${result}`);
+ }
+ } catch (error) {
+ deps.onTokenFlowError?.('complete', error);
+ }
+ }
+}
+
+export interface PersistMCPAuthorizationTransactionParams<TTokens> {
+ scope: MCPRecoveryGenerationScope;
+ flowIds: readonly string[];
+ tokens: TTokens;
+ completeAuthorization: (tokens: TTokens) => Promise<void>;
+ persistTokens: (
+ tokens: TTokens,
+ onStoreCommitted: (tokens: TTokens) => Promise<void>,
+ ) => Promise<TTokens>;
+}
+
+export interface PersistMCPAuthorizationTransactionDeps<TTokens>
+ extends CompleteMCPAuthorizationWithTokenWaitersDeps<TTokens>,
+ MCPAuthorizationPublicationDeps {
+ ensureServerActive: () => Promise<boolean>;
+ inactiveServerError: () => Error;
+}
+
+/** Writes a durable intent now and returns the exact publication that clears only that intent. */
+export async function prepareMCPAuthorizationMutation(
+ scope: MCPRecoveryGenerationScope,
+ deps: MCPAuthorizationPublicationDeps,
+): Promise<() => Promise<void>> {
+ const publicationRetryVersion = await deps.persistPublicationRetry?.(scope);
+ return () =>
+ publishMCPAuthorizationMutation(scope, {
+ ...deps,
+ persistPublicationRetry:
+ publicationRetryVersion != null ? async () => publicationRetryVersion : undefined,
+ });
+}
+
+/** Owns the OAuth authorization transaction while the token store's rollback journal is live. */
+export async function persistMCPAuthorizationTransaction<TTokens>(
+ params: PersistMCPAuthorizationTransactionParams<TTokens>,
+ deps: PersistMCPAuthorizationTransactionDeps<TTokens>,
+): Promise<TTokens> {
+ if (!(await deps.ensureServerActive())) {
+ throw deps.inactiveServerError();
+ }
+ const publishPreparedMutation = await prepareMCPAuthorizationMutation(params.scope, deps);
+ return params.persistTokens(params.tokens, async (committedTokens) => {
+ if (!(await deps.ensureServerActive())) {
+ throw deps.inactiveServerError();
+ }
+ await publishPreparedMutation();
+ await completeMCPAuthorizationWithTokenWaiters(
+ {
+ flowIds: params.flowIds,
+ tokens: committedTokens,
+ completeAuthorization: params.completeAuthorization,
+ },
+ deps,
+ );
+ });
+}
+
+/**
+ * Publishes every committed credential batch before disconnecting its live connection. Partial
+ * batches still advance the generation. Teardown fences the credential change, disconnects, then
+ * writes a second durable intent before OAuth cleanup and fences that cleanup independently.
+ */
+export async function finalizeMCPAuthorizationMutation(
+ params: FinalizeMCPAuthorizationMutationParams,
+ deps: FinalizeMCPAuthorizationMutationDeps,
+): Promise<boolean> {
+ const committed = params.mutationResults.some((result) => !(result instanceof Error));
+ if (!committed && params.teardown !== true) {
+ if (params.publicationRetryVersion != null) {
+ await deps.clearPublicationRetry?.(params.scope, params.publicationRetryVersion);
+ }
+ return false;
+ }
+
+ let publicationError: unknown;
+ let publicationFailed = false;
+ const preparedPublicationRetryVersion = params.publicationRetryVersion;
+ try {
+ await publishMCPAuthorizationMutation(params.scope, {
+ invalidateRecoveryGeneration: deps.invalidateRecoveryGeneration,
+ clearLocalRecovery: deps.clearLocalRecovery,
+ persistPublicationRetry:
+ preparedPublicationRetryVersion != null
+ ? async () => preparedPublicationRetryVersion
+ : deps.persistPublicationRetry,
+ clearPublicationRetry: deps.clearPublicationRetry,
+ retryDelaysMs: deps.retryDelaysMs,
+ attemptTimeoutMs: deps.attemptTimeoutMs,
+ });
+ } catch (error) {
+ publicationFailed = true;
+ publicationError = error;
+ }
+
+ try {
+ await deps.disconnectUserConnection(params.scope.userId, params.scope.serverName);
+ } catch (error) {
+ deps.onDisconnectError?.(error);
+ }
+
+ let cleanupPublicationError: unknown;
+ if (deps.afterDisconnect != null) {
+ try {
+ const publishCleanupMutation = await prepareMCPAuthorizationMutation(params.scope, deps);
+ await deps.afterDisconnect();
+ await publishCleanupMutation();
+ } catch (error) {
+ cleanupPublicationError = error;
+ }
+ }
+
+ if (publicationFailed) {
+ throw publicationError;
+ }
+ if (cleanupPublicationError != null) {
+ throw cleanupPublicationError;
+ }
+ return committed;
+}
diff --git a/packages/api/src/mcp/authorizationRetry.spec.ts b/packages/api/src/mcp/authorizationRetry.spec.ts
new file mode 100644
index 0000000000..b226156e47
--- /dev/null
+++ b/packages/api/src/mcp/authorizationRetry.spec.ts
@@ -0,0 +1,190 @@
+import type {
+ MCPAuthorizationFenceRetryRecord,
+ MCPAuthorizationFenceRetryStorage,
+} from './authorizationRetry';
+import { createMCPAuthorizationFenceRetryService } from './authorizationRetry';
+
+const scope = { userId: 'user-1', serverName: 'server-1' };
+
+function createHarness() {
+ const records = new Map<string, MCPAuthorizationFenceRetryRecord>();
+ const key = (
+ tenantId: string | null | undefined,
+ userId: string,
+ serverName: string,
+ version: string,
+ ) => JSON.stringify([tenantId ?? '', userId, serverName, version]);
+ const storage: MCPAuthorizationFenceRetryStorage = {
+ upsert: jest.fn(async ({ scope: inputScope, tenantId, version, now }) => {
+ records.set(key(tenantId, inputScope.userId, inputScope.serverName, version), {
+ ...inputScope,
+ tenantId,
+ version,
+ updatedAt: now,
+ });
+ }),
+ deleteVersion: jest.fn(async ({ scope: inputScope, tenantId, version }) => {
+ records.delete(key(tenantId, inputScope.userId, inputScope.serverName, version));
+ }),
+ deferVersion: jest.fn(async ({ scope: inputScope, tenantId, version, updatedAt }) => {
+ const recordKey = key(tenantId, inputScope.userId, inputScope.serverName, version);
+ const record = records.get(recordKey);
+ if (record?.version === version) {
+ record.updatedAt = updatedAt;
+ }
+ }),
+ list: jest.fn(async (limit) =>
+ [...records.values()]
+ .sort((left, right) => left.updatedAt.getTime() - right.updatedAt.getTime())
+ .slice(0, limit),
+ ),
+ };
+ const runInRetryScope = jest.fn(async (_retry, operation) => operation());
+ const registerShutdown = jest.fn();
+ const service = createMCPAuthorizationFenceRetryService({
+ storage,
+ getTenantId: () => 'tenant-a',
+ runInRetryScope,
+ registerShutdown,
+ });
+ return { records, registerShutdown, runInRetryScope, service, storage };
+}
+
+describe('MCP authorization fence retry service', () => {
+ afterEach(() => jest.useRealTimers());
+
+ it('clears only the marker version created by that publisher', async () => {
+ const { records, service, storage } = createHarness();
+ const firstVersion = await service.persist(scope);
+ const secondVersion = await service.persist(scope);
+
+ await service.clear(scope, firstVersion);
+
+ expect(storage.deleteVersion).toHaveBeenCalledWith({
+ scope,
+ tenantId: 'tenant-a',
+ version: firstVersion,
+ });
+ expect([...records.values()]).toEqual([
+ expect.objectContaining({ ...scope, version: secondVersion }),
+ ]);
+ });
+
+ it('preserves every overlapping publication intent for the same scope', async () => {
+ const { records, service } = createHarness();
+ const firstVersion = await service.persist(scope);
+ const secondVersion = await service.persist(scope);
+
+ expect(records.size).toBe(2);
+ expect([...records.values()].map(({ version }) => version)).toEqual([
+ firstVersion,
+ secondVersion,
+ ]);
+ });
+
+ it('replays a bounded batch in tenant scope and deletes exact published versions', async () => {
+ const { records, runInRetryScope, service, storage } = createHarness();
+ const version = await service.persist(scope);
+ const invalidate = jest.fn().mockResolvedValue(undefined);
+
+ service.start(invalidate, { intervalMs: 5_000, batchSize: 7 });
+ await service.drain();
+
+ expect(storage.list).toHaveBeenCalledWith(7);
+ expect(runInRetryScope).toHaveBeenCalledWith(
+ expect.objectContaining({ ...scope, tenantId: 'tenant-a', version }),
+ expect.any(Function),
+ );
+ expect(invalidate).toHaveBeenCalledWith(scope);
+ expect(storage.deleteVersion).toHaveBeenCalledWith({
+ scope,
+ tenantId: 'tenant-a',
+ version,
+ });
+ expect(records.size).toBe(0);
+ await service.stop();
+ });
+
+ it('uses the configured cadence and registers clean shutdown', async () => {
+ jest.useFakeTimers();
+ const { registerShutdown, service, storage } = createHarness();
+ service.start(jest.fn().mockResolvedValue(undefined), { intervalMs: 2_500, batchSize: 3 });
+ await service.drain();
+ (storage.list as jest.Mock).mockClear();
+
+ await jest.advanceTimersByTimeAsync(2_500);
+
+ expect(storage.list).toHaveBeenCalledWith(3);
+ expect(registerShutdown).toHaveBeenCalledWith(
+ 'MCP authorization fence retry worker',
+ expect.any(Function),
+ );
+ await service.stop();
+ });
+
+ it('times out and defers a failed oldest record so later retries are not starved', async () => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
+ const { records, service, storage } = createHarness();
+ await service.persist({ userId: 'user-1', serverName: 'first' });
+ jest.setSystemTime(new Date('2026-01-01T00:00:00.001Z'));
+ await service.persist({ userId: 'user-1', serverName: 'second' });
+ let finishFirst: (() => void) | undefined;
+ const firstAttempt = new Promise<void>((resolve) => {
+ finishFirst = resolve;
+ });
+ const invalidate = jest.fn(({ serverName }: typeof scope) =>
+ serverName === 'first' ? firstAttempt : Promise.resolve(),
+ );
+
+ service.start(invalidate, { intervalMs: 10_000, batchSize: 1, attemptTimeoutMs: 5 });
+ const firstDrain = service.drain();
+ await jest.advanceTimersByTimeAsync(5);
+ await firstDrain;
+ await service.drain();
+ const thirdDrain = service.drain();
+ await jest.advanceTimersByTimeAsync(5);
+ await thirdDrain;
+
+ expect(invalidate).toHaveBeenNthCalledWith(1, { userId: 'user-1', serverName: 'first' });
+ expect(invalidate).toHaveBeenNthCalledWith(2, { userId: 'user-1', serverName: 'second' });
+ expect(invalidate).toHaveBeenNthCalledWith(3, { userId: 'user-1', serverName: 'first' });
+ expect(invalidate).toHaveBeenCalledTimes(3);
+ expect(storage.deferVersion).toHaveBeenCalledWith(
+ expect.objectContaining({
+ scope: { userId: 'user-1', serverName: 'first' },
+ updatedAt: new Date('2026-01-01T00:00:00.006Z'),
+ }),
+ );
+ expect([...records.values()].map(({ serverName }) => serverName)).toEqual(['first']);
+ finishFirst?.();
+ await firstAttempt;
+ await service.drain();
+ expect(records.size).toBe(0);
+ await service.stop();
+ });
+
+ it('bounds a stalled deferral so the worker can drain again', async () => {
+ jest.useFakeTimers();
+ const { service, storage } = createHarness();
+ await service.persist(scope);
+ (storage.deferVersion as jest.Mock).mockImplementationOnce(() => new Promise(() => undefined));
+ service.start(
+ jest.fn(() => new Promise(() => undefined)),
+ {
+ intervalMs: 10_000,
+ batchSize: 1,
+ attemptTimeoutMs: 5,
+ },
+ );
+
+ const firstDrain = service.drain();
+ await jest.advanceTimersByTimeAsync(10);
+ await firstDrain;
+ const secondDrain = service.drain();
+ await jest.advanceTimersByTimeAsync(10);
+ await secondDrain;
+
+ expect(storage.list).toHaveBeenCalledTimes(2);
+ await service.stop();
+ });
+});
diff --git a/packages/api/src/mcp/authorizationRetry.ts b/packages/api/src/mcp/authorizationRetry.ts
new file mode 100644
index 0000000000..42b592830c
--- /dev/null
+++ b/packages/api/src/mcp/authorizationRetry.ts
@@ -0,0 +1,240 @@
+import { randomUUID } from 'crypto';
+import { logger } from '@librechat/data-schemas';
+import type { MCPRecoveryGenerationScope } from './catalog/recovery';
+import { registerShutdownTask } from '~/app/shutdown';
+
+const DEFAULT_RETRY_INTERVAL_MS = 30_000;
+const DEFAULT_RETRY_BATCH_SIZE = 100;
+const DEFAULT_ATTEMPT_TIMEOUT_MS = 1_000;
+
+export interface MCPAuthorizationFenceRetryRecord extends MCPRecoveryGenerationScope {
+ tenantId?: string | null;
+ version: string;
+ updatedAt: Date;
+}
+
+export interface MCPAuthorizationFenceRetryStorage {
+ upsert(input: {
+ scope: MCPRecoveryGenerationScope;
+ tenantId?: string | null;
+ version: string;
+ now: Date;
+ }): Promise<void>;
+ deleteVersion(input: {
+ scope: MCPRecoveryGenerationScope;
+ tenantId?: string | null;
+ version: string;
+ }): Promise<void>;
+ deferVersion(input: {
+ scope: MCPRecoveryGenerationScope;
+ tenantId?: string | null;
+ version: string;
+ updatedAt: Date;
+ }): Promise<void>;
+ list(limit: number): Promise<readonly MCPAuthorizationFenceRetryRecord[]>;
+}
+
+export interface MCPAuthorizationFenceRetryServiceDeps {
+ storage: MCPAuthorizationFenceRetryStorage;
+ getTenantId: () => string | null | undefined;
+ runInRetryScope: (
+ retry: MCPAuthorizationFenceRetryRecord,
+ operation: () => Promise<void>,
+ ) => Promise<void>;
+ registerShutdown?: typeof registerShutdownTask;
+}
+
+export interface MCPAuthorizationFenceRetryWorkerPolicy {
+ intervalMs?: number;
+ batchSize?: number;
+ attemptTimeoutMs?: number;
+}
+
+export interface MCPAuthorizationFenceRetryService {
+ clear(scope: MCPRecoveryGenerationScope, version: string): Promise<void>;
+ drain(): Promise<void>;
+ persist(scope: MCPRecoveryGenerationScope): Promise<string>;
+ start(
+ invalidator: (scope: MCPRecoveryGenerationScope) => Promise<unknown>,
+ policy?: MCPAuthorizationFenceRetryWorkerPolicy,
+ ): void;
+ stop(): Promise<void>;
+}
+
+/** Owns durable authorization-fence retry lifecycle independently of the legacy server adapter. */
+export function createMCPAuthorizationFenceRetryService(
+ deps: MCPAuthorizationFenceRetryServiceDeps,
+): MCPAuthorizationFenceRetryService {
+ type RetryAttemptResult = { succeeded: true } | { succeeded: false; error: unknown };
+ let retryTimer: ReturnType<typeof setInterval> | undefined;
+ let drainPromise: Promise<void> | undefined;
+ const activeAttempts = new Map<string, Promise<RetryAttemptResult>>();
+ let invalidateRecoveryGeneration:
+ | ((scope: MCPRecoveryGenerationScope) => Promise<unknown>)
+ | undefined;
+ let retryBatchSize = DEFAULT_RETRY_BATCH_SIZE;
+ let attemptTimeoutMs = DEFAULT_ATTEMPT_TIMEOUT_MS;
+
+ const attemptKey = (retry: MCPAuthorizationFenceRetryRecord): string =>
+ JSON.stringify([retry.tenantId ?? '', retry.userId, retry.serverName, retry.version]);
+
+ const getOrStartAttempt = (
+ retry: MCPAuthorizationFenceRetryRecord,
+ ): Promise<RetryAttemptResult> => {
+ const key = attemptKey(retry);
+ const activeAttempt = activeAttempts.get(key);
+ if (activeAttempt != null) {
+ return activeAttempt;
+ }
+
+ const attempt = deps
+ .runInRetryScope(retry, async () => {
+ await invalidateRecoveryGeneration?.({
+ userId: retry.userId,
+ serverName: retry.serverName,
+ });
+ })
+ .then(async () => {
+ await deps.storage.deleteVersion({
+ scope: { userId: retry.userId, serverName: retry.serverName },
+ tenantId: retry.tenantId,
+ version: retry.version,
+ });
+ return { succeeded: true } as const;
+ })
+ .catch((error: unknown) => ({ succeeded: false, error }) as const)
+ .finally(() => {
+ if (activeAttempts.get(key) === attempt) {
+ activeAttempts.delete(key);
+ }
+ });
+ activeAttempts.set(key, attempt);
+ return attempt;
+ };
+
+ const persist = async (scope: MCPRecoveryGenerationScope): Promise<string> => {
+ const version = randomUUID();
+ await deps.storage.upsert({
+ scope,
+ tenantId: deps.getTenantId() ?? null,
+ version,
+ now: new Date(),
+ });
+ return version;
+ };
+
+ const clear = async (scope: MCPRecoveryGenerationScope, version: string): Promise<void> => {
+ await deps.storage.deleteVersion({
+ scope,
+ tenantId: deps.getTenantId() ?? null,
+ version,
+ });
+ };
+
+ const drain = async (): Promise<void> => {
+ if (drainPromise != null || invalidateRecoveryGeneration == null) {
+ return drainPromise;
+ }
+ drainPromise = (async () => {
+ const retries = await deps.storage.list(retryBatchSize);
+ for (const retry of retries) {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ let timedOut = false;
+ const key = attemptKey(retry);
+ const attempt = getOrStartAttempt(retry);
+ try {
+ const result = await Promise.race([
+ attempt,
+ new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(() => {
+ timedOut = true;
+ reject(new Error('MCP authorization generation replay timed out'));
+ }, attemptTimeoutMs);
+ }),
+ ]);
+ if (!result.succeeded) {
+ throw result.error;
+ }
+ } catch (error) {
+ logger.warn(
+ `[MCP authorization] Durable generation retry failed for ${retry.serverName}`,
+ error,
+ );
+ /** The underlying cache call may ignore cancellation. Retire it from deduplication so a
+ * recovered dependency gets a fresh attempt; its exact-version delete remains safe if
+ * the old promise eventually succeeds. */
+ if (timedOut && activeAttempts.get(key) === attempt) {
+ activeAttempts.delete(key);
+ }
+ try {
+ let deferTimeoutId: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ deps.storage.deferVersion({
+ scope: { userId: retry.userId, serverName: retry.serverName },
+ tenantId: retry.tenantId,
+ version: retry.version,
+ updatedAt: new Date(Math.max(Date.now(), retry.updatedAt.getTime() + 1)),
+ }),
+ new Promise<never>((_, reject) => {
+ deferTimeoutId = setTimeout(
+ () => reject(new Error('MCP authorization retry deferral timed out')),
+ attemptTimeoutMs,
+ );
+ }),
+ ]);
+ } finally {
+ if (deferTimeoutId != null) {
+ clearTimeout(deferTimeoutId);
+ }
+ }
+ } catch (deferError) {
+ logger.warn(
+ `[MCP authorization] Could not defer generation retry for ${retry.serverName}`,
+ deferError,
+ );
+ }
+ } finally {
+ if (timeoutId != null) {
+ clearTimeout(timeoutId);
+ }
+ }
+ }
+ })().finally(() => {
+ drainPromise = undefined;
+ });
+ return drainPromise;
+ };
+
+ const scheduleDrain = (): void => {
+ void drain().catch((error) =>
+ logger.warn('[MCP authorization] Could not read durable generation retries', error),
+ );
+ };
+
+ const stop = async (): Promise<void> => {
+ if (retryTimer != null) {
+ clearInterval(retryTimer);
+ retryTimer = undefined;
+ }
+ await drainPromise?.catch(() => undefined);
+ };
+
+ const start = (
+ invalidator: (scope: MCPRecoveryGenerationScope) => Promise<unknown>,
+ policy: MCPAuthorizationFenceRetryWorkerPolicy = {},
+ ): void => {
+ invalidateRecoveryGeneration = invalidator;
+ retryBatchSize = policy.batchSize ?? DEFAULT_RETRY_BATCH_SIZE;
+ attemptTimeoutMs = policy.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;
+ if (retryTimer != null) {
+ return;
+ }
+ retryTimer = setInterval(scheduleDrain, policy.intervalMs ?? DEFAULT_RETRY_INTERVAL_MS);
+ retryTimer.unref?.();
+ (deps.registerShutdown ?? registerShutdownTask)('MCP authorization fence retry worker', stop);
+ scheduleDrain();
+ };
+
+ return { clear, drain, persist, start, stop };
+}
diff --git a/packages/api/src/mcp/catalog/recovery.spec.ts b/packages/api/src/mcp/catalog/recovery.spec.ts
index 14aae00773..02daa614aa 100644
--- a/packages/api/src/mcp/catalog/recovery.spec.ts
+++ b/packages/api/src/mcp/catalog/recovery.spec.ts
@@ -1,19 +1,25 @@
import { logger } from '@librechat/data-schemas';
import { Constants } from 'librechat-data-provider';
-import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
+import { ErrorCode, McpError, type Tool } from '@modelcontextprotocol/sdk/types.js';
import type { IUser } from '@librechat/data-schemas';
import type { LCAvailableTools, ParsedServerConfig, ToolDiscoveryOptions } from '../types';
import {
MCPCatalogCapacityError,
+ MCPServerCatalogRecoveryTracker,
loadMCPServerCatalogs,
+ publishMCPAuthorizationMutation,
+ readMCPRecoveryGeneration,
+ readMCPRecoveryGenerationAround,
recoverMCPServerCatalogs,
} from './recovery';
+import { MCPTokenRefreshUnavailableError } from '../oauth';
jest.mock('@librechat/data-schemas', () => ({
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
}));
const user = { id: 'user-1' } as IUser;
+const recoveryTracker = new MCPServerCatalogRecoveryTracker();
const serverConfig = (name: string): ParsedServerConfig =>
({ type: 'streamable-http', url: `https://${name}.example.com/mcp` }) as ParsedServerConfig;
const withUserVars = (config: ParsedServerConfig): ParsedServerConfig =>
@@ -32,7 +38,306 @@ const availableTools = (name: string): LCAvailableTools => ({
},
});
+afterEach(() => {
+ recoveryTracker.clear(user.id);
+ jest.restoreAllMocks();
+});
+
+describe('readMCPRecoveryGeneration', () => {
+ it('keeps recovery available when the injected shared cache is unavailable', async () => {
+ const reader = jest.fn().mockRejectedValue(new Error('cache unavailable'));
+
+ await expect(
+ readMCPRecoveryGeneration({ userId: user.id, serverName: 'oauth-server' }, reader),
+ ).resolves.toBeUndefined();
+ expect(logger.debug).toHaveBeenCalledWith(
+ expect.stringContaining('oauth-server'),
+ expect.any(Error),
+ );
+ });
+
+ it('returns unknown instead of waiting indefinitely for the shared cache', async () => {
+ const reader = jest.fn(() => new Promise<string>(() => undefined));
+
+ await expect(
+ readMCPRecoveryGeneration({ userId: user.id, serverName: 'slow-cache' }, reader, {
+ timeoutMs: 5,
+ }),
+ ).resolves.toBeUndefined();
+ });
+});
+
+describe('readMCPRecoveryGenerationAround', () => {
+ it('returns a generation only when both reads coherently bracket the operation', async () => {
+ const operation = jest.fn().mockResolvedValue('authorized');
+ const changedReader = jest
+ .fn()
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-2');
+
+ await expect(
+ readMCPRecoveryGenerationAround(
+ { userId: user.id, serverName: 'oauth' },
+ changedReader,
+ operation,
+ ),
+ ).resolves.toEqual({ value: 'authorized' });
+ });
+});
+
+describe('publishMCPAuthorizationMutation', () => {
+ it('retries the shared fence and clears local suppression only after it advances', async () => {
+ const invalidateRecoveryGeneration = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('cache unavailable'))
+ .mockResolvedValue(undefined);
+ const clearLocalRecovery = jest.fn();
+ const persistPublicationRetry = jest.fn().mockResolvedValue('retry-v1');
+ const clearPublicationRetry = jest.fn().mockResolvedValue(undefined);
+
+ await publishMCPAuthorizationMutation(
+ { userId: user.id, serverName: 'oauth' },
+ {
+ invalidateRecoveryGeneration,
+ clearLocalRecovery,
+ persistPublicationRetry,
+ clearPublicationRetry,
+ retryDelaysMs: [0, 0],
+ },
+ );
+
+ expect(invalidateRecoveryGeneration).toHaveBeenCalledTimes(2);
+ expect(persistPublicationRetry.mock.invocationCallOrder[0]).toBeLessThan(
+ invalidateRecoveryGeneration.mock.invocationCallOrder[0],
+ );
+ expect(clearPublicationRetry).toHaveBeenCalledWith(
+ { userId: user.id, serverName: 'oauth' },
+ 'retry-v1',
+ );
+ expect(clearLocalRecovery).toHaveBeenCalledWith(user.id, 'oauth');
+ });
+
+ it('bounds each shared fence attempt', async () => {
+ const invalidateRecoveryGeneration = jest.fn(() => new Promise(() => undefined));
+ const persistPublicationRetry = jest.fn().mockResolvedValue('retry-v1');
+ const clearPublicationRetry = jest.fn();
+
+ await expect(
+ publishMCPAuthorizationMutation(
+ { userId: user.id, serverName: 'oauth' },
+ {
+ invalidateRecoveryGeneration,
+ persistPublicationRetry,
+ clearPublicationRetry,
+ retryDelaysMs: [0],
+ attemptTimeoutMs: 5,
+ },
+ ),
+ ).rejects.toThrow('MCP authorization generation publication timed out');
+
+ expect(invalidateRecoveryGeneration).toHaveBeenCalledTimes(1);
+ expect(persistPublicationRetry).toHaveBeenCalledTimes(1);
+ expect(clearPublicationRetry).not.toHaveBeenCalled();
+ });
+});
+
+describe('MCPServerCatalogRecoveryTracker capacity', () => {
+ const policy = {
+ discoveryBackoffMs: [60_000],
+ discoveryTimeoutMs: 3_000,
+ reauthRetryMs: 60_000,
+ maxStateEntries: 2,
+ generationReadTimeoutMs: 500,
+ authorizationFenceRetryMs: [0],
+ authorizationFenceTimeoutMs: 1_000,
+ authorizationFenceRetryIntervalMs: 30_000,
+ authorizationFenceRetryBatchSize: 100,
+ };
+
+ const candidate = (serverName: string) => ({
+ serverName,
+ serverConfig: serverConfig(serverName),
+ });
+ const failed = (serverName: string) => async () => ({
+ serverName,
+ tools: null,
+ state: 'backoff' as const,
+ });
+
+ it('keeps one process-wide capacity when requests carry different limits', async () => {
+ const tracker = new MCPServerCatalogRecoveryTracker(2);
+ const discoverA = jest.fn(failed('a'));
+
+ await tracker.run(user, candidate('a'), policy, 'generation-1', discoverA);
+ await tracker.run(
+ user,
+ candidate('b'),
+ { ...policy, maxStateEntries: 1 },
+ 'generation-1',
+ failed('b'),
+ );
+ await tracker.run(user, candidate('a'), policy, 'generation-1', discoverA);
+
+ expect(discoverA).toHaveBeenCalledTimes(1);
+ });
+
+ it('evicts the least recently used completed entry', async () => {
+ const tracker = new MCPServerCatalogRecoveryTracker(2);
+ const discoverA = jest.fn(failed('a'));
+ const discoverB = jest.fn(failed('b'));
+
+ await tracker.run(user, candidate('a'), policy, 'generation-1', discoverA);
+ await tracker.run(user, candidate('b'), policy, 'generation-1', discoverB);
+ await tracker.run(user, candidate('a'), policy, 'generation-1', discoverA);
+ await tracker.run(user, candidate('c'), policy, 'generation-1', failed('c'));
+ await tracker.run(user, candidate('a'), policy, 'generation-1', discoverA);
+ await tracker.run(user, candidate('b'), policy, 'generation-1', discoverB);
+
+ expect(discoverA).toHaveBeenCalledTimes(1);
+ expect(discoverB).toHaveBeenCalledTimes(2);
+ });
+});
+
describe('recoverMCPServerCatalogs', () => {
+ it('does not discover with a credential snapshot superseded while auth was loading', async () => {
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: [] });
+ const getRecoveryGeneration = jest
+ .fn()
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-2');
+
+ const result = await recoverMCPServerCatalogs(
+ {
+ user,
+ servers: [
+ {
+ serverName: 'guarded',
+ serverConfig: withUserVars(serverConfig('guarded')),
+ },
+ ],
+ },
+ {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({
+ [`${Constants.mcp_prefix}guarded`]: { API_KEY: 'old-value' },
+ }),
+ discoverServerTools,
+ formatServerTools: jest.fn().mockReturnValue({}),
+ getRecoveryGeneration,
+ recoveryTracker,
+ },
+ );
+
+ expect(result.size).toBe(0);
+ expect(discoverServerTools).not.toHaveBeenCalled();
+ });
+
+ it('does not discover custom credentials when either bracketing generation is unknown', async () => {
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: [] });
+ const getRecoveryGeneration = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('cache unavailable'))
+ .mockResolvedValueOnce('generation-2');
+
+ await recoverMCPServerCatalogs(
+ {
+ user,
+ servers: [
+ {
+ serverName: 'guarded',
+ serverConfig: withUserVars(serverConfig('guarded')),
+ },
+ ],
+ },
+ {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({
+ [`${Constants.mcp_prefix}guarded`]: { API_KEY: 'possibly-stale' },
+ }),
+ discoverServerTools,
+ formatServerTools: jest.fn().mockReturnValue({}),
+ getRecoveryGeneration,
+ recoveryTracker,
+ },
+ );
+
+ expect(discoverServerTools).not.toHaveBeenCalled();
+ });
+
+ it('discards discovery completed after its authorization generation was superseded', async () => {
+ const getRecoveryGeneration = jest
+ .fn()
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-2');
+
+ const result = await recoverMCPServerCatalogs(
+ { user, servers: [{ serverName: 'oauth', serverConfig: serverConfig('oauth') }] },
+ {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools: jest.fn().mockResolvedValue({
+ tools: [{ name: 'stale', inputSchema: { type: 'object' } }],
+ }),
+ formatServerTools: jest.fn().mockReturnValue(availableTools('stale')),
+ getRecoveryGeneration,
+ recoveryTracker,
+ },
+ );
+
+ expect(result.size).toBe(0);
+ });
+
+ it('preserves backoff when generation reads intermittently fail', async () => {
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: null });
+ const getRecoveryGeneration = jest
+ .fn()
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-1')
+ .mockRejectedValue(new Error('cache unavailable'));
+ const deps = {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn().mockReturnValue({}),
+ getRecoveryGeneration,
+ recoveryTracker,
+ };
+ const servers = [{ serverName: 'offline', serverConfig: serverConfig('offline') }];
+
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+ });
+
+ it('retains a known generation when a due retry runs during a cache outage', async () => {
+ let now = 1_800_000_000_000;
+ jest.spyOn(Date, 'now').mockImplementation(() => now);
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: null });
+ const getRecoveryGeneration = jest
+ .fn()
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-1')
+ .mockResolvedValueOnce('generation-1');
+ const deps = {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn().mockReturnValue({}),
+ getRecoveryGeneration,
+ recoveryTracker,
+ };
+ const servers = [{ serverName: 'offline', serverConfig: serverConfig('offline') }];
+ const recoveryPolicy = { discoveryBackoffMs: [10, 20] };
+
+ await recoverMCPServerCatalogs({ user, servers, recoveryPolicy }, deps);
+ now += 10;
+ getRecoveryGeneration.mockRejectedValue(new Error('cache unavailable'));
+ await recoverMCPServerCatalogs({ user, servers, recoveryPolicy }, deps);
+ now += 1;
+ getRecoveryGeneration.mockResolvedValue('generation-1');
+ await recoverMCPServerCatalogs({ user, servers, recoveryPolicy }, deps);
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(2);
+ });
+
it('loads user auth once and preserves config-only lookup context for each server', async () => {
const servers = [
{ serverName: 'alpha', serverConfig: withUserVars(serverConfig('alpha')) },
@@ -51,7 +356,12 @@ describe('recoverMCPServerCatalogs', () => {
const result = await recoverMCPServerCatalogs(
{ user, servers },
- { loadUserMCPAuthMap, discoverServerTools, formatServerTools },
+ {
+ loadUserMCPAuthMap,
+ discoverServerTools,
+ formatServerTools,
+ getRecoveryGeneration: jest.fn().mockResolvedValue('generation-1'),
+ },
);
expect(loadUserMCPAuthMap).toHaveBeenCalledTimes(1);
@@ -110,7 +420,8 @@ describe('recoverMCPServerCatalogs', () => {
);
expect(getServerToolFunctionsSnapshot).toHaveBeenCalledTimes(21);
- expect(discoverServerTools).toHaveBeenCalledTimes(21);
+ expect(discoverServerTools.mock.calls.length).toBeGreaterThan(0);
+ expect(discoverServerTools.mock.calls.length).toBeLessThanOrEqual(21);
expect(maxActive).toBe(3);
expect(results).toHaveLength(4);
expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(3);
@@ -180,6 +491,192 @@ describe('recoverMCPServerCatalogs', () => {
expect([...result.keys()]).toEqual(['good']);
});
+
+ it('single-flights concurrent discovery for the same user and server', async () => {
+ let release: ((value: { tools: Tool[] }) => void) | undefined;
+ const discoverServerTools = jest.fn(
+ () =>
+ new Promise<{ tools: Tool[] }>((resolve) => {
+ release = resolve;
+ }),
+ );
+ const servers = [{ serverName: 'shared', serverConfig: serverConfig('shared') }];
+ const deps = {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn().mockReturnValue(availableTools('shared-tool')),
+ recoveryTracker,
+ };
+
+ const first = recoverMCPServerCatalogs({ user, servers }, deps);
+ const second = recoverMCPServerCatalogs({ user, servers }, deps);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+ release?.({ tools: [] });
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ new Map([['shared', availableTools('shared-tool')]]),
+ new Map([['shared', availableTools('shared-tool')]]),
+ ]);
+ });
+
+ it('retains reauthorization state and recovered public tools during the retry window', async () => {
+ let recoveryGeneration = 'generation-1';
+ const discoverServerTools = jest.fn().mockResolvedValue({
+ tools: [{ name: 'public-tool', inputSchema: { type: 'object' as const } }],
+ oauthRequired: true,
+ authenticationKind: 'oauth' as const,
+ });
+ const servers = [{ serverName: 'oauth-server', serverConfig: serverConfig('oauth-server') }];
+ const deps = {
+ getCachedServerTools: jest.fn().mockResolvedValue(null),
+ getServerToolFunctionsSnapshot: jest.fn().mockResolvedValue({ tools: null }),
+ cacheServerTools: jest.fn(),
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn().mockReturnValue(availableTools('public-tool')),
+ recoveryTracker,
+ getRecoveryGeneration: jest.fn(async () => recoveryGeneration),
+ };
+
+ const first = await loadMCPServerCatalogs({ user, servers }, deps);
+ const second = await loadMCPServerCatalogs({ user, servers }, deps);
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+ expect(first.reauthRequiredServers).toEqual(new Set(['oauth-server']));
+ expect(first.reauthRequiredGenerations).toEqual(new Map([['oauth-server', 'generation-1']]));
+ expect(first.serverTools).toEqual(new Map([['oauth-server', availableTools('public-tool')]]));
+ expect(second.reauthRequiredServers).toEqual(new Set(['oauth-server']));
+ expect(second.serverTools).toEqual(new Map());
+
+ recoveryGeneration = 'generation-2';
+ const afterCredentialMutation = await loadMCPServerCatalogs({ user, servers }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(2);
+ expect(afterCredentialMutation.reauthRequiredGenerations).toEqual(
+ new Map([['oauth-server', 'generation-2']]),
+ );
+ });
+
+ it('backs off non-OAuth authorization failures instead of requesting reauthorization', async () => {
+ const discoverServerTools = jest.fn().mockResolvedValue({
+ tools: null,
+ oauthRequired: true,
+ authenticationKind: 'server' as const,
+ });
+ const servers = [{ serverName: 'server-auth', serverConfig: serverConfig('server-auth') }];
+ const deps = {
+ getCachedServerTools: jest.fn().mockResolvedValue(null),
+ getServerToolFunctionsSnapshot: jest.fn().mockResolvedValue({ tools: null }),
+ cacheServerTools: jest.fn(),
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn(),
+ recoveryTracker,
+ };
+
+ const first = await loadMCPServerCatalogs({ user, servers }, deps);
+ const second = await loadMCPServerCatalogs({ user, servers }, deps);
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+ expect(first.reauthRequiredServers).toEqual(new Set());
+ expect(second.reauthRequiredServers).toEqual(new Set());
+ });
+
+ it('backs off transient OAuth refresh failures instead of requesting reauthorization', async () => {
+ const discoverServerTools = jest
+ .fn()
+ .mockRejectedValue(
+ new MCPTokenRefreshUnavailableError('oauth-server', new Error('provider unavailable')),
+ );
+ const servers = [{ serverName: 'oauth-server', serverConfig: serverConfig('oauth-server') }];
+ const deps = {
+ getCachedServerTools: jest.fn().mockResolvedValue(null),
+ getServerToolFunctionsSnapshot: jest.fn().mockResolvedValue({ tools: null }),
+ cacheServerTools: jest.fn(),
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn(),
+ recoveryTracker,
+ };
+
+ const first = await loadMCPServerCatalogs({ user, servers }, deps);
+ const second = await loadMCPServerCatalogs({ user, servers }, deps);
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+ expect(first.reauthRequiredServers).toEqual(new Set());
+ expect(second.reauthRequiredServers).toEqual(new Set());
+ });
+
+ it.each([
+ [
+ 'OBO',
+ {
+ ...serverConfig('request-auth'),
+ obo: { scopes: 'api://mcp/.default' },
+ } as ParsedServerConfig,
+ ],
+ [
+ 'direct OpenID bearer',
+ {
+ ...serverConfig('request-auth'),
+ source: 'yaml',
+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },
+ } as ParsedServerConfig,
+ ],
+ ])('keeps %s discovery request-bound', async (_kind, requestAuthConfig) => {
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: null });
+ const servers = [{ serverName: 'request-auth', serverConfig: requestAuthConfig }];
+ const deps = {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn(),
+ recoveryTracker,
+ };
+
+ await Promise.all([
+ recoverMCPServerCatalogs({ user, servers, signal: firstController.signal }, deps),
+ recoverMCPServerCatalogs({ user, servers, signal: secondController.signal }, deps),
+ ]);
+
+ expect(discoverServerTools).toHaveBeenCalledTimes(2);
+ expect(discoverServerTools).toHaveBeenCalledWith(
+ expect.objectContaining({ signal: firstController.signal }),
+ );
+ expect(discoverServerTools).toHaveBeenCalledWith(
+ expect.objectContaining({ signal: secondController.signal }),
+ );
+ });
+
+ it('backs off failed discovery progressively and resets after explicit reconnect', async () => {
+ let now = 1_800_000_000_000;
+ jest.spyOn(Date, 'now').mockImplementation(() => now);
+ const discoverServerTools = jest.fn().mockRejectedValue(new Error('offline'));
+ const servers = [{ serverName: 'offline', serverConfig: serverConfig('offline') }];
+ const deps = {
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn(),
+ recoveryTracker,
+ };
+
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+
+ now += 5 * 60_000;
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(2);
+
+ now += 5 * 60_000;
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(2);
+
+ recoveryTracker.clear(user.id, 'offline');
+ await recoverMCPServerCatalogs({ user, servers }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(3);
+ });
});
describe('loadMCPServerCatalogs', () => {
@@ -286,6 +783,36 @@ describe('loadMCPServerCatalogs', () => {
expect(result.serverTools).toEqual(new Map([['recovered', {}]]));
expect(result.serversWithoutTools).toEqual(['missing']);
});
+
+ it('applies the configured recovery policy through the catalog loader', async () => {
+ let now = 1_800_000_000_000;
+ jest.spyOn(Date, 'now').mockImplementation(() => now);
+ const servers = [{ serverName: 'offline', serverConfig: serverConfig('offline') }];
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: null });
+ const deps = {
+ getCachedServerTools: jest.fn().mockResolvedValue(null),
+ getServerToolFunctionsSnapshot: jest.fn().mockResolvedValue({ tools: null }),
+ cacheServerTools: jest.fn(),
+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),
+ discoverServerTools,
+ formatServerTools: jest.fn(),
+ recoveryTracker,
+ };
+ const recoveryPolicy = {
+ discoveryBackoffMs: [10],
+ reauthRetryMs: 20,
+ maxStateEntries: 10,
+ };
+
+ await loadMCPServerCatalogs({ user, servers, recoveryPolicy }, deps);
+ now += 9;
+ await loadMCPServerCatalogs({ user, servers, recoveryPolicy }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(1);
+
+ now += 1;
+ await loadMCPServerCatalogs({ user, servers, recoveryPolicy }, deps);
+ expect(discoverServerTools).toHaveBeenCalledTimes(2);
+ });
});
describe('recoverMCPServerCatalogs — bounded, skippable discovery', () => {
@@ -296,6 +823,7 @@ describe('recoverMCPServerCatalogs — bounded, skippable discovery', () => {
loadUserMCPAuthMap: jest.fn().mockResolvedValue(userMCPAuthMap),
discoverServerTools,
formatServerTools: jest.fn().mockReturnValue({}),
+ getRecoveryGeneration: jest.fn().mockResolvedValue('generation-1'),
});
it('bounds each server discovery end to end rather than per attempt', async () => {
@@ -329,6 +857,24 @@ describe('recoverMCPServerCatalogs — bounded, skippable discovery', () => {
expect(options.deadlineMs).toBeLessThanOrEqual(Date.now() + 900);
});
+ it('honors a larger configured passive discovery budget', async () => {
+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: [] });
+ const before = Date.now();
+
+ await recoverMCPServerCatalogs(
+ {
+ user,
+ servers: [{ serverName: 'remote', serverConfig: serverConfig('remote') }],
+ recoveryPolicy: { discoveryTimeoutMs: 12_000 },
+ },
+ recoveryDeps(discoverServerTools),
+ );
+
+ const [options] = discoverServerTools.mock.calls[0];
+ expect(options.deadlineMs).toBeGreaterThanOrEqual(before + 12_000);
+ expect(options.deadlineMs).toBeLessThanOrEqual(Date.now() + 12_000);
+ });
+
it('leaves a server the config tier marked unreachable to that tier’s retry window', async () => {
const discoverServerTools = jest.fn().mockResolvedValue({ tools: [] });
const deps = recoveryDeps(discoverServerTools);
diff --git a/packages/api/src/mcp/catalog/recovery.ts b/packages/api/src/mcp/catalog/recovery.ts
index ee7a3112f3..d23c74b61b 100644
--- a/packages/api/src/mcp/catalog/recovery.ts
+++ b/packages/api/src/mcp/catalog/recovery.ts
@@ -4,6 +4,7 @@ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
import type { IUser } from '@librechat/data-schemas';
import type { LCAvailableTools, ParsedServerConfig, ToolDiscoveryOptions } from '../types';
import { hasCustomUserVars, getMissingCustomUserVars } from '../utils';
+import { usesDirectOpenIDBearerRecovery } from '../openid';
import { getServerCustomUserVars } from '../auth';
import { mcpConfig } from '../mcpConfig';
@@ -18,7 +19,17 @@ let activeCatalogWork = 0;
* long regardless of where the server stalls. Recovery targets a server that is reachable and
* authorized but whose catalog cache expired, and such a server answers well inside this window.
*/
-const RECOVERY_BUDGET_MS = 3000;
+const DEFAULT_RECOVERY_POLICY: MCPServerCatalogRecoveryPolicy = {
+ discoveryBackoffMs: [5 * 60_000, 10 * 60_000, 20 * 60_000, 30 * 60_000],
+ discoveryTimeoutMs: 3_000,
+ reauthRetryMs: 30 * 60_000,
+ maxStateEntries: 10_000,
+ generationReadTimeoutMs: 500,
+ authorizationFenceRetryMs: [0, 50, 200],
+ authorizationFenceTimeoutMs: 1_000,
+ authorizationFenceRetryIntervalMs: 30_000,
+ authorizationFenceRetryBatchSize: 100,
+};
export interface MCPServerCatalogRecoveryInput {
serverName: string;
@@ -30,8 +41,101 @@ export interface MCPServerCatalogRecoveryDeps {
userId: string,
serverNames: readonly string[],
) => Promise<Record<string, Record<string, string>>>;
- discoverServerTools: (options: ToolDiscoveryOptions) => Promise<{ tools: Tool[] | null }>;
+ discoverServerTools: (options: ToolDiscoveryOptions) => Promise<{
+ tools: Tool[] | null;
+ oauthRequired?: boolean;
+ authenticationKind?: 'oauth' | 'obo' | 'server';
+ }>;
formatServerTools: (serverName: string, tools: Tool[]) => LCAvailableTools;
+ recoveryTracker?: MCPServerCatalogRecoveryTracker;
+ getRecoveryGeneration?: MCPRecoveryGenerationReader;
+}
+
+export interface MCPRecoveryGenerationScope {
+ userId: string;
+ serverName: string;
+}
+
+export type MCPRecoveryGenerationReader = (
+ scope: MCPRecoveryGenerationScope,
+) => Promise<string | undefined>;
+
+const AUTHORIZATION_FENCE_RETRY_DELAYS_MS = [0, 50, 200] as const;
+
+export async function publishMCPAuthorizationMutation(
+ scope: MCPRecoveryGenerationScope,
+ deps: {
+ invalidateRecoveryGeneration: (scope: MCPRecoveryGenerationScope) => Promise<unknown>;
+ clearLocalRecovery?: (userId: string, serverName: string) => void;
+ persistPublicationRetry?: (scope: MCPRecoveryGenerationScope) => Promise<string>;
+ clearPublicationRetry?: (
+ scope: MCPRecoveryGenerationScope,
+ publicationRetryVersion: string,
+ ) => Promise<void>;
+ retryDelaysMs?: readonly number[];
+ attemptTimeoutMs?: number;
+ },
+): Promise<void> {
+ /** 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. */
+ const publicationRetryVersion = await deps.persistPublicationRetry?.(scope);
+ let lastError: unknown;
+ for (const delayMs of deps.retryDelaysMs ?? AUTHORIZATION_FENCE_RETRY_DELAYS_MS) {
+ if (delayMs > 0) {
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ }
+ try {
+ const attemptTimeoutMs =
+ deps.attemptTimeoutMs ?? DEFAULT_RECOVERY_POLICY.authorizationFenceTimeoutMs;
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ deps.invalidateRecoveryGeneration(scope),
+ new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(
+ () => reject(new Error('MCP authorization generation publication timed out')),
+ attemptTimeoutMs,
+ );
+ }),
+ ]);
+ } finally {
+ if (timeoutId != null) clearTimeout(timeoutId);
+ }
+ try {
+ if (publicationRetryVersion != null) {
+ await deps.clearPublicationRetry?.(scope, publicationRetryVersion);
+ }
+ } catch (error) {
+ /** A leftover retry only advances the opaque generation again and is therefore safe. */
+ logger.warn(
+ `[MCP authorization] Published generation for ${scope.serverName} but could not clear its retry intent`,
+ error,
+ );
+ }
+ deps.clearLocalRecovery?.(scope.userId, scope.serverName);
+ return;
+ } catch (error) {
+ lastError = error;
+ logger.warn(
+ `[MCP authorization] Failed to publish credential generation for ${scope.serverName}; retrying`,
+ error,
+ );
+ }
+ }
+ throw lastError;
+}
+
+export interface MCPServerCatalogRecoveryPolicy {
+ discoveryBackoffMs: readonly number[];
+ discoveryTimeoutMs: number;
+ reauthRetryMs: number;
+ maxStateEntries: number;
+ generationReadTimeoutMs: number;
+ authorizationFenceRetryMs: readonly number[];
+ authorizationFenceTimeoutMs: number;
+ authorizationFenceRetryIntervalMs: number;
+ authorizationFenceRetryBatchSize: number;
}
export interface MCPServerCatalogSnapshot {
@@ -65,6 +169,14 @@ export interface MCPServerCatalogLoaderDeps extends MCPServerCatalogRecoveryDeps
export interface MCPServerCatalogLoaderResult {
serverTools: Map<string, LCAvailableTools>;
serversWithoutTools: string[];
+ reauthRequiredServers: Set<string>;
+ reauthRequiredGenerations: Map<string, string | undefined>;
+}
+
+interface MCPServerCatalogRecoveryResult {
+ serverTools: Map<string, LCAvailableTools>;
+ reauthRequiredServers: Set<string>;
+ reauthRequiredGenerations: Map<string, string | undefined>;
}
interface MCPServerCatalogEntry extends MCPServerCatalogSnapshot {
@@ -77,6 +189,23 @@ interface RecoveryCandidate extends MCPServerCatalogRecoveryInput {
customUserVars?: Record<string, string>;
}
+type RecoveryOutcome = {
+ serverName: string;
+ tools: LCAvailableTools | null;
+ state?: 'reauth_required' | 'backoff';
+ recoveryGeneration?: string;
+};
+
+interface RecoveryStateEntry {
+ configFingerprint: string;
+ recoveryGeneration?: string;
+ failureCount: number;
+ nextRetryAt: number;
+ lastTouchedAt: number;
+ outcome?: RecoveryOutcome;
+ inFlight?: Promise<RecoveryOutcome>;
+}
+
interface CatalogWorkLane {
tasks: ReadonlyArray<() => Promise<void>>;
resolve: (admitted: boolean) => void;
@@ -95,35 +224,231 @@ export class MCPCatalogCapacityError extends Error {
}
}
-/** Bounds one server's discovery, honouring a shorter operator `initTimeout`. */
-function resolveBudget(serverConfig: ParsedServerConfig): number {
+/** Reads the cross-replica credential fence without making status or recovery depend on shared
+ * cache availability. The application supplies the cache implementation at its wiring boundary. */
+export async function readMCPRecoveryGeneration(
+ scope: MCPRecoveryGenerationScope,
+ reader?: MCPRecoveryGenerationReader,
+ options?: { timeoutMs?: number; signal?: AbortSignal },
+): Promise<string | undefined> {
+ if (reader == null || options?.signal?.aborted) {
+ return undefined;
+ }
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_RECOVERY_POLICY.generationReadTimeoutMs;
+ let timeoutId: number | undefined;
+ let onAbort: (() => void) | undefined;
+ try {
+ return await Promise.race([
+ reader(scope),
+ new Promise<undefined>((resolve) => {
+ timeoutId = setTimeout(resolve, timeoutMs);
+ if (options?.signal != null) {
+ onAbort = () => resolve(undefined);
+ options.signal.addEventListener('abort', onAbort, { once: true });
+ }
+ }),
+ ]);
+ } catch (error) {
+ logger.debug(
+ `[MCP catalog recovery] Could not read shared generation for ${scope.serverName}; using process-local state`,
+ error,
+ );
+ return undefined;
+ } finally {
+ if (timeoutId != null) {
+ clearTimeout(timeoutId);
+ }
+ if (onAbort != null) {
+ options?.signal?.removeEventListener('abort', onAbort);
+ }
+ }
+}
+
+export async function readMCPRecoveryGenerationAround<T>(
+ scope: MCPRecoveryGenerationScope,
+ reader: MCPRecoveryGenerationReader | undefined,
+ operation: () => Promise<T>,
+ options?: { timeoutMs?: number; signal?: AbortSignal },
+): Promise<{ value: T; generation?: string }> {
+ const before = await readMCPRecoveryGeneration(scope, reader, options);
+ const value = await operation();
+ const after = await readMCPRecoveryGeneration(scope, reader, options);
+ return {
+ value,
+ ...(before != null && before === after && { generation: before }),
+ };
+}
+
+/** Bounds one server's discovery, honouring the shorter configured limit. */
+function resolveBudget(
+ serverConfig: ParsedServerConfig,
+ policy: MCPServerCatalogRecoveryPolicy,
+): number {
const { initTimeout } = serverConfig;
if (typeof initTimeout === 'number') {
- return Math.min(initTimeout, RECOVERY_BUDGET_MS);
+ return Math.min(initTimeout, policy.discoveryTimeoutMs);
+ }
+ return policy.discoveryTimeoutMs;
+}
+
+function getRecoveryKey(userId: string, serverName: string): string {
+ return `${userId}\u0000${serverName}`;
+}
+
+function getRecoveryFingerprint(
+ serverConfig: ParsedServerConfig,
+ policy: MCPServerCatalogRecoveryPolicy,
+): string {
+ return JSON.stringify([serverConfig, policy]);
+}
+
+export class MCPServerCatalogRecoveryTracker {
+ private readonly states = new Map<string, RecoveryStateEntry>();
+
+ constructor(private readonly maxStateEntries: number = DEFAULT_RECOVERY_POLICY.maxStateEntries) {}
+
+ private touch(key: string, entry: RecoveryStateEntry): void {
+ if (this.states.get(key) !== entry) {
+ return;
+ }
+ this.states.delete(key);
+ this.states.set(key, entry);
+ }
+
+ /** Clears suppression after a credential/config mutation commits. */
+ public clear(userId: string, serverName?: string): void {
+ if (serverName != null) {
+ this.states.delete(getRecoveryKey(userId, serverName));
+ return;
+ }
+ const prefix = `${userId}\u0000`;
+ for (const key of this.states.keys()) {
+ if (key.startsWith(prefix)) {
+ this.states.delete(key);
+ }
+ }
+ }
+
+ public run(
+ user: IUser,
+ candidate: RecoveryCandidate,
+ policy: MCPServerCatalogRecoveryPolicy,
+ recoveryGeneration: string | undefined,
+ discover: () => Promise<RecoveryOutcome>,
+ ): Promise<RecoveryOutcome> {
+ const key = getRecoveryKey(user.id, candidate.serverName);
+ const configFingerprint = getRecoveryFingerprint(candidate.serverConfig, policy);
+ const now = Date.now();
+ const existing = this.states.get(key);
+ const sameObservedState =
+ existing?.configFingerprint === configFingerprint &&
+ (recoveryGeneration == null || existing.recoveryGeneration === recoveryGeneration);
+ if (sameObservedState) {
+ existing.lastTouchedAt = now;
+ this.touch(key, existing);
+ if (existing.inFlight != null) {
+ return existing.inFlight;
+ }
+ if (existing.outcome != null && existing.nextRetryAt > now) {
+ return Promise.resolve(existing.outcome);
+ }
+ }
+
+ const entry: RecoveryStateEntry = {
+ configFingerprint,
+ recoveryGeneration:
+ recoveryGeneration ?? (sameObservedState ? existing?.recoveryGeneration : undefined),
+ failureCount: sameObservedState ? existing.failureCount : 0,
+ nextRetryAt: 0,
+ lastTouchedAt: now,
+ };
+ const flight = discover()
+ .then((outcome) => {
+ if (this.states.get(key) !== entry) {
+ return { serverName: candidate.serverName, tools: null };
+ }
+ entry.lastTouchedAt = Date.now();
+ this.touch(key, entry);
+ outcome.recoveryGeneration = entry.recoveryGeneration;
+ if (outcome.state === 'reauth_required') {
+ entry.failureCount = 0;
+ entry.nextRetryAt = entry.lastTouchedAt + policy.reauthRetryMs;
+ /** Keep the authorization decision, but never promote an unfenced discovery catalog
+ * into a cross-request cache. The configured server still appears with no tools. */
+ entry.outcome = { ...outcome, tools: null };
+ } else if (outcome.state === 'backoff') {
+ const delay =
+ policy.discoveryBackoffMs[
+ Math.min(entry.failureCount, policy.discoveryBackoffMs.length - 1)
+ ];
+ entry.failureCount += 1;
+ entry.nextRetryAt = entry.lastTouchedAt + delay;
+ entry.outcome = outcome;
+ } else {
+ this.states.delete(key);
+ }
+ return outcome;
+ })
+ .finally(() => {
+ if (this.states.get(key) === entry) {
+ entry.inFlight = undefined;
+ this.trim();
+ }
+ });
+ entry.inFlight = flight;
+ this.states.set(key, entry);
+ this.trim();
+ return flight;
+ }
+
+ private trim(): void {
+ while (this.states.size > this.maxStateEntries) {
+ let removed = false;
+ for (const [key, entry] of this.states) {
+ if (entry.inFlight != null) {
+ continue;
+ }
+ this.states.delete(key);
+ removed = true;
+ break;
+ }
+ if (!removed) return;
+ }
}
- return RECOVERY_BUDGET_MS;
}
async function discoverCandidate(
user: IUser,
{ serverName, serverConfig, customUserVars }: RecoveryCandidate,
deps: MCPServerCatalogRecoveryDeps,
+ policy: MCPServerCatalogRecoveryPolicy,
signal?: AbortSignal,
-): Promise<[string, LCAvailableTools | null]> {
+): Promise<RecoveryOutcome> {
try {
const result = await deps.discoverServerTools({
user,
serverName,
configServers: { [serverName]: serverConfig },
customUserVars,
- deadlineMs: Date.now() + resolveBudget(serverConfig),
+ deadlineMs: Date.now() + resolveBudget(serverConfig, policy),
signal,
});
- return [
+ const tools = result.tools == null ? null : deps.formatServerTools(serverName, result.tools);
+ if (signal?.aborted) {
+ return { serverName, tools: null };
+ }
+ if (result.oauthRequired === true && result.authenticationKind === 'oauth') {
+ return { serverName, tools, state: 'reauth_required' };
+ }
+ return {
serverName,
- result.tools == null ? null : deps.formatServerTools(serverName, result.tools),
- ];
+ tools,
+ ...(tools == null && { state: 'backoff' as const }),
+ };
} catch (error) {
+ if (signal?.aborted) {
+ return { serverName, tools: null };
+ }
/** Discovery raises `InvalidRequest` precisely when configuration makes the attempt
* impossible — domain policy, unresolved placeholders, missing runtime fields. That
* failure recurs on every request until an admin changes configuration, so it is
@@ -132,10 +457,10 @@ async function discoverCandidate(
logger.debug(
`[MCP catalog recovery] ${serverName} is not recoverable under current configuration: ${error.message}`,
);
- return [serverName, null];
+ return { serverName, tools: null, state: 'backoff' };
}
logger.error(`[MCP catalog recovery] Failed to discover tools for ${serverName}:`, error);
- return [serverName, null];
+ return { serverName, tools: null, state: 'backoff' };
}
}
@@ -218,21 +543,26 @@ function runCatalogWork(
/**
* Passively discovers cold MCP catalogs for one request.
*
- * A recovered catalog cannot be retained: a discovery connection owns no publication generation
- * and is disposed, and the tool cache refuses unfenced writes, so the result is served only to
- * the requesting user. Recovery therefore stays stateless and individually cheap rather than
- * scheduling around a result it is not allowed to keep — it skips only what configuration alone
- * proves pointless, and bounds everything else by a per-server budget.
+ * A recovered catalog cannot enter the authoritative tool cache: a discovery connection owns no
+ * publication generation and is disposed. Process-local recovery state therefore retains only
+ * enough information to coalesce concurrent requests and suppress repeated failed/OAuth attempts;
+ * successful ordinary catalogs remain request-local.
*/
-export async function recoverMCPServerCatalogs(
+async function recoverMCPServerCatalogsWithState(
params: {
user: IUser;
servers: readonly MCPServerCatalogRecoveryInput[];
signal?: AbortSignal;
+ recoveryPolicy?: Partial<MCPServerCatalogRecoveryPolicy>;
},
deps: MCPServerCatalogRecoveryDeps,
-): Promise<Map<string, LCAvailableTools>> {
+): Promise<MCPServerCatalogRecoveryResult> {
const { user, servers, signal } = params;
+ const policy = { ...DEFAULT_RECOVERY_POLICY, ...params.recoveryPolicy };
+ if (policy.discoveryBackoffMs.length === 0) {
+ policy.discoveryBackoffMs = DEFAULT_RECOVERY_POLICY.discoveryBackoffMs;
+ }
+ const tracker = deps.recoveryTracker ?? new MCPServerCatalogRecoveryTracker();
/** Only the config tier retries a failed stub on its own clock. A `yaml`- or `user`-sourced
* stub has no such timer, so skipping it unconditionally would hide the server for good —
* exactly the state this recovery exists to escape. */
@@ -244,9 +574,30 @@ export async function recoverMCPServerCatalogs(
return false;
});
if (recoverable.length === 0) {
- return new Map();
+ return {
+ serverTools: new Map(),
+ reauthRequiredServers: new Set(),
+ reauthRequiredGenerations: new Map(),
+ };
}
+ const generationSnapshots = new Map<string, string | undefined>();
+ await Promise.all(
+ recoverable.map(async ({ serverName, serverConfig }) => {
+ if (serverConfig.obo != null || usesDirectOpenIDBearerRecovery(serverConfig)) {
+ return;
+ }
+ generationSnapshots.set(
+ serverName,
+ await readMCPRecoveryGeneration(
+ { userId: user.id, serverName },
+ deps.getRecoveryGeneration,
+ { timeoutMs: policy.generationReadTimeoutMs, signal },
+ ),
+ );
+ }),
+ );
+
/** Only credential-bearing servers can consume the auth map, so a list without any avoids
* the plugin-auth round trip entirely. */
const credentialServers = recoverable.filter(({ serverConfig }) =>
@@ -274,13 +625,62 @@ export async function recoverMCPServerCatalogs(
authorized.push({ ...candidate, customUserVars });
}
if (authorized.length === 0) {
- return new Map();
+ return {
+ serverTools: new Map(),
+ reauthRequiredServers: new Set(),
+ reauthRequiredGenerations: new Map(),
+ };
}
- const results: Array<[string, LCAvailableTools | null] | undefined> = [];
+ const results: Array<RecoveryOutcome | undefined> = [];
const admitted = await runCatalogWork(
authorized.map((candidate, index) => async () => {
- results[index] = await discoverCandidate(user, candidate, deps, signal);
+ /** OBO and direct OpenID bearer discovery consume a request's live upstream-token closure,
+ * so they must never join another request's flight or outlive that request's cancellation. */
+ const usesRequestCredential =
+ candidate.serverConfig.obo != null ||
+ usesDirectOpenIDBearerRecovery(candidate.serverConfig);
+ if (usesRequestCredential) {
+ results[index] = await discoverCandidate(user, candidate, deps, policy, signal);
+ return;
+ }
+ const observedGeneration = await readMCPRecoveryGeneration(
+ { userId: user.id, serverName: candidate.serverName },
+ deps.getRecoveryGeneration,
+ { timeoutMs: policy.generationReadTimeoutMs, signal },
+ );
+ const snapshotGeneration = generationSnapshots.get(candidate.serverName);
+ const requiresCredentialSnapshotFence = hasCustomUserVars(candidate.serverConfig);
+ if (
+ requiresCredentialSnapshotFence &&
+ (snapshotGeneration == null ||
+ observedGeneration == null ||
+ snapshotGeneration !== observedGeneration)
+ ) {
+ tracker.clear(user.id, candidate.serverName);
+ results[index] = { serverName: candidate.serverName, tools: null };
+ return;
+ }
+ const recoveryGeneration = observedGeneration ?? snapshotGeneration;
+ const outcome = await tracker.run(user, candidate, policy, recoveryGeneration, () =>
+ discoverCandidate(user, candidate, deps, policy),
+ );
+ const finalGeneration = await readMCPRecoveryGeneration(
+ { userId: user.id, serverName: candidate.serverName },
+ deps.getRecoveryGeneration,
+ { timeoutMs: policy.generationReadTimeoutMs, signal },
+ );
+ const outcomeGeneration = outcome.recoveryGeneration ?? recoveryGeneration;
+ if (
+ outcomeGeneration != null &&
+ finalGeneration != null &&
+ outcomeGeneration !== finalGeneration
+ ) {
+ tracker.clear(user.id, candidate.serverName);
+ results[index] = { serverName: candidate.serverName, tools: null };
+ return;
+ }
+ results[index] = outcome;
}),
signal,
);
@@ -288,11 +688,32 @@ export async function recoverMCPServerCatalogs(
throw new MCPCatalogCapacityError();
}
- return new Map(
- results.filter(
- (entry): entry is [string, LCAvailableTools] => entry != null && entry[1] != null,
- ),
- );
+ const serverTools = new Map<string, LCAvailableTools>();
+ const reauthRequiredServers = new Set<string>();
+ const reauthRequiredGenerations = new Map<string, string | undefined>();
+ for (const result of results) {
+ if (result?.tools != null) {
+ serverTools.set(result.serverName, result.tools);
+ }
+ if (result?.state === 'reauth_required') {
+ reauthRequiredServers.add(result.serverName);
+ reauthRequiredGenerations.set(result.serverName, result.recoveryGeneration);
+ }
+ }
+ return { serverTools, reauthRequiredServers, reauthRequiredGenerations };
+}
+
+/** Preserves the public recovery helper's Map contract for existing package consumers. */
+export async function recoverMCPServerCatalogs(
+ params: {
+ user: IUser;
+ servers: readonly MCPServerCatalogRecoveryInput[];
+ signal?: AbortSignal;
+ recoveryPolicy?: Partial<MCPServerCatalogRecoveryPolicy>;
+ },
+ deps: MCPServerCatalogRecoveryDeps,
+): Promise<Map<string, LCAvailableTools>> {
+ return (await recoverMCPServerCatalogsWithState(params, deps)).serverTools;
}
/** Loads cached, connected, then passive MCP catalogs for a marketplace-style list request. */
@@ -301,6 +722,7 @@ export async function loadMCPServerCatalogs(
user: IUser;
servers: readonly MCPServerCatalogRecoveryInput[];
signal?: AbortSignal;
+ recoveryPolicy?: Partial<MCPServerCatalogRecoveryPolicy>;
},
deps: MCPServerCatalogLoaderDeps,
): Promise<MCPServerCatalogLoaderResult> {
@@ -351,10 +773,17 @@ export async function loadMCPServerCatalogs(
const coldServers = snapshots
.filter(({ tools }) => tools == null)
.map(({ serverName, serverConfig }) => ({ serverName, serverConfig }));
- let recovered = new Map<string, LCAvailableTools>();
+ let recovered: MCPServerCatalogRecoveryResult = {
+ serverTools: new Map(),
+ reauthRequiredServers: new Set(),
+ reauthRequiredGenerations: new Map(),
+ };
if (coldServers.length > 0) {
try {
- recovered = await recoverMCPServerCatalogs({ user, servers: coldServers, signal }, deps);
+ recovered = await recoverMCPServerCatalogsWithState(
+ { user, servers: coldServers, signal, recoveryPolicy: params.recoveryPolicy },
+ deps,
+ );
} catch (error) {
if (error instanceof MCPCatalogCapacityError) {
throw error;
@@ -366,12 +795,15 @@ export async function loadMCPServerCatalogs(
const serverTools = new Map<string, LCAvailableTools>();
const serversWithoutTools: string[] = [];
for (const snapshot of snapshots) {
- const tools = snapshot.tools ?? recovered.get(snapshot.serverName);
+ const tools = snapshot.tools ?? recovered.serverTools.get(snapshot.serverName);
if (tools == null) {
serversWithoutTools.push(snapshot.serverName);
continue;
}
serverTools.set(snapshot.serverName, tools);
+ if (snapshot.tools != null) {
+ deps.recoveryTracker?.clear(user.id, snapshot.serverName);
+ }
if (snapshot.source !== 'snapshot' || snapshot.tools == null) {
continue;
@@ -393,5 +825,10 @@ export async function loadMCPServerCatalogs(
);
}
- return { serverTools, serversWithoutTools };
+ return {
+ serverTools,
+ serversWithoutTools,
+ reauthRequiredServers: recovered.reauthRequiredServers,
+ reauthRequiredGenerations: recovered.reauthRequiredGenerations,
+ };
}
diff --git a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts b/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts
index b2fb0bd4e2..77dee5d711 100644
--- a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts
+++ b/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts
@@ -18,6 +18,15 @@ export class OAuthReconnectionManager {
protected readonly flowManager: FlowStateManager<MCPOAuthTokens | null>;
protected readonly tokenMethods: TokenMethods;
private readonly mcpManager: MCPManager | null;
+ private readonly onOAuthCredentialsChanged?: (scope: {
+ userId: string;
+ serverName: string;
+ }) => Promise<void>;
+
+ private readonly onOAuthCredentialsChanging?: (scope: {
+ userId: string;
+ serverName: string;
+ }) => Promise<() => Promise<void>>;
private readonly reconnectionsTracker: OAuthReconnectionTracker;
@@ -32,12 +41,23 @@ export class OAuthReconnectionManager {
flowManager: FlowStateManager<MCPOAuthTokens | null>,
tokenMethods: TokenMethods,
reconnections?: OAuthReconnectionTracker,
+ onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>,
+ onOAuthCredentialsChanging?: (scope: {
+ userId: string;
+ serverName: string;
+ }) => Promise<() => Promise<void>>,
): Promise<OAuthReconnectionManager> {
if (OAuthReconnectionManager.instance != null) {
throw new Error('OAuthReconnectionManager already initialized');
}
- const manager = new OAuthReconnectionManager(flowManager, tokenMethods, reconnections);
+ const manager = new OAuthReconnectionManager(
+ flowManager,
+ tokenMethods,
+ reconnections,
+ onOAuthCredentialsChanged,
+ onOAuthCredentialsChanging,
+ );
OAuthReconnectionManager.instance = manager;
return manager;
@@ -47,10 +67,17 @@ export class OAuthReconnectionManager {
flowManager: FlowStateManager<MCPOAuthTokens | null>,
tokenMethods: TokenMethods,
reconnections?: OAuthReconnectionTracker,
+ onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>,
+ onOAuthCredentialsChanging?: (scope: {
+ userId: string;
+ serverName: string;
+ }) => Promise<() => Promise<void>>,
) {
this.flowManager = flowManager;
this.tokenMethods = tokenMethods;
this.reconnectionsTracker = reconnections ?? new OAuthReconnectionTracker();
+ this.onOAuthCredentialsChanged = onOAuthCredentialsChanged;
+ this.onOAuthCredentialsChanging = onOAuthCredentialsChanging;
try {
this.mcpManager = MCPManager.getInstance();
@@ -196,6 +223,12 @@ export class OAuthReconnectionManager {
serverConfig: config,
flowManager: this.flowManager,
tokenMethods: this.tokenMethods,
+ ...(this.onOAuthCredentialsChanged && {
+ onOAuthCredentialsChanged: this.onOAuthCredentialsChanged,
+ }),
+ ...(this.onOAuthCredentialsChanging && {
+ onOAuthCredentialsChanging: this.onOAuthCredentialsChanging,
+ }),
// don't force new connection, let it reuse existing or create new as needed
forceNew: false,
// set a reasonable timeout for reconnection attempts
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index 1035be76e3..3bbf1d8214 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -1158,7 +1158,10 @@ export class MCPOAuthHandler {
authorizationCode: string,
flowManager: FlowStateManager<MCPOAuthTokens>,
oauthHeaders: Record<string, string>,
- persistBeforeComplete?: (tokens: MCPOAuthTokens) => Promise<MCPOAuthTokens>,
+ persistBeforeComplete?: (
+ tokens: MCPOAuthTokens,
+ completePersistedFlow: (tokens: MCPOAuthTokens) => Promise<void>,
+ ) => Promise<MCPOAuthTokens>,
rollbackPersistedTokens?: (tokens: MCPOAuthTokens) => Promise<void>,
expectedAttempt?: { createdAt: number; state: string },
): Promise<MCPOAuthTokens> {
@@ -1241,22 +1244,39 @@ export class MCPOAuthHandler {
* Persist before completing the flow so waiting connection factories cannot race the
* callback route to write the same credential generation.
*/
+ const observedState = typeof metadata.state === 'string' ? metadata.state : '';
+ let flowCompleted = false;
+ let completionPromise: Promise<void> | undefined;
+ const completePersistedFlow = async (persistedTokens: MCPOAuthTokens): Promise<void> => {
+ completionPromise ??= (async () => {
+ const completionResult = await flowManager.completeFlowIfCurrent(
+ flowId,
+ this.FLOW_TYPE,
+ flowState.createdAt,
+ observedState,
+ persistedTokens,
+ );
+ if (completionResult !== 'updated') {
+ throw new Error('OAuth flow was cancelled before completion');
+ }
+ flowCompleted = true;
+ })();
+ await completionPromise;
+ };
+
if (persistBeforeComplete) {
- mcpTokens = await persistBeforeComplete(mcpTokens);
+ mcpTokens = await persistBeforeComplete(mcpTokens, completePersistedFlow);
}
- /** Now wake flow waiters with the persisted token snapshot. */
- const observedState = typeof metadata.state === 'string' ? metadata.state : '';
- const completionResult = await flowManager.completeFlowIfCurrent(
- flowId,
- this.FLOW_TYPE,
- flowState.createdAt,
- observedState,
- mcpTokens,
- );
- if (completionResult !== 'updated') {
- await rollbackPersistedTokens?.(mcpTokens);
- throw new Error('OAuth flow was cancelled before completion');
+ /** Legacy persistence callbacks complete here. Transaction-aware callbacks can settle
+ * inside their own rollback boundary by invoking `completePersistedFlow` themselves. */
+ if (!flowCompleted) {
+ try {
+ await completePersistedFlow(mcpTokens);
+ } catch (error) {
+ await rollbackPersistedTokens?.(mcpTokens);
+ throw error;
+ }
}
return mcpTokens;
diff --git a/packages/api/src/mcp/oauth/tokens.ts b/packages/api/src/mcp/oauth/tokens.ts
index 898b5c7a32..51d401c44f 100644
--- a/packages/api/src/mcp/oauth/tokens.ts
+++ b/packages/api/src/mcp/oauth/tokens.ts
@@ -28,6 +28,23 @@ export class ReauthenticationRequiredError extends Error {
}
}
+/** Durable credentials could not be read or decrypted. This is retryable infrastructure state,
+ * never evidence that the user must authorize the server again. */
+export class MCPTokenStorageUnavailableError extends Error {
+ constructor(serverName: string, cause: unknown) {
+ super(`OAuth token storage is unavailable for "${serverName}"`, { cause });
+ this.name = 'MCPTokenStorageUnavailableError';
+ }
+}
+
+/** The refresh credential may still be usable, but its provider could not complete this attempt. */
+export class MCPTokenRefreshUnavailableError extends Error {
+ constructor(serverName: string, cause: unknown) {
+ super(`OAuth token refresh is temporarily unavailable for "${serverName}"`, { cause });
+ this.name = 'MCPTokenRefreshUnavailableError';
+ }
+}
+
interface StoreTokensParams {
userId: string;
serverName: string;
@@ -48,6 +65,10 @@ interface StoreTokensParams {
refreshToken?: IToken | null;
clientInfoToken?: IToken | null;
};
+ /** Runs after all token rows are written but while the rollback journal is still available. */
+ onStoreCommitted?: (tokens: MCPOAuthTokens) => Promise<void>;
+ /** Runs after preflight reads and encryption, immediately before the first token-row write. */
+ onStorePreparing?: () => Promise<void>;
}
interface GetTokensParams {
@@ -81,6 +102,8 @@ interface GetTokensParams {
* cache invalidation tied to the fresh tokens cannot be skipped by a timeout.
*/
onRefreshSuccess?: (tokens: MCPOAuthTokens) => Promise<void>;
+ /** Creates the exact post-write callback after durable fence intent is safely stored. */
+ onRefreshPreparing?: () => Promise<(tokens?: MCPOAuthTokens) => Promise<void>>;
/** Separates in-flight redemptions for the same named server under different OAuth bindings. */
singleFlightScope?: string;
/** Shared cache-backed fence used to serialize refresh persistence with server teardown. */
@@ -373,6 +396,8 @@ export class MCPTokenStorage {
metadata,
expectedCredentialSetId,
signal,
+ onStoreCommitted,
+ onStorePreparing,
}: StoreTokensParams): Promise<MCPOAuthTokens> {
const logPrefix = this.getLogPrefix(userId, serverName);
const rollbackWrites: Array<() => Promise<void>> = [];
@@ -710,6 +735,8 @@ export class MCPTokenStorage {
]
: plannedWrites;
+ await onStorePreparing?.();
+
for (const write of orderedWrites) {
if (signal?.aborted) {
throw new Error('Token storage aborted by OAuth teardown');
@@ -730,6 +757,15 @@ export class MCPTokenStorage {
}
}
+ const storedTokens: MCPOAuthTokens = {
+ ...tokens,
+ credential_set_id: credentialSetId,
+ obtained_at:
+ 'obtained_at' in tokens && typeof tokens.obtained_at === 'number'
+ ? tokens.obtained_at
+ : Date.now(),
+ expires_at: accessTokenExpiry.getTime(),
+ };
/**
* An interactive response without a refresh token must never bind an older refresh
* secret to the new client. Remove that stale record after the committed writes. This
@@ -761,20 +797,14 @@ export class MCPTokenStorage {
}
}
+ await onStoreCommitted?.(storedTokens);
+
logger.debug(`${logPrefix} Stored OAuth tokens`, {
client_id: clientInfo?.client_id,
has_refresh_token: !!tokens.refresh_token,
expires_at: 'expires_at' in tokens ? tokens.expires_at : 'N/A',
});
- return {
- ...tokens,
- credential_set_id: credentialSetId,
- obtained_at:
- 'obtained_at' in tokens && typeof tokens.obtained_at === 'number'
- ? tokens.obtained_at
- : Date.now(),
- expires_at: accessTokenExpiry.getTime(),
- };
+ return storedTokens;
} catch (error) {
for (const rollback of rollbackWrites.reverse()) {
try {
@@ -972,6 +1002,7 @@ export class MCPTokenStorage {
refreshTokens,
existingAccessToken,
onRefreshSuccess,
+ onRefreshPreparing,
signal,
flowManager,
leaseId,
@@ -1110,6 +1141,7 @@ export class MCPTokenStorage {
// Pass existing token state to avoid duplicate DB calls
let storedTokens: MCPOAuthTokens;
try {
+ let preparedRefreshCommit: ((tokens?: MCPOAuthTokens) => Promise<void>) | undefined;
storedTokens = await this.storeTokens({
userId,
serverName,
@@ -1127,6 +1159,19 @@ export class MCPTokenStorage {
metadata: storedClientMetadata,
expectedCredentialSetId: refreshCredentialSetId,
signal,
+ onStorePreparing:
+ onRefreshPreparing == null
+ ? undefined
+ : async () => {
+ preparedRefreshCommit = await onRefreshPreparing();
+ },
+ onStoreCommitted: async (tokens) => {
+ if (preparedRefreshCommit != null) {
+ await preparedRefreshCommit(tokens);
+ } else {
+ await onRefreshSuccess?.(tokens);
+ }
+ },
});
} finally {
try {
@@ -1138,14 +1183,6 @@ export class MCPTokenStorage {
}
}
- if (onRefreshSuccess) {
- try {
- await onRefreshSuccess(storedTokens);
- } catch (hookError) {
- logger.warn(`${logPrefix} onRefreshSuccess callback failed`, hookError);
- }
- }
-
logger.info(`${logPrefix} Successfully refreshed and stored OAuth tokens`);
return storedTokens;
} catch (refreshError) {
@@ -1153,18 +1190,32 @@ export class MCPTokenStorage {
if (refreshError instanceof ReauthenticationRequiredError) {
throw refreshError;
}
+ if (
+ signal.aborted &&
+ this.refreshTeardownCounts.has(this.getRefreshOwnerKey(userId, serverName))
+ ) {
+ return null;
+ }
// Check if it's an unauthorized_client error (refresh not supported)
const errorMessage =
refreshError instanceof Error ? refreshError.message : String(refreshError);
- if (errorMessage.toLowerCase().includes('unauthorized_client')) {
+ const normalizedErrorMessage = errorMessage.toLowerCase();
+ if (normalizedErrorMessage.includes('unauthorized_client')) {
logger.info(
`${logPrefix} Server does not support refresh tokens for this client. New authentication required.`,
);
- } else if (isInvalidClientMessage(errorMessage)) {
+ return null;
+ }
+ if (normalizedErrorMessage.includes('invalid_grant')) {
+ logger.info(`${logPrefix} Refresh grant is no longer valid. New authentication required.`);
+ return null;
+ }
+ if (isInvalidClientMessage(errorMessage)) {
if (deleteTokens) {
logger.info(
`${logPrefix} Client registration rejected during token refresh, attempting to clear stale registration and refresh token`,
);
+ const publishPreparedCleanup = await onRefreshPreparing?.();
const results = await Promise.allSettled([
MCPTokenStorage.deleteClientRegistration({
userId,
@@ -1186,13 +1237,15 @@ export class MCPTokenStorage {
logger.warn(`${logPrefix} Failed to clear stale token data`, r.reason);
}
}
+ await publishPreparedCleanup?.();
throw new ReauthenticationRequiredError(serverName, 'invalid_client');
}
logger.warn(
`${logPrefix} Client registration rejected during token refresh but deleteTokens not available — stale registration cannot be cleared`,
);
+ return null;
}
- return null;
+ throw new MCPTokenRefreshUnavailableError(serverName, refreshError);
}
}
@@ -1209,6 +1262,8 @@ export class MCPTokenStorage {
refreshTokens,
singleFlightScope,
flowManager,
+ onRefreshSuccess,
+ onRefreshPreparing,
}: GetTokensParams): Promise<MCPOAuthTokens | null> {
const logPrefix = this.getLogPrefix(userId, serverName);
@@ -1258,6 +1313,8 @@ export class MCPTokenStorage {
refreshTokens,
singleFlightScope,
flowManager,
+ onRefreshSuccess,
+ onRefreshPreparing,
existingAccessToken: accessTokenData,
});
}
@@ -1309,11 +1366,14 @@ export class MCPTokenStorage {
logger.debug(`${logPrefix} Loaded existing OAuth tokens from storage`);
return tokens;
} catch (error) {
- if (error instanceof ReauthenticationRequiredError) {
+ if (
+ error instanceof ReauthenticationRequiredError ||
+ error instanceof MCPTokenRefreshUnavailableError
+ ) {
throw error;
}
logger.error(`${logPrefix} Failed to retrieve tokens`, error);
- return null;
+ throw new MCPTokenStorageUnavailableError(serverName, error);
}
}
diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.ts
index 3d3bcabe34..98d1ae4ffa 100644
--- a/packages/api/src/mcp/types/index.ts
+++ b/packages/api/src/mcp/types/index.ts
@@ -261,6 +261,13 @@ export interface UserConnectionContext {
* only a single `connect()`, so a caller that must return within a fixed budget sets this to
* cap every segment, including `tools/list` pagination and the unauthenticated fallback. */
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. */
+ onOAuthCredentialsChanging?: (scope: {
+ userId: string;
+ serverName: string;
+ }) => Promise<() => Promise<void>>;
}
export interface RequestScopedMCPConnectionStore {
@@ -324,6 +331,8 @@ export interface ToolDiscoveryOptions {
connectionTimeout?: number;
/** Absolute epoch-ms bound on the whole discovery operation; see `UserConnectionContext`. */
deadlineMs?: number;
+ onOAuthCredentialsChanged?: (scope: { userId: string; serverName: string }) => Promise<void>;
+ onOAuthCredentialsChanging?: UserConnectionContext['onOAuthCredentialsChanging'];
/** Pre-resolved config-source servers for tenant-scoped lookup */
configServers?: Record<string, ParsedServerConfig>;
oboTokenResolver?: OboTokenResolver;
@@ -336,4 +345,5 @@ export interface ToolDiscoveryResult {
tools: Tool[] | null;
oauthRequired: boolean;
oauthUrl: string | null;
+ authenticationKind?: 'oauth' | 'obo' | 'server';
}
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index bd9f964b07..1b3917fd84 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -917,6 +917,58 @@ describe('allowedAddressesSchema', () => {
expect(result.success).toBe(true);
});
+ it('defaults and validates MCP catalog recovery controls', () => {
+ const defaults = configSchema.parse({ version: '1.0', mcpSettings: {} });
+ expect(defaults.mcpSettings?.catalogRecovery).toEqual({
+ discoveryBackoffMs: [300_000, 600_000, 1_200_000, 1_800_000],
+ discoveryTimeoutMs: 3_000,
+ reauthRetryMs: 1_800_000,
+ maxStateEntries: 10_000,
+ generationReadTimeoutMs: 500,
+ authorizationFenceRetryMs: [0, 50, 200],
+ authorizationFenceTimeoutMs: 1_000,
+ authorizationFenceRetryIntervalMs: 30_000,
+ authorizationFenceRetryBatchSize: 100,
+ });
+
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ mcpSettings: { catalogRecovery: { discoveryBackoffMs: [] } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ mcpSettings: { catalogRecovery: { discoveryTimeoutMs: 0 } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ mcpSettings: { catalogRecovery: { authorizationFenceRetryMs: [-1] } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ mcpSettings: { catalogRecovery: { authorizationFenceTimeoutMs: 0 } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ mcpSettings: { catalogRecovery: { authorizationFenceRetryIntervalMs: 0 } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ mcpSettings: { catalogRecovery: { authorizationFenceRetryBatchSize: 0 } },
+ }).success,
+ ).toBe(false);
+ });
+
it('accepts the field on actions', () => {
const result = configSchema.safeParse({
version: '1.0',
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 4a6fa293b7..3bd0bfaee5 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2690,6 +2690,48 @@ export const configSchema = z.object({
.object({
allowedDomains: z.array(z.string()).optional(),
allowedAddresses: allowedAddressesSchema,
+ catalogRecovery: z
+ .object({
+ discoveryBackoffMs: z
+ .array(
+ z
+ .number()
+ .int()
+ .positive()
+ .max(24 * 60 * 60_000),
+ )
+ .min(1)
+ .max(8)
+ .default([5 * 60_000, 10 * 60_000, 20 * 60_000, 30 * 60_000]),
+ discoveryTimeoutMs: z
+ .number()
+ .int()
+ .positive()
+ .max(5 * 60_000)
+ .default(3_000),
+ reauthRetryMs: z
+ .number()
+ .int()
+ .positive()
+ .max(24 * 60 * 60_000)
+ .default(30 * 60_000),
+ maxStateEntries: z.number().int().positive().max(1_000_000).default(10_000),
+ generationReadTimeoutMs: z.number().int().positive().max(10_000).default(500),
+ authorizationFenceRetryMs: z
+ .array(z.number().int().nonnegative().max(60_000))
+ .min(1)
+ .max(8)
+ .default([0, 50, 200]),
+ authorizationFenceTimeoutMs: z.number().int().positive().max(30_000).default(1_000),
+ authorizationFenceRetryIntervalMs: z
+ .number()
+ .int()
+ .positive()
+ .max(60 * 60_000)
+ .default(30_000),
+ authorizationFenceRetryBatchSize: z.number().int().positive().max(10_000).default(100),
+ })
+ .default({}),
})
.optional(),
interface: interfaceSchema,
diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.ts
index 8443897c1b..565c9e1b0b 100644
--- a/packages/data-provider/src/types/queries.ts
+++ b/packages/data-provider/src/types/queries.ts
@@ -140,6 +140,10 @@ export type MCPServer = {
name: string;
icon: string;
authenticated: boolean;
+ /** Passive discovery found that stored OAuth authorization must be renewed. */
+ authorizationState?: 'reauth_required';
+ /** Shared credential/catalog generation observed by passive discovery. */
+ authorizationGeneration?: string;
authConfig: s.TPluginAuthConfig[];
tools: MCPTool[];
};
@@ -242,6 +246,8 @@ export interface MCPServerStatus {
| 'authorized'
| 'needs_authorization'
| 'error';
+ /** Shared credential/catalog generation observed by the status endpoint. */
+ authorizationGeneration?: string;
}
export interface MCPConnectionStatusResponse {
@@ -259,6 +265,7 @@ export interface MCPServerConnectionStatusResponse {
configurationState?: MCPServerStatus['configurationState'];
connectionStatus: 'disconnected' | 'connecting' | 'connected' | 'error';
authorizationState?: MCPServerStatus['authorizationState'];
+ authorizationGeneration?: string;
}
export interface MCPAuthValuesResponse {
diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.ts
index 0e9299b970..feb39b8823 100644
--- a/packages/data-schemas/src/index.ts
+++ b/packages/data-schemas/src/index.ts
@@ -41,6 +41,7 @@ export {
recordAgentEventActorReceiptMetric,
setAgentEventActorReceiptMetricObserver,
MCPAuthorityProofError,
+ createMCPAuthorizationFenceRetryStorage,
MAX_MCP_AUTHORITY_TARGETS,
createMCPAuthorityBootRevision,
createMCPAuthorityConfigSourceRevision,
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index 942e6a7d0c..eca37034d6 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -3,6 +3,10 @@ import {
createOpenIDRefreshFlightMethods,
type OpenIDRefreshFlightMethods,
} from './openidRefreshFlight';
+export {
+ createMCPAuthorizationFenceRetryStorage,
+ type MCPAuthorizationFenceRetryStorage,
+} from './mcpAuthorizationFenceRetry';
import {
createRefreshTokenBridgeMethods,
type RefreshTokenBridgeMethods,
diff --git a/packages/data-schemas/src/methods/mcpAuthorizationFenceRetry.spec.ts b/packages/data-schemas/src/methods/mcpAuthorizationFenceRetry.spec.ts
new file mode 100644
index 0000000000..3652bddfe4
--- /dev/null
+++ b/packages/data-schemas/src/methods/mcpAuthorizationFenceRetry.spec.ts
@@ -0,0 +1,59 @@
+import { createMCPAuthorizationFenceRetryStorage } from './mcpAuthorizationFenceRetry';
+
+const mockBuildIndexWithRetry = jest.fn(
+ async (build: () => Promise<unknown>, _label?: string, _options?: unknown) => build(),
+);
+const mockRunAsSystem = jest.fn(async (operation: () => Promise<unknown>) => operation());
+
+jest.mock('~/utils/retry', () => ({
+ buildIndexWithRetry: (build: () => Promise<unknown>, label?: string, options?: unknown) =>
+ mockBuildIndexWithRetry(build, label, options),
+}));
+jest.mock('~/config/tenantContext', () => ({
+ runAsSystem: (operation: () => Promise<unknown>) => mockRunAsSystem(operation),
+}));
+
+describe('MCP authorization fence retry storage', () => {
+ it('guards its index and preserves exact-version mutations', async () => {
+ const updateOne = jest.fn().mockResolvedValue({ acknowledged: true });
+ const deleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
+ const toArray = jest.fn().mockResolvedValue([{ version: 'v2' }]);
+ const limit = jest.fn(() => ({ toArray }));
+ const sort = jest.fn(() => ({ limit }));
+ const createIndex = jest.fn().mockResolvedValue('updatedAt_1');
+ const collection = { updateOne, deleteOne, find: jest.fn(() => ({ sort })), createIndex };
+ const mongoose = {
+ connection: { collection: jest.fn(() => collection) },
+ } as unknown as typeof import('mongoose');
+ const storage = createMCPAuthorizationFenceRetryStorage(mongoose);
+ const scope = { userId: 'user-1', serverName: 'github' };
+ const now = new Date('2026-01-01T00:00:00.000Z');
+
+ await storage.upsert({ scope, tenantId: 'tenant-a', version: 'v2', now });
+ await storage.deleteVersion({ scope, tenantId: 'tenant-a', version: 'v1' });
+ await storage.deferVersion({
+ scope,
+ tenantId: 'tenant-a',
+ version: 'v2',
+ updatedAt: new Date(now.getTime() + 1),
+ });
+ await expect(storage.list(7)).resolves.toEqual([{ version: 'v2' }]);
+
+ expect(deleteOne).toHaveBeenCalledWith({
+ _id: JSON.stringify(['tenant-a', 'user-1', 'github', 'v1']),
+ version: 'v1',
+ });
+ expect(updateOne).toHaveBeenLastCalledWith(
+ { _id: JSON.stringify(['tenant-a', 'user-1', 'github', 'v2']), version: 'v2' },
+ { $max: { updatedAt: new Date(now.getTime() + 1) } },
+ );
+ expect(mockBuildIndexWithRetry).toHaveBeenCalledWith(
+ expect.any(Function),
+ 'mcp_authorization_fence_retries.updatedAt_1',
+ undefined,
+ );
+ expect(createIndex).toHaveBeenCalledWith({ updatedAt: 1 }, { name: 'updatedAt_1' });
+ expect(limit).toHaveBeenCalledWith(7);
+ expect(mockRunAsSystem).toHaveBeenCalledWith(expect.any(Function));
+ });
+});
diff --git a/packages/data-schemas/src/methods/mcpAuthorizationFenceRetry.ts b/packages/data-schemas/src/methods/mcpAuthorizationFenceRetry.ts
new file mode 100644
index 0000000000..cc81afb0e7
--- /dev/null
+++ b/packages/data-schemas/src/methods/mcpAuthorizationFenceRetry.ts
@@ -0,0 +1,97 @@
+import type { Collection } from 'mongodb';
+import { runAsSystem } from '~/config/tenantContext';
+import { buildIndexWithRetry } from '~/utils/retry';
+
+const COLLECTION_NAME = 'mcp_authorization_fence_retries';
+const UPDATED_AT_INDEX = 'updatedAt_1';
+
+export interface MCPAuthorizationFenceRetryScope {
+ userId: string;
+ serverName: string;
+}
+
+export interface MCPAuthorizationFenceRetryRecord extends MCPAuthorizationFenceRetryScope {
+ _id: string;
+ tenantId?: string | null;
+ version: string;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+interface RetryVersionInput {
+ scope: MCPAuthorizationFenceRetryScope;
+ tenantId?: string | null;
+ version: string;
+}
+
+interface RetryUpsertInput extends RetryVersionInput {
+ now: Date;
+}
+
+interface RetryDeferInput extends RetryVersionInput {
+ updatedAt: Date;
+}
+
+function retryId(
+ scope: MCPAuthorizationFenceRetryScope,
+ tenantId: string | null | undefined,
+ version: string,
+): string {
+ return JSON.stringify([tenantId ?? '', String(scope.userId), scope.serverName, version]);
+}
+
+/** Owns the raw collection and guarded index lifecycle used by durable MCP fence replay. */
+export function createMCPAuthorizationFenceRetryStorage(mongoose: typeof import('mongoose')) {
+ let indexPromise: Promise<unknown> | undefined;
+ const collection = (): Collection<MCPAuthorizationFenceRetryRecord> =>
+ mongoose.connection.collection<MCPAuthorizationFenceRetryRecord>(COLLECTION_NAME);
+
+ const ensureIndex = (): Promise<unknown> => {
+ indexPromise ??= buildIndexWithRetry(
+ () => collection().createIndex({ updatedAt: 1 }, { name: UPDATED_AT_INDEX }),
+ `${COLLECTION_NAME}.${UPDATED_AT_INDEX}`,
+ ).catch((error) => {
+ indexPromise = undefined;
+ throw error;
+ });
+ return indexPromise;
+ };
+
+ return {
+ async upsert({ scope, tenantId, version, now }: RetryUpsertInput): Promise<void> {
+ await collection().updateOne(
+ { _id: retryId(scope, tenantId, version) },
+ {
+ $set: {
+ userId: String(scope.userId),
+ serverName: scope.serverName,
+ tenantId: tenantId ?? null,
+ version,
+ updatedAt: now,
+ },
+ $setOnInsert: { createdAt: now },
+ },
+ { upsert: true },
+ );
+ },
+ async deleteVersion({ scope, tenantId, version }: RetryVersionInput): Promise<void> {
+ await collection().deleteOne({ _id: retryId(scope, tenantId, version), version });
+ },
+ async deferVersion({ scope, tenantId, version, updatedAt }: RetryDeferInput): Promise<void> {
+ await collection().updateOne(
+ { _id: retryId(scope, tenantId, version), version },
+ { $max: { updatedAt } },
+ );
+ },
+ async list(limit: number): Promise<MCPAuthorizationFenceRetryRecord[]> {
+ await ensureIndex();
+ return runAsSystem(async () =>
+ collection().find({}).sort({ updatedAt: 1 }).limit(limit).toArray(),
+ );
+ },
+ };
+}
+
+export type MCPAuthorizationFenceRetryStorage = ReturnType<
+ typeof createMCPAuthorizationFenceRetryStorage
+>;