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: Retire Cancelled MCP OAuth State (#15702)

Danny Avila601ed078709b
diff --git a/api/config/index.js b/api/config/index.js
index 804c094d29..79a1c24663 100644
--- a/api/config/index.js
+++ b/api/config/index.js
@@ -4,6 +4,7 @@ const {
mcpConfig,
MCPManager,
FlowStateManager,
+ evalKeyvRedisScript,
MCPServersRegistry,
OAuthReconnectionManager,
} = require('@librechat/api');
@@ -27,6 +28,7 @@ function getFlowStateManager(flowsCache) {
ttl: mcpConfig.OAUTH_FLOW_TTL,
monitorTimeout: mcpConfig.OAUTH_HANDLING_TIMEOUT,
retainedFailureTypes: ['mcp_oauth'],
+ redisScriptExecutor: evalKeyvRedisScript,
});
}
return flowManager;
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js
index d90f7f0f5b..79defb5df4 100644
--- a/api/server/controllers/UserController.js
+++ b/api/server/controllers/UserController.js
@@ -1,11 +1,9 @@
const mongoose = require('mongoose');
-const { logger, getTenantId } = require('@librechat/data-schemas');
+const { logger } = require('@librechat/data-schemas');
const {
getNewS3URL,
needsRefresh,
GenerationJobManager,
- MCPOAuthHandler,
- MCPTokenStorage,
getAppConfigOptionsFromUser,
normalizeHttpError,
getWebSearchInstallEntries,
@@ -14,17 +12,12 @@ const {
deleteAllSharedLinksWithCleanup,
revokeUserCodeEnvironmentWorkers,
} = require('@librechat/api');
-const {
- Tools,
- CacheKeys,
- Constants,
- FileSources,
- ResourceType,
-} = require('librechat-data-provider');
+const { Tools, Constants, FileSources, ResourceType } = require('librechat-data-provider');
const { updateUserPluginAuth, deleteUserPluginAuth } = require('~/server/services/PluginService');
const { verifyOTPOrBackupCode } = require('~/server/services/twoFactorService');
const { verifyEmail, resendVerificationEmail } = require('~/server/services/AuthService');
-const { getMCPManager, getFlowStateManager, getMCPServersRegistry } = require('~/config');
+const { getMCPManager } = require('~/config');
+const { maybeUninstallOAuthMCP } = require('~/server/services/MCP/oauthCleanup');
const { invalidateCachedTools } = require('~/server/services/Config/getCachedTools');
const { processDeleteRequest } = require('~/server/services/Files/process');
const subagentThreadTaskStore = require('~/server/services/Endpoints/agents/subagentThreadStore');
@@ -40,7 +33,6 @@ const {
quiesceUserSchedules,
restoreUserSchedulesFromDeletion,
} = require('~/server/services/Schedules');
-const { getLogStores } = require('~/cache');
const db = require('~/models');
const PUBLIC_USER_RESPONSE_FIELDS = [
@@ -573,208 +565,6 @@ const resendVerificationController = async (req, res) => {
}
};
-/** Best-effort cleanup of stored MCP OAuth tokens and flow state. */
-const clearStoredMCPOAuthState = async (userId, serverName) => {
- try {
- await MCPTokenStorage.deleteUserTokens({
- userId,
- serverName,
- deleteToken: async (filter) => {
- await db.deleteTokens(filter);
- },
- });
- } catch (error) {
- logger.warn(
- `[clearStoredMCPOAuthState] Failed to delete MCP OAuth tokens for ${serverName}:`,
- error,
- );
- }
-
- try {
- const flowsCache = getLogStores(CacheKeys.FLOWS);
- const flowManager = getFlowStateManager(flowsCache);
- const baseFlowId = MCPOAuthHandler.generateFlowId(userId, serverName);
- const tenantId = getTenantId();
- const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(userId, serverName, tenantId);
- const oauthFlowId = MCPOAuthHandler.generateFlowId(userId, serverName, tenantId);
- const flowDeletes = [
- [tokenFlowId, 'mcp_get_tokens'],
- [oauthFlowId, 'mcp_oauth'],
- [baseFlowId, 'mcp_get_tokens'],
- [baseFlowId, 'mcp_oauth'],
- ].filter(
- ([flowId, type], index, deletes) =>
- deletes.findIndex(([candidateId, candidateType]) => {
- return candidateId === flowId && candidateType === type;
- }) === index,
- );
- const results = await Promise.allSettled(
- flowDeletes.map(([flowId, type]) =>
- type === 'mcp_oauth'
- ? MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager)
- : flowManager.deleteFlow(flowId, type),
- ),
- );
- for (const result of results) {
- if (result.status === 'rejected') {
- logger.warn(
- `[clearStoredMCPOAuthState] Failed to clear MCP OAuth flow state for ${serverName}:`,
- result.reason,
- );
- }
- }
- } catch (error) {
- logger.warn(
- `[clearStoredMCPOAuthState] Failed to clear MCP OAuth flow state for ${serverName}:`,
- error,
- );
- }
-};
-
-/** Revokes MCP OAuth tokens at the provider when possible, then clears local state. */
-const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
- if (!pluginKey.startsWith(Constants.mcp_prefix)) {
- // this is not an MCP server, so nothing to do here
- return;
- }
-
- const serverName = pluginKey.replace(Constants.mcp_prefix, '');
- const serverConfig =
- (await getMCPServersRegistry().getServerConfig(serverName, userId)) ??
- appConfig?.mcpServers?.[serverName];
- const oauthServers = await getMCPServersRegistry().getOAuthServers(userId);
- if (!oauthServers.has(serverName) || !serverConfig) {
- await clearStoredMCPOAuthState(userId, serverName);
- return;
- }
-
- // 1. get client info used for revocation (client id, secret)
- let clientTokenData = null;
- try {
- clientTokenData = await MCPTokenStorage.getClientInfoAndMetadata({
- userId,
- serverName,
- findToken: db.findToken,
- });
- } catch (error) {
- logger.warn(
- `[maybeUninstallOAuthMCP] Unable to load OAuth client metadata for ${serverName}; clearing local MCP OAuth state only.`,
- error,
- );
- await clearStoredMCPOAuthState(userId, serverName);
- return;
- }
- if (clientTokenData == null) {
- logger.info(
- `[maybeUninstallOAuthMCP] Missing OAuth client metadata for ${serverName}; clearing local MCP OAuth state only.`,
- );
- await clearStoredMCPOAuthState(userId, serverName);
- return;
- }
- const { clientInfo, clientMetadata } = clientTokenData;
- const storedServerUrl = clientMetadata.server_url;
- const storedClientSource = clientMetadata.client_source;
- if (
- typeof storedServerUrl !== 'string' ||
- typeof clientMetadata.token_endpoint !== 'string' ||
- typeof clientMetadata.revocation_endpoint !== 'string' ||
- typeof clientMetadata.credential_set_id !== 'string' ||
- (storedClientSource !== 'configured' && storedClientSource !== 'dynamic')
- ) {
- logger.warn(
- `[maybeUninstallOAuthMCP] Stored OAuth binding metadata is incomplete for ${serverName}; clearing local MCP OAuth state without remote revocation.`,
- );
- await clearStoredMCPOAuthState(userId, serverName);
- return;
- }
-
- // 2. get decrypted tokens before deletion
- let tokens = null;
- try {
- tokens = await MCPTokenStorage.getTokens({
- userId,
- serverName,
- findToken: db.findToken,
- });
- if (tokens) {
- MCPTokenStorage.assertCredentialSetBinding(
- serverName,
- tokens.credential_set_id,
- clientMetadata,
- );
- }
- } catch (error) {
- tokens = null;
- logger.warn(
- `[maybeUninstallOAuthMCP] Unable to load OAuth tokens for ${serverName}; clearing local token state.`,
- error,
- );
- }
-
- // 3. revoke OAuth tokens at the provider
- const revocationEndpoint = clientMetadata.revocation_endpoint;
- const revocationEndpointAuthMethodsSupported =
- clientMetadata.revocation_endpoint_auth_methods_supported;
- const oauthHeaders = serverConfig.oauth_headers ?? {};
- // Use the request's merged (tenant/principal-scoped) allowlists so admin-panel mcpSettings
- // overrides are honored for OAuth revocation, consistent with inspection/connection.
- const allowedDomains = appConfig?.mcpSettings?.allowedDomains;
- const allowedAddresses = appConfig?.mcpSettings?.allowedAddresses;
-
- if (tokens?.access_token) {
- try {
- await MCPOAuthHandler.revokeOAuthToken(
- serverName,
- tokens.access_token,
- 'access',
- {
- serverUrl: storedServerUrl,
- clientId: clientInfo.client_id,
- clientSecret: clientInfo.client_secret ?? '',
- revocationEndpoint,
- revocationEndpointAuthMethodsSupported,
- },
- oauthHeaders,
- allowedDomains,
- allowedAddresses,
- );
- } catch (error) {
- logger.error(
- `[maybeUninstallOAuthMCP] Error revoking OAuth access token for ${serverName}:`,
- error,
- );
- }
- }
-
- if (tokens?.refresh_token) {
- try {
- await MCPOAuthHandler.revokeOAuthToken(
- serverName,
- tokens.refresh_token,
- 'refresh',
- {
- serverUrl: storedServerUrl,
- clientId: clientInfo.client_id,
- clientSecret: clientInfo.client_secret ?? '',
- revocationEndpoint,
- revocationEndpointAuthMethodsSupported,
- },
- oauthHeaders,
- allowedDomains,
- allowedAddresses,
- );
- } catch (error) {
- logger.error(
- `[maybeUninstallOAuthMCP] Error revoking OAuth refresh token for ${serverName}:`,
- error,
- );
- }
- }
-
- // 4. delete tokens from the DB and clear the flow state after revocation attempts
- await clearStoredMCPOAuthState(userId, serverName);
-};
-
module.exports = {
getUserController,
getTermsStatusController,
diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
index d843005c85..1c16b7e0d1 100644
--- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
+++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
@@ -9,19 +9,21 @@ const mockGetFlowStateManager = jest.fn();
const mockGetMCPServersRegistry = jest.fn();
jest.mock('@librechat/data-schemas', () => ({
+ ...jest.requireActual('@librechat/data-schemas'),
logger: { error: jest.fn(), info: jest.fn(), warn: jest.fn() },
getTenantId: jest.fn(),
webSearchKeys: [],
}));
jest.mock('librechat-data-provider', () => ({
+ ...jest.requireActual('librechat-data-provider'),
Tools: {},
- CacheKeys: { FLOWS: 'flows' },
Constants: { mcp_delimiter: '_mcp_', mcp_prefix: 'mcp_' },
FileSources: {},
}));
jest.mock('@librechat/api', () => ({
+ ...jest.requireActual('@librechat/api'),
MCPOAuthHandler: {
generateFlowId: jest.fn((userId, serverName, tenantId) => {
const flowId = `${userId}:${serverName}`;
@@ -182,6 +184,10 @@ const storedOAuthBinding = {
beforeEach(() => {
jest.clearAllMocks();
getTenantId.mockReturnValue(undefined);
+ mockFindToken.mockImplementation(async ({ type }) => ({
+ token: `encrypted-${type}`,
+ metadata: { credential_set_id: credentialSetId },
+ }));
});
describe('updateUserPluginsController MCP OAuth cleanup', () => {
@@ -228,7 +234,7 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
expect(MCPTokenStorage.getClientInfoAndMetadata).toHaveBeenCalledWith({
userId: 'user-1',
serverName: 'test-server',
- findToken: mockFindToken,
+ findToken: expect.any(Function),
});
expect(MCPTokenStorage.deleteUserTokens).toHaveBeenCalledWith({
userId: 'user-1',
@@ -401,7 +407,7 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
expect(MCPTokenStorage.getTokens).toHaveBeenCalledWith({
userId: 'user-1',
serverName: 'test-server',
- findToken: mockFindToken,
+ findToken: expect.any(Function),
});
expect(logger.warn).toHaveBeenCalledWith(
'[maybeUninstallOAuthMCP] Unable to load OAuth tokens for test-server; clearing local token state.',
@@ -443,7 +449,7 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
expect(MCPTokenStorage.getTokens).toHaveBeenCalledWith({
userId: 'user-1',
serverName: 'test-server',
- findToken: mockFindToken,
+ findToken: expect.any(Function),
});
expect(MCPTokenStorage.assertCredentialSetBinding).toHaveBeenCalledWith(
'test-server',
diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
index 5e6e1d5444..6c46ea509b 100644
--- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
+++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
@@ -22,6 +22,7 @@ const mockLoggerError = jest.fn();
const mockGetTenantId = jest.fn();
jest.mock('@librechat/data-schemas', () => ({
+ ...jest.requireActual('@librechat/data-schemas'),
logger: { info: mockLoggerInfo, warn: mockLoggerWarn, error: mockLoggerError },
getTenantId: (...args) => mockGetTenantId(...args),
webSearchKeys: [],
@@ -29,6 +30,7 @@ jest.mock('@librechat/data-schemas', () => ({
jest.mock('@librechat/api', () => {
return {
+ ...jest.requireActual('@librechat/api'),
MCPOAuthHandler: {
revokeOAuthToken: (...args) => mockRevokeOAuthToken(...args),
deleteFlowAndStateMapping: (...args) => mockDeleteFlowAndStateMapping(...args),
@@ -41,6 +43,8 @@ jest.mock('@librechat/api', () => {
return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;
},
},
+ isOAuthServer: (config) =>
+ config.requiresOAuth !== false && (config.requiresOAuth || config.oauth != null),
MCPTokenStorage: {
getTokens: (...args) => mockGetTokens(...args),
getClientInfoAndMetadata: (...args) => mockGetClientInfoAndMetadata(...args),
@@ -55,8 +59,8 @@ jest.mock('@librechat/api', () => {
});
jest.mock('librechat-data-provider', () => ({
+ ...jest.requireActual('librechat-data-provider'),
Tools: {},
- CacheKeys: { FLOWS: 'flows' },
Constants: { mcp_delimiter: '::', mcp_prefix: 'mcp_' },
FileSources: {},
ResourceType: {},
@@ -161,6 +165,8 @@ const serverConfig = {
oauth_headers: { 'X-Tenant': 'acme' },
};
+const parsedServerConfig = { ...serverConfig };
+
const appConfig = {
mcpServers: { acme: serverConfig },
};
@@ -182,6 +188,10 @@ function setupOAuthServerFound() {
mockGetAllowedDomains.mockReturnValue(['https://acme.example.com']);
mockGetAllowedAddresses.mockReturnValue(null);
mockGetClientInfoAndMetadata.mockResolvedValue({ clientInfo, clientMetadata });
+ mockFindToken.mockImplementation(async ({ type }) => ({
+ token: `encrypted-${type}`,
+ metadata: { credential_set_id: credentialSetId },
+ }));
}
describe('maybeUninstallOAuthMCP', () => {
@@ -234,6 +244,41 @@ describe('maybeUninstallOAuthMCP', () => {
expect(mockDeleteFlowAndStateMapping).toHaveBeenCalledTimes(1);
});
+ test('scopes metadata-missing cleanup to token records snapshotted before flow cancellation', async () => {
+ setupOAuthServerFound();
+ mockGetClientInfoAndMetadata.mockResolvedValue(null);
+ mockFindToken.mockImplementation(async ({ type }) =>
+ type === 'mcp_oauth' ? { token: 'encrypted-old-access' } : null,
+ );
+ mockDeleteUserTokens.mockImplementation(
+ async ({ userId: ownerId, serverName: name, deleteToken }) => {
+ const identifier = `mcp:${name}`;
+ await deleteToken({
+ userId: ownerId,
+ type: 'mcp_oauth_client',
+ identifier: `${identifier}:client`,
+ });
+ await deleteToken({ userId: ownerId, type: 'mcp_oauth', identifier });
+ await deleteToken({
+ userId: ownerId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ });
+ },
+ );
+
+ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);
+
+ expect(mockDeleteTokens).toHaveBeenCalledTimes(1);
+ expect(mockDeleteTokens).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ identifier: 'mcp:acme',
+ token: 'encrypted-old-access',
+ }),
+ );
+ });
+
test('clears stored state when client info cannot be loaded', async () => {
setupOAuthServerFound();
mockGetClientInfoAndMetadata.mockRejectedValue(new Error('bad client data'));
@@ -279,7 +324,13 @@ describe('maybeUninstallOAuthMCP', () => {
credential_set_id: credentialSetId,
});
mockRevokeOAuthToken.mockResolvedValue(undefined);
- mockDeleteUserTokens.mockResolvedValue(undefined);
+ mockFindToken.mockResolvedValue({
+ token: 'encrypted-old-token',
+ metadata: { credential_set_id: credentialSetId },
+ });
+ mockDeleteUserTokens.mockImplementation(async ({ deleteToken }) => {
+ await deleteToken({ userId, type: 'mcp_oauth', identifier: `mcp:${serverName}` });
+ });
mockDeleteFlow.mockResolvedValue(undefined);
await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);
@@ -292,6 +343,10 @@ describe('maybeUninstallOAuthMCP', () => {
expect(mockDeleteUserTokens).toHaveBeenCalledTimes(1);
expect(mockDeleteUserTokens.mock.calls[0][0]).toMatchObject({ userId, serverName });
+ expect(mockDeleteTokens).toHaveBeenCalledWith(
+ expect.objectContaining({ token: 'encrypted-old-token' }),
+ );
+ expect(mockDeleteTokens.mock.calls[0][0]).not.toHaveProperty('metadataCredentialSetId');
expect(mockDeleteFlow).toHaveBeenCalledTimes(1);
expect(mockDeleteFlow.mock.calls[0][1]).toBe('mcp_get_tokens');
@@ -299,6 +354,23 @@ describe('maybeUninstallOAuthMCP', () => {
expect(mockDeleteFlowAndStateMapping).toHaveBeenCalledWith('user-123:acme', expect.anything());
});
+ test('uses a retained deleted-server config to revoke before clearing local state', async () => {
+ setupOAuthServerFound();
+ mockGetServerConfig.mockResolvedValue(null);
+ mockGetOAuthServers.mockResolvedValue(new Set());
+ mockGetTokens.mockResolvedValue({
+ access_token: 'access-abc',
+ credential_set_id: credentialSetId,
+ });
+
+ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig, parsedServerConfig);
+
+ expect(mockGetOAuthServers).not.toHaveBeenCalled();
+ expect(mockRevokeOAuthToken).toHaveBeenCalledTimes(1);
+ expect(mockDeleteUserTokens).toHaveBeenCalledTimes(1);
+ expect(mockDeleteFlowAndStateMapping).toHaveBeenCalledTimes(1);
+ });
+
test('does not revoke tokens from a concurrently replaced credential generation', async () => {
setupOAuthServerFound();
mockGetTokens.mockResolvedValue({
diff --git a/api/server/controllers/__tests__/mcp.servers.spec.js b/api/server/controllers/__tests__/mcp.servers.spec.js
index 7ff8de938d..185a804075 100644
--- a/api/server/controllers/__tests__/mcp.servers.spec.js
+++ b/api/server/controllers/__tests__/mcp.servers.spec.js
@@ -28,6 +28,7 @@ const mockRegistryInstance = {
commitServerUpdate: jest.fn(),
updateServer: jest.fn(),
removeServer: jest.fn(),
+ resolveAllowlists: jest.fn(),
};
const mockMcpManager = { disconnectUserConnection: jest.fn() };
@@ -51,6 +52,7 @@ jest.mock('~/server/services/Config', () => ({
invalidateCachedTools: jest.fn(),
}));
+const mockMaybeUninstallOAuthMCP = jest.fn();
const {
getMCPServersList,
getMCPServerById,
@@ -124,7 +126,12 @@ beforeEach(async () => {
mockRegistryInstance.commitServerUpdate.mockReset();
mockRegistryInstance.updateServer.mockReset();
mockRegistryInstance.removeServer.mockReset();
+ mockRegistryInstance.resolveAllowlists.mockReset().mockResolvedValue({
+ allowedDomains: ['https://oauth.example.com'],
+ allowedAddresses: null,
+ });
mockMcpManager.disconnectUserConnection.mockReset().mockResolvedValue(undefined);
+ mockMaybeUninstallOAuthMCP.mockReset().mockResolvedValue(undefined);
const cacheService = require('~/server/services/Config');
cacheService.invalidateCachedTools.mockReset().mockResolvedValue(undefined);
cacheService.getMCPServerTools.mockReset().mockResolvedValue({ retained: {} });
@@ -354,6 +361,7 @@ describe('DB-backed server mutation fencing', () => {
expect(require('~/server/services/Config').invalidateCachedTools).not.toHaveBeenCalled();
expect(mockRegistryInstance.commitServerUpdate).not.toHaveBeenCalled();
expect(mockMcpManager.disconnectUserConnection).not.toHaveBeenCalled();
+ expect(mockMaybeUninstallOAuthMCP).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(500);
});
@@ -374,6 +382,7 @@ describe('DB-backed server mutation fencing', () => {
);
expect(mockMcpManager.disconnectUserConnection).not.toHaveBeenCalled();
+ expect(mockMaybeUninstallOAuthMCP).not.toHaveBeenCalled();
expect(mockRegistryInstance.commitServerUpdate).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(500);
});
@@ -448,15 +457,33 @@ describe('DB-backed server mutation fencing', () => {
it('fences before deletion and fences cross-replica creations before disconnecting', async () => {
const user = await createUser();
+ mockRegistryInstance.getServerConfig.mockResolvedValue(
+ createDbConfig(new mongoose.Types.ObjectId()),
+ );
mockRegistryInstance.removeServer.mockResolvedValue(undefined);
const res = createRes();
- await deleteMCPServerController({ user, params: { serverName: 'github' } }, res);
+ await deleteMCPServerController(
+ { user, params: { serverName: 'github' } },
+ res,
+ mockMaybeUninstallOAuthMCP,
+ );
const { invalidateCachedTools } = require('~/server/services/Config');
expect(invalidateCachedTools).toHaveBeenCalledWith({ userId: user.id, serverName: 'github' });
expect(invalidateCachedTools).toHaveBeenCalledTimes(2);
expect(mockMcpManager.disconnectUserConnection).toHaveBeenCalledWith(user.id, 'github');
+ expect(mockMaybeUninstallOAuthMCP).toHaveBeenCalledWith(
+ user.id,
+ 'mcp_github',
+ {
+ mcpSettings: {
+ allowedDomains: ['https://oauth.example.com'],
+ allowedAddresses: null,
+ },
+ },
+ expect.objectContaining({ source: 'user' }),
+ );
expect(invalidateCachedTools.mock.invocationCallOrder[0]).toBeLessThan(
mockRegistryInstance.removeServer.mock.invocationCallOrder[0],
);
@@ -469,6 +496,49 @@ describe('DB-backed server mutation fencing', () => {
expect(res.status).toHaveBeenCalledWith(200);
});
+ it('cleans credentials created by an authorized shared user during server deletion', async () => {
+ const owner = await createUser();
+ const sharedUser = await createUser();
+ const dbId = new mongoose.Types.ObjectId();
+ await grantPermission({
+ principalType: PrincipalType.USER,
+ principalId: sharedUser.id,
+ resourceType: ResourceType.MCPSERVER,
+ resourceId: dbId,
+ accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,
+ grantedBy: owner.id,
+ });
+ mockRegistryInstance.getServerConfig.mockResolvedValue(createDbConfig(dbId));
+ mockRegistryInstance.removeServer.mockResolvedValue(undefined);
+ const tokenSnapshot = jest
+ .spyOn(mongoose.models.Token, 'distinct')
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([new mongoose.Types.ObjectId(sharedUser.id)]);
+
+ try {
+ await deleteMCPServerController(
+ { user: owner, params: { serverName: 'github' } },
+ createRes(),
+ mockMaybeUninstallOAuthMCP,
+ );
+
+ expect(tokenSnapshot).toHaveBeenCalledTimes(2);
+ expect(mockMaybeUninstallOAuthMCP).toHaveBeenCalledWith(
+ sharedUser.id,
+ 'mcp_github',
+ expect.any(Object),
+ expect.objectContaining({ dbId: dbId.toString() }),
+ );
+ expect(require('~/server/services/Config').invalidateCachedTools).toHaveBeenCalledWith({
+ userId: sharedUser.id,
+ serverName: 'github',
+ });
+ expect(mockMcpManager.disconnectUserConnection).toHaveBeenCalledWith(sharedUser.id, 'github');
+ } finally {
+ tokenSnapshot.mockRestore();
+ }
+ });
+
it('does not delete the registry entry when the distributed fence fails', async () => {
const user = await createUser();
require('~/server/services/Config').invalidateCachedTools.mockRejectedValue(
diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.js
index dd871e5731..af66d8d4ce 100644
--- a/api/server/controllers/mcp.js
+++ b/api/server/controllers/mcp.js
@@ -6,6 +6,7 @@
* @import { MCPServerDocument } from 'librechat-data-provider'
*/
const { randomUUID } = require('crypto');
+const mongoose = require('mongoose');
const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas');
const {
checkAccess,
@@ -23,6 +24,8 @@ const {
isMCPDomainNotAllowedError,
isMCPInspectionFailedError,
isMCPOAuthSecretReentryRequiredError,
+ prepareMCPServerOAuthDeletion,
+ cleanupDeletedMCPServerOAuthUsers,
} = require('@librechat/api');
const {
Constants,
@@ -626,13 +629,33 @@ const updateMCPServerController = async (req, res) => {
* Delete MCP server
* @route DELETE /api/mcp/servers/:serverName
*/
-const deleteMCPServerController = async (req, res) => {
+const deleteMCPServerController = async (req, res, uninstallOAuthMCP) => {
try {
const userId = req.user?.id;
const { serverName } = req.params;
const registry = getMCPServersRegistry();
const existingConfig = await registry.getServerConfig(serverName, userId);
- const retainedTools = await getMCPServerTools(userId, serverName, existingConfig);
+ const tokenIdentifier = `mcp:${serverName}`;
+ const getTokenUserIds = () =>
+ mongoose.models.Token
+ ? mongoose.models.Token.distinct('userId', {
+ identifier: {
+ $in: [tokenIdentifier, `${tokenIdentifier}:client`, `${tokenIdentifier}:refresh`],
+ },
+ })
+ : Promise.resolve([]);
+ const getAclEntries = () =>
+ existingConfig?.dbId && mongoose.models.AclEntry
+ ? mongoose.models.AclEntry.find({
+ resourceType: ResourceType.MCPSERVER,
+ resourceId: existingConfig.dbId,
+ permBits: { $bitsAnySet: PermissionBits.VIEW },
+ }).lean()
+ : Promise.resolve([]);
+ const [oauthDeletionSnapshot, retainedTools] = await Promise.all([
+ prepareMCPServerOAuthDeletion({ getTokenUserIds, getAclEntries }),
+ getMCPServerTools(userId, serverName, existingConfig),
+ ]);
await invalidateCachedTools({ userId, serverName });
try {
await registry.removeServer(serverName, 'DB', userId);
@@ -648,6 +671,32 @@ const deleteMCPServerController = async (req, res) => {
/** Fence connections another replica could have created before deletion committed. */
await fenceCommittedMCPMutation({ userId, serverName });
await disconnectLocalMCPServer(userId, serverName);
+ try {
+ await cleanupDeletedMCPServerOAuthUsers({
+ ownerUserId: userId,
+ serverName,
+ serverConfig: existingConfig,
+ snapshot: oauthDeletionSnapshot,
+ getTokenUserIds,
+ getUserPrincipals: (candidateUserId) => db.getUserPrincipals({ userId: candidateUserId }),
+ resolveAllowlists: (candidateUserId) =>
+ registry.resolveAllowlists({ userId: candidateUserId }),
+ fenceAndDisconnectUser: async (candidateUserId) => {
+ if (candidateUserId === userId) {
+ return;
+ }
+ await fenceCommittedMCPMutation({ userId: candidateUserId, serverName });
+ await disconnectLocalMCPServer(candidateUserId, serverName);
+ },
+ uninstallOAuthMCP,
+ });
+ } catch (error) {
+ logger.warn(
+ `[deleteMCPServer] Server ${serverName} was deleted, but OAuth cleanup failed for user ${userId}:`,
+ error,
+ );
+ throw error;
+ }
res.status(200).json({ message: 'MCP server deleted successfully' });
} catch (error) {
logger.error('[deleteMCPServer]', error);
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js
index aa5cb4c2e5..dcdf7d8888 100644
--- a/api/server/routes/__tests__/mcp.spec.js
+++ b/api/server/routes/__tests__/mcp.spec.js
@@ -60,6 +60,7 @@ jest.mock('@librechat/api', () => {
resolveStateToFlowId: jest.fn(async (state) => state),
storeStateMapping: jest.fn(),
deleteStateMapping: jest.fn(),
+ failFlowAndDeleteStateMapping: jest.fn(),
},
MCPTokenStorage: {
storeTokens: jest.fn(),
@@ -67,6 +68,9 @@ jest.mock('@librechat/api', () => {
getTokens: jest.fn(),
deleteUserTokens: jest.fn(),
},
+ getMCPServerGeneration: jest.fn((config) =>
+ config.dbId ? `db:${config.dbId}` : `config:${JSON.stringify(config)}`,
+ ),
MCPConnection: {
clearCooldown: jest.fn(),
},
@@ -160,6 +164,10 @@ jest.mock('~/server/services/PluginService', () => ({
getUserPluginAuthValue: jest.fn(),
}));
+jest.mock('~/server/services/MCP/oauthCleanup', () => ({
+ maybeUninstallOAuthMCP: jest.fn().mockResolvedValue(undefined),
+}));
+
jest.mock('~/config', () => ({
getMCPManager: jest.fn(),
getFlowStateManager: jest.fn(),
@@ -588,6 +596,10 @@ describe('MCP Routes', () => {
const { MCPOAuthHandler, MCPTokenStorage } = require('@librechat/api');
const { getLogStores } = require('~/cache');
+ beforeEach(() => {
+ mockRegistryInstance.getServerConfig.mockResolvedValue({});
+ });
+
it('should redirect to error page when OAuth error is received', async () => {
const response = await request(app).get('/api/mcp/test-server/oauth/callback').query({
error: 'access_denied',
@@ -603,13 +615,16 @@ describe('MCP Routes', () => {
it('should fail the flow when OAuth error is received with valid CSRF cookie', async () => {
const flowId = 'test-user-id:test-server';
const mockFlowManager = {
- failFlow: jest.fn().mockResolvedValue(true),
+ getFlowState: jest.fn().mockResolvedValue({
+ createdAt: 123,
+ metadata: { state: flowId },
+ }),
+ failFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
};
getLogStores.mockReturnValueOnce({});
require('~/config').getFlowStateManager.mockReturnValueOnce(mockFlowManager);
MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);
- MCPOAuthHandler.getFlowState.mockResolvedValueOnce({ state: flowId });
const csrfToken = generateTestCsrfToken(flowId);
const response = await request(app)
@@ -623,9 +638,11 @@ describe('MCP Routes', () => {
expect(response.status).toBe(302);
expect(response.headers.location).toBe(`${basePath}/oauth/error?error=invalid_client`);
- expect(mockFlowManager.failFlow).toHaveBeenCalledWith(
+ expect(mockFlowManager.failFlowIfCurrent).toHaveBeenCalledWith(
flowId,
'mcp_oauth',
+ 123,
+ flowId,
'invalid_client',
);
});
@@ -633,13 +650,16 @@ describe('MCP Routes', () => {
it('should fail the flow when OAuth error is received with valid session cookie', async () => {
const flowId = 'test-user-id:test-server';
const mockFlowManager = {
- failFlow: jest.fn().mockResolvedValue(true),
+ getFlowState: jest.fn().mockResolvedValue({
+ createdAt: 123,
+ metadata: { state: flowId },
+ }),
+ failFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
};
getLogStores.mockReturnValueOnce({});
require('~/config').getFlowStateManager.mockReturnValueOnce(mockFlowManager);
MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);
- MCPOAuthHandler.getFlowState.mockResolvedValueOnce({ state: flowId });
const sessionToken = generateTestCsrfToken('test-user-id');
const response = await request(app)
@@ -653,9 +673,11 @@ describe('MCP Routes', () => {
expect(response.status).toBe(302);
expect(response.headers.location).toBe(`${basePath}/oauth/error?error=invalid_client`);
- expect(mockFlowManager.failFlow).toHaveBeenCalledWith(
+ expect(mockFlowManager.failFlowIfCurrent).toHaveBeenCalledWith(
flowId,
'mcp_oauth',
+ 123,
+ flowId,
'invalid_client',
);
});
@@ -663,14 +685,17 @@ describe('MCP Routes', () => {
it('should NOT fail the flow when the error callback carries a superseded state', async () => {
const flowId = 'test-user-id:test-server';
const mockFlowManager = {
- failFlow: jest.fn(),
+ getFlowState: jest.fn().mockResolvedValue({
+ createdAt: 123,
+ metadata: { state: 'current-attempt-state' },
+ }),
+ failFlowIfCurrent: jest.fn(),
};
getLogStores.mockReturnValueOnce({});
require('~/config').getFlowStateManager.mockReturnValueOnce(mockFlowManager);
/** Orphaned mapping resolves the superseded state to the current flow */
MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce(flowId);
- MCPOAuthHandler.getFlowState.mockResolvedValueOnce({ state: 'current-attempt-state' });
const csrfToken = generateTestCsrfToken(flowId);
const response = await request(app)
@@ -684,7 +709,7 @@ describe('MCP Routes', () => {
expect(response.status).toBe(302);
expect(response.headers.location).toBe(`${basePath}/oauth/error?error=access_denied`);
- expect(mockFlowManager.failFlow).not.toHaveBeenCalled();
+ expect(mockFlowManager.failFlowIfCurrent).not.toHaveBeenCalled();
});
it('should NOT fail the flow when OAuth error is received without cookies (DoS prevention)', async () => {
@@ -919,6 +944,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://override.example.com/{{LIBRECHAT_BODY_CONVERSATIONID}}/mcp',
metadata: {},
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -931,7 +957,9 @@ describe('MCP Routes', () => {
access_token: 'test-token',
});
MCPTokenStorage.storeTokens.mockResolvedValue();
- mockRegistryInstance.getServerConfig.mockResolvedValue({});
+ mockRegistryInstance.getServerConfig.mockResolvedValue({
+ url: 'https://override.example.com/{{LIBRECHAT_BODY_CONVERSATIONID}}/mcp',
+ });
const mockMcpManager = createLeasedMcpManager({
fetchToolsSnapshot: jest.fn().mockResolvedValue({ tools: [], complete: true }),
@@ -965,6 +993,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://override.example.com/{{LIBRECHAT_BODY_CONVERSATIONID}}/mcp',
metadata: {},
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -982,7 +1011,7 @@ describe('MCP Routes', () => {
});
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
- mockResolveAllMcpConfigs.mockResolvedValueOnce({ 'test-server': mergedServerConfig });
+ mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': mergedServerConfig });
const fetchOrderedToolsSnapshot = jest
.fn()
@@ -1027,6 +1056,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://override.example.com/mcp',
metadata: {},
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -1049,7 +1079,7 @@ describe('MCP Routes', () => {
});
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
- mockResolveAllMcpConfigs.mockResolvedValueOnce({ 'test-server': mergedServerConfig });
+ mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': mergedServerConfig });
require('@librechat/api').getUserMCPAuthMap.mockResolvedValueOnce({
[`mcp_test-server`]: { LITELLM_KEY: 'sk-real-user-key' },
});
@@ -1094,6 +1124,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://override.example.com/mcp',
metadata: {},
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -1113,7 +1144,7 @@ describe('MCP Routes', () => {
});
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
- mockResolveAllMcpConfigs.mockResolvedValueOnce({ 'test-server': mergedServerConfig });
+ mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': mergedServerConfig });
require('@librechat/api').getUserMCPAuthMap.mockClear();
const mockMcpManager = createLeasedMcpManager({
@@ -1205,6 +1236,68 @@ describe('MCP Routes', () => {
});
});
+ it('rejects a callback when a deleted server name belongs to a replacement generation', async () => {
+ const flowId = 'test-user-id:test-server';
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING', createdAt: Date.now() }),
+ };
+ getLogStores.mockReturnValue({});
+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
+ MCPOAuthHandler.getFlowState.mockResolvedValue({
+ state: flowId,
+ serverName: 'test-server',
+ userId: 'test-user-id',
+ serverUrl: 'https://old.example.com/mcp',
+ serverGeneration: 'db:old-id',
+ });
+ mockRegistryInstance.getServerConfig.mockResolvedValue({
+ dbId: 'replacement-id',
+ url: 'https://old.example.com/mcp',
+ });
+
+ 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');
+ expect(MCPOAuthHandler.completeOAuthFlow).not.toHaveBeenCalled();
+ expect(MCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ });
+
+ it('keeps a Config callback live when inspected config resolution omits the server', async () => {
+ const flowId = 'test-user-id:test-server';
+ const rawConfig = {
+ type: 'streamable-http',
+ url: 'https://runtime.example.com/{{LIBRECHAT_USER_ID}}',
+ };
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING', createdAt: Date.now() }),
+ };
+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
+ require('~/server/services/Config').getAppConfig.mockResolvedValueOnce({
+ mcpConfig: { 'test-server': rawConfig },
+ });
+ MCPOAuthHandler.getFlowState.mockResolvedValue({
+ state: flowId,
+ serverName: 'test-server',
+ userId: 'test-user-id',
+ serverUrl: 'https://runtime.example.com/test-user-id',
+ serverGeneration: `config:${JSON.stringify(rawConfig)}`,
+ });
+ MCPOAuthHandler.completeOAuthFlow.mockRejectedValue(new Error('stop after liveness check'));
+ mockResolveAllMcpConfigs.mockResolvedValue({});
+ mockRegistryInstance.getServerConfig.mockResolvedValue(undefined);
+
+ await request(app)
+ .get('/api/mcp/test-server/oauth/callback')
+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`])
+ .query({ code: 'test-auth-code', state: flowId });
+
+ expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalled();
+ });
+
it('should handle OAuth callback successfully', async () => {
// mockRegistryInstance is defined at the top of the file
const mockFlowManager = {
@@ -1216,6 +1309,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://mcp.example.com/mcp',
metadata: { toolFlowId: 'tool-flow-123' },
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -1228,7 +1322,9 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
- mockRegistryInstance.getServerConfig.mockResolvedValue({});
+ mockRegistryInstance.getServerConfig.mockResolvedValue({
+ url: 'https://mcp.example.com/mcp',
+ });
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -1279,6 +1375,8 @@ describe('MCP Routes', () => {
mockFlowManager,
{},
expect.any(Function),
+ expect.any(Function),
+ expect.objectContaining({ state: flowId }),
);
expect(MCPTokenStorage.storeTokens).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1455,6 +1553,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://mcp.example.com/mcp',
metadata: { toolFlowId: 'tool-flow-123' },
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -1465,6 +1564,9 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockResolveAllMcpConfigs.mockResolvedValue({
+ 'test-server': { url: 'https://mcp.example.com/mcp' },
+ });
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
require('~/config').getOAuthReconnectionManager.mockReturnValue({
@@ -1493,6 +1595,8 @@ describe('MCP Routes', () => {
mockFlowManager,
{ 'X-Custom-Auth': 'header-value' },
expect.any(Function),
+ expect.any(Function),
+ expect.objectContaining({ state: flowId }),
);
expect(mockRegistryInstance.getServerConfig).not.toHaveBeenCalled();
});
@@ -1507,6 +1611,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://mcp.example.com/mcp',
metadata: { toolFlowId: 'tool-flow-123' },
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -1517,6 +1622,7 @@ describe('MCP Routes', () => {
mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({
+ url: 'https://mcp.example.com/mcp',
oauth_headers: { 'X-Registry-Header': 'from-registry' },
});
getLogStores.mockReturnValue({});
@@ -1547,6 +1653,8 @@ describe('MCP Routes', () => {
mockFlowManager,
{ 'X-Registry-Header': 'from-registry' },
expect.any(Function),
+ expect.any(Function),
+ expect.objectContaining({ state: flowId }),
);
expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
'test-server',
@@ -1683,6 +1791,7 @@ describe('MCP Routes', () => {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
+ serverUrl: 'https://mcp.example.com/mcp',
metadata: { toolFlowId: 'tool-flow-request-scoped' },
clientInfo: {},
codeVerifier: 'test-verifier',
@@ -1798,7 +1907,10 @@ describe('MCP Routes', () => {
it('should use original flow state credentials when storing tokens', async () => {
// mockRegistryInstance is defined at the top of the file
const mockFlowManager = {
- getFlowState: jest.fn(),
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: Date.now(),
+ }),
completeFlow: jest.fn().mockResolvedValue(),
deleteFlow: jest.fn().mockResolvedValue(true),
};
@@ -2247,8 +2359,9 @@ describe('MCP Routes', () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
+ metadata: { state: 'opaque-state' },
}),
- failFlow: jest.fn().mockResolvedValue(),
};
getLogStores.mockReturnValue({});
@@ -2263,9 +2376,10 @@ describe('MCP Routes', () => {
message: 'OAuth flow for test-server cancelled successfully',
});
- expect(mockFlowManager.failFlow).toHaveBeenCalledWith(
+ expect(MCPOAuthHandler.failFlowAndDeleteStateMapping).toHaveBeenCalledWith(
'test-user-id:test-server',
- 'mcp_oauth',
+ expect.objectContaining({ metadata: { state: 'opaque-state' } }),
+ mockFlowManager,
'User cancelled OAuth flow',
);
});
@@ -2291,8 +2405,10 @@ describe('MCP Routes', () => {
it('should return 500 when cancellation fails', async () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING' }),
- failFlow: jest.fn().mockRejectedValue(new Error('Database error')),
};
+ MCPOAuthHandler.failFlowAndDeleteStateMapping.mockRejectedValueOnce(
+ new Error('Database error'),
+ );
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -3156,7 +3272,10 @@ describe('MCP Routes', () => {
refresh_token: 'edge-refresh-token',
};
const mockFlowManager = {
- getFlowState: jest.fn(),
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: Date.now(),
+ }),
completeFlow: jest.fn(),
};
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -3210,6 +3329,7 @@ describe('MCP Routes', () => {
MCPOAuthHandler.getFlowState.mockReset();
MCPOAuthHandler.completeOAuthFlow.mockReset();
MCPTokenStorage.storeTokens.mockReset();
+ mockRegistryInstance.getServerConfig.mockResolvedValue({});
});
it('should wrap callback body in tenantStorage.run when flowState has tenantId and no current context', async () => {
@@ -3235,6 +3355,13 @@ describe('MCP Routes', () => {
token_type: 'bearer',
});
MCPTokenStorage.storeTokens.mockResolvedValue();
+ require('~/config').getFlowStateManager.mockReturnValue({
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: Date.now(),
+ }),
+ completeFlow: jest.fn(),
+ });
const response = await request(app)
.get(`/api/mcp/test-server/oauth/callback?code=test-code&state=${flowId}`)
diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.js
index e430a4a324..7dc81c8f90 100644
--- a/api/server/routes/mcp.js
+++ b/api/server/routes/mcp.js
@@ -13,6 +13,7 @@ const {
createAuthIdentityContext,
MCPOAuthHandler,
MCPTokenStorage,
+ getMCPServerGeneration,
setOAuthSession,
PENDING_STALE_MS,
getUserMCPAuthMap,
@@ -49,7 +50,8 @@ const {
} = require('~/server/services/MCP');
const { requireJwtAuth, canAccessMCPServerResource } = require('~/server/middleware');
const { getUserPluginAuthValue } = require('~/server/services/PluginService');
-const { invalidateCachedTools } = require('~/server/services/Config');
+const { maybeUninstallOAuthMCP } = require('~/server/services/MCP/oauthCleanup');
+const { invalidateCachedTools, getAppConfig } = require('~/server/services/Config');
const { updateMCPServerTools } = require('~/server/services/Config/mcp');
const { reinitMCPServer } = require('~/server/services/Tools/mcp');
const { createOpenIDSessionTokenProvider } = require('~/server/services/OpenIDSessionRefresh');
@@ -214,7 +216,13 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, async
if (typeof oldState === 'string') {
await MCPOAuthHandler.deleteStateMapping(oldState, flowManager);
}
- const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: getTenantId() };
+ const effectiveConfig = (await resolveAllMcpConfigs(userId))?.[serverName];
+ const metadataWithUrl = {
+ ...flowMetadata,
+ authorizationUrl,
+ tenantId: getTenantId(),
+ ...(effectiveConfig && { serverGeneration: getMCPServerGeneration(effectiveConfig) }),
+ };
await flowManager.initFlow(oauthFlowId, 'mcp_oauth', metadataWithUrl);
await MCPOAuthHandler.storeStateMapping(flowMetadata.state, oauthFlowId, flowManager);
setOAuthCsrfCookie(res, oauthFlowId, OAUTH_CSRF_COOKIE_PATH);
@@ -263,9 +271,16 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
/** A stale mapping can resolve a superseded attempt's state to the
* current flow (deterministic flow ids); only fail the flow this
* error callback actually belongs to */
- const flowMeta = await MCPOAuthHandler.getFlowState(flowId, flowManager);
- if (flowMeta?.state === state) {
- await flowManager.failFlow(flowId, 'mcp_oauth', String(oauthError));
+ const currentFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');
+ const flowMeta = currentFlow?.metadata;
+ if (currentFlow && flowMeta?.state === state) {
+ await flowManager.failFlowIfCurrent(
+ flowId,
+ 'mcp_oauth',
+ currentFlow.createdAt,
+ state,
+ String(oauthError),
+ );
logger.debug('[MCP OAuth] Marked flow as FAILED with OAuth error', {
flowId,
error: oauthError,
@@ -371,7 +386,11 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
/** Check if this flow has already been completed (idempotency protection) */
const currentFlowState = await flowManager.getFlowState(flowId, 'mcp_oauth');
- if (currentFlowState?.status === 'COMPLETED') {
+ if (!currentFlowState) {
+ logger.warn('[MCP OAuth] Flow disappeared before token exchange', { flowId, serverName });
+ return res.redirect(`${basePath}/oauth/error?error=invalid_state`);
+ }
+ if (currentFlowState.status === 'COMPLETED') {
logger.warn('[MCP OAuth] Flow already completed, preventing duplicate token exchange', {
flowId,
serverName,
@@ -408,6 +427,76 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
await runWithTenant(async () => {
const oauthHeaders =
flowState.oauthHeaders ?? (await getOAuthHeaders(serverName, flowState.userId));
+ const resolveActiveServer = async () => {
+ const [configs, appConfig] = await Promise.all([
+ resolveAllMcpConfigs(flowState.userId),
+ getAppConfig({ userId: flowState.userId, tenantId: getTenantId() }),
+ ]);
+ const activeConfig =
+ configs?.[serverName] ??
+ appConfig?.mcpConfig?.[serverName] ??
+ (await getMCPServersRegistry().getServerConfig(serverName, flowState.userId));
+ if (!activeConfig) {
+ return false;
+ }
+ if (flowState.serverGeneration) {
+ return getMCPServerGeneration(activeConfig) === flowState.serverGeneration;
+ }
+ return activeConfig.url === flowState.serverUrl;
+ };
+ if (!(await resolveActiveServer())) {
+ throw new Error(`MCP server ${serverName} was deleted during OAuth authorization`);
+ }
+ const rollbackStoredTokens = async (storedTokens) => {
+ const storedMetadata = MCPOAuthHandler.buildStoredClientMetadata(
+ flowState.metadata,
+ flowState.resourceMetadata,
+ flowState.serverUrl,
+ flowState.clientSource,
+ );
+ const revocationMetadata = {
+ serverUrl: flowState.serverUrl,
+ clientId: flowState.clientInfo?.client_id ?? '',
+ clientSecret: flowState.clientInfo?.client_secret ?? '',
+ revocationEndpoint: storedMetadata?.revocation_endpoint,
+ revocationEndpointAuthMethodsSupported:
+ storedMetadata?.revocation_endpoint_auth_methods_supported,
+ };
+ for (const [tokenType, token] of [
+ ['access', storedTokens.access_token],
+ ['refresh', storedTokens.refresh_token],
+ ]) {
+ if (!token) {
+ continue;
+ }
+ try {
+ await MCPOAuthHandler.revokeOAuthToken(
+ serverName,
+ token,
+ tokenType,
+ revocationMetadata,
+ oauthHeaders,
+ flowState.allowedDomains,
+ flowState.allowedAddresses,
+ );
+ } catch (error) {
+ logger.warn(
+ `[MCP OAuth] Failed to revoke ${tokenType} token after callback cancellation:`,
+ error,
+ );
+ }
+ }
+ await MCPTokenStorage.deleteUserTokens({
+ userId: flowState.userId,
+ serverName,
+ deleteToken: async (filter) => {
+ await db.deleteTokens({
+ ...filter,
+ metadataCredentialSetId: storedTokens.credential_set_id,
+ });
+ },
+ });
+ };
const tokens = await MCPOAuthHandler.completeOAuthFlow(
flowId,
code,
@@ -437,6 +526,10 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
flowState.clientSource,
),
})) ?? exchangedTokens;
+ if (!(await resolveActiveServer())) {
+ await rollbackStoredTokens(storedTokens);
+ throw new Error(`MCP server ${serverName} was deleted during OAuth authorization`);
+ }
logger.debug('[MCP OAuth] Stored OAuth tokens before completing callback flow', {
serverName,
userId: flowState.userId,
@@ -476,6 +569,8 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
return storedTokens;
},
+ rollbackStoredTokens,
+ { createdAt: currentFlowState.createdAt, state },
);
logger.info('[MCP OAuth] OAuth flow completed, tokens received in callback route');
@@ -739,7 +834,12 @@ router.post('/oauth/cancel/:serverName', requireJwtAuth, async (req, res) => {
});
}
- await flowManager.failFlow(flowId, 'mcp_oauth', 'User cancelled OAuth flow');
+ await MCPOAuthHandler.failFlowAndDeleteStateMapping(
+ flowId,
+ flowState,
+ flowManager,
+ 'User cancelled OAuth flow',
+ );
logger.info(`[MCP OAuth Cancel] Successfully cancelled OAuth flow for ${serverName}`);
@@ -1156,7 +1256,7 @@ router.delete(
requiredPermission: PermissionBits.DELETE,
resourceIdParam: 'serverName',
}),
- deleteMCPServerController,
+ (req, res) => deleteMCPServerController(req, res, maybeUninstallOAuthMCP),
);
module.exports = router;
diff --git a/api/server/services/MCP/oauthCleanup.js b/api/server/services/MCP/oauthCleanup.js
new file mode 100644
index 0000000000..479dccfea0
--- /dev/null
+++ b/api/server/services/MCP/oauthCleanup.js
@@ -0,0 +1,27 @@
+const { CacheKeys } = require('librechat-data-provider');
+const { MCPOAuthHandler, MCPTokenStorage, cleanupMCPServerOAuth } = require('@librechat/api');
+const { getFlowStateManager, getMCPServersRegistry } = require('~/config');
+const { getLogStores } = require('~/cache');
+const db = require('~/models');
+
+const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig, serverConfigOverride) => {
+ const registry = getMCPServersRegistry();
+ return cleanupMCPServerOAuth({
+ userId,
+ pluginKey,
+ appConfig,
+ serverConfigOverride,
+ dependencies: {
+ flowManager: getFlowStateManager(getLogStores(CacheKeys.FLOWS)),
+ oauthHandler: MCPOAuthHandler,
+ tokenStorage: MCPTokenStorage,
+ findToken: db.findToken,
+ deleteTokens: db.deleteTokens,
+ getServerConfig: (serverName, ownerId) => registry.getServerConfig(serverName, ownerId),
+ isRegisteredOAuthServer: async (serverName, ownerId) =>
+ (await registry.getOAuthServers(ownerId)).has(serverName),
+ },
+ });
+};
+
+module.exports = { maybeUninstallOAuthMCP };
diff --git a/packages/api/src/flow/manager.test.ts b/packages/api/src/flow/manager.test.ts
index 2e89effbe1..74248f428a 100644
--- a/packages/api/src/flow/manager.test.ts
+++ b/packages/api/src/flow/manager.test.ts
@@ -49,6 +49,100 @@ describe('FlowStateManager', () => {
});
describe('Concurrency Tests', () => {
+ it('atomically updates the default in-memory Keyv envelope', async () => {
+ const keyv = new Keyv({
+ namespace: 'flow-atomic-test',
+ serialize: JSON.stringify,
+ deserialize: JSON.parse,
+ });
+ const manager = new FlowStateManager<string>(keyv, { ttl: 30000, ci: true });
+ await manager.initFlow('oauth-flow', 'mcp_oauth', { state: 'expected-state' });
+ const flow = await manager.getFlowState('oauth-flow', 'mcp_oauth');
+
+ await expect(
+ manager.failFlowIfCurrent(
+ 'oauth-flow',
+ 'mcp_oauth',
+ flow!.createdAt,
+ 'expected-state',
+ 'cancelled',
+ ),
+ ).resolves.toBe('updated');
+
+ expect(await manager.getFlowState('oauth-flow', 'mcp_oauth')).toMatchObject({
+ status: 'FAILED',
+ error: 'cancelled',
+ });
+ });
+
+ it('does not delete a replacement OAuth attempt', async () => {
+ await flowManager.initFlow('oauth-flow', 'mcp_oauth', { state: 'new-state' });
+
+ await expect(
+ flowManager.deleteFlowIfCurrent('oauth-flow', 'mcp_oauth', 1, 'old-state'),
+ ).resolves.toBe('stale');
+
+ expect(await flowManager.getFlowState('oauth-flow', 'mcp_oauth')).toMatchObject({
+ status: 'PENDING',
+ metadata: { state: 'new-state' },
+ });
+ });
+
+ it('does not complete a replacement OAuth attempt', async () => {
+ await flowManager.initFlow('oauth-flow', 'mcp_oauth', { state: 'new-state' });
+
+ await expect(
+ flowManager.completeFlowIfCurrent('oauth-flow', 'mcp_oauth', 1, 'old-state', 'old-result'),
+ ).resolves.toBe('stale');
+
+ expect(await flowManager.getFlowState('oauth-flow', 'mcp_oauth')).toMatchObject({
+ status: 'PENDING',
+ metadata: { state: 'new-state' },
+ });
+ });
+
+ it('does not overwrite an already completed OAuth attempt', async () => {
+ await flowManager.initFlow('oauth-flow', 'mcp_oauth', { state: 'expected-state' });
+ const flow = await flowManager.getFlowState('oauth-flow', 'mcp_oauth');
+ await flowManager.completeFlow('oauth-flow', 'mcp_oauth', 'first-result');
+
+ await expect(
+ flowManager.completeFlowIfCurrent(
+ 'oauth-flow',
+ 'mcp_oauth',
+ flow!.createdAt,
+ 'expected-state',
+ 'second-result',
+ ),
+ ).resolves.toBe('stale');
+
+ expect(await flowManager.getFlowState('oauth-flow', 'mcp_oauth')).toMatchObject({
+ status: 'COMPLETED',
+ result: 'first-result',
+ });
+ });
+
+ 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');
+
+ await expect(
+ flowManager.failFlowIfCurrent(
+ 'oauth-flow',
+ 'mcp_oauth',
+ flow!.createdAt,
+ 'expected-state',
+ 'cancelled',
+ ),
+ ).resolves.toBe('updated');
+
+ expect(await flowManager.getFlowState('oauth-flow', 'mcp_oauth')).toMatchObject({
+ status: 'FAILED',
+ error: 'cancelled',
+ metadata: { state: 'expected-state' },
+ });
+ });
+
it('should handle concurrent flow creation and return same result', async () => {
const flowId = 'test-flow';
const type = 'test-type';
diff --git a/packages/api/src/flow/manager.ts b/packages/api/src/flow/manager.ts
index ef52367ee3..7b0a26187c 100644
--- a/packages/api/src/flow/manager.ts
+++ b/packages/api/src/flow/manager.ts
@@ -5,6 +5,63 @@ import type { FlowState, FlowMetadata, FlowManagerOptions } from './types';
import { registerShutdownTask } from '../app/shutdown';
import { math } from '~/utils/math';
+type GuardedMutationResult = 'updated' | 'stale' | 'missing';
+
+interface KeyvRedisStore {
+ constructor: { name: string };
+ namespace?: string;
+ createKeyPrefix(key: string, namespace?: string): string;
+ client?: {
+ eval(script: string, options: { keys: string[]; arguments: string[] }): Promise<unknown>;
+ };
+}
+
+const GUARDED_DELETE_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
+redis.call('DEL', KEYS[1])
+return 1
+`;
+
+const GUARDED_FAIL_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
+if flow.status == 'COMPLETED' then return -1 end
+flow.status = 'FAILED'
+flow.error = ARGV[3]
+flow.failedAt = 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 GUARDED_COMPLETE_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
+if flow.status ~= 'PENDING' 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
+`;
+
/**
* Lifetime of a PENDING OAuth flow: how long the auth button stays valid and an
* in-flight flow can be reused before it is replaced. Mirrors
@@ -31,12 +88,19 @@ export class FlowStateManager<T = unknown> {
private monitorTimeout: number;
private retainedFailureTypes: Set<string>;
private intervals: Set<NodeJS.Timeout>;
+ private redisScriptExecutor?: FlowManagerOptions['redisScriptExecutor'];
constructor(store: Keyv, options?: FlowManagerOptions) {
if (!options) {
options = { ttl: 60000 * 3 };
}
- const { ci = false, ttl, monitorTimeout = ttl, retainedFailureTypes = [] } = options;
+ const {
+ ci = false,
+ ttl,
+ monitorTimeout = ttl,
+ retainedFailureTypes = [],
+ redisScriptExecutor,
+ } = options;
if (!ci && !(store instanceof Keyv)) {
throw new Error('Invalid store provided to FlowStateManager');
@@ -45,6 +109,7 @@ export class FlowStateManager<T = unknown> {
this.ttl = ttl;
this.monitorTimeout = monitorTimeout;
this.retainedFailureTypes = new Set(retainedFailureTypes);
+ this.redisScriptExecutor = redisScriptExecutor;
this.keyv = store;
this.intervals = new Set();
@@ -74,6 +139,224 @@ export class FlowStateManager<T = unknown> {
return `${type}:${flowId}`;
}
+ private getRedisKey(flowKey: string): string | null {
+ const store = this.keyv.store as KeyvRedisStore;
+ if (store?.constructor?.name !== 'KeyvRedis' || typeof store.createKeyPrefix !== 'function') {
+ return null;
+ }
+ const key = this.keyv.namespace ? `${this.keyv.namespace}:${flowKey}` : flowKey;
+ return store.createKeyPrefix(key, store.namespace);
+ }
+
+ private async evalRedisScript(script: string, key: string, args: string[]): Promise<unknown> {
+ if (this.redisScriptExecutor) {
+ return this.redisScriptExecutor(script, { keys: [key], arguments: args });
+ }
+ const store = this.keyv.store as KeyvRedisStore;
+ if (typeof store.client?.eval !== 'function') {
+ throw new Error('KeyvRedis store does not expose an atomic eval capability');
+ }
+ return store.client.eval(script, { keys: [key], arguments: args });
+ }
+
+ private static guardedResult(result: unknown): GuardedMutationResult {
+ if (result === 1) {
+ return 'updated';
+ }
+ return result === 0 ? 'missing' : 'stale';
+ }
+
+ private static isCurrentAttempt(
+ flowState: FlowState | null | undefined,
+ expectedCreatedAt: number,
+ expectedState: string,
+ ): boolean {
+ return (
+ flowState?.createdAt === expectedCreatedAt &&
+ (typeof flowState.metadata?.state === 'string' ? flowState.metadata.state : '') ===
+ expectedState
+ );
+ }
+
+ private getInMemoryEntry(flowKey: string): {
+ store: Map<string, string>;
+ key: string;
+ envelope: { value: FlowState<T>; expires?: number };
+ } | null {
+ if (!(this.keyv instanceof Keyv) || !(this.keyv.store instanceof Map)) {
+ return null;
+ }
+ const key = this.keyv.namespace ? `${this.keyv.namespace}:${flowKey}` : flowKey;
+ const raw = this.keyv.store.get(key);
+ if (typeof raw !== 'string') {
+ return null;
+ }
+ return {
+ store: this.keyv.store as Map<string, string>,
+ key,
+ envelope: JSON.parse(raw) as { value: FlowState<T>; expires?: number },
+ };
+ }
+
+ /** Deletes a flow only while it still represents the caller's observed attempt. */
+ async deleteFlowIfCurrent(
+ flowId: string,
+ type: string,
+ expectedCreatedAt: number,
+ expectedState = '',
+ ): Promise<GuardedMutationResult> {
+ const flowKey = this.getFlowKey(flowId, type);
+ const redisKey = this.getRedisKey(flowKey);
+ if (redisKey) {
+ const result = await this.evalRedisScript(GUARDED_DELETE_FLOW, redisKey, [
+ String(expectedCreatedAt),
+ expectedState,
+ ]);
+ return FlowStateManager.guardedResult(result);
+ }
+
+ const memoryEntry = this.getInMemoryEntry(flowKey);
+ if (memoryEntry) {
+ if (
+ !FlowStateManager.isCurrentAttempt(
+ memoryEntry.envelope.value,
+ expectedCreatedAt,
+ expectedState,
+ )
+ ) {
+ return 'stale';
+ }
+ return memoryEntry.store.delete(memoryEntry.key) ? 'updated' : 'missing';
+ }
+
+ const current = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;
+ if (!current) {
+ return 'missing';
+ }
+ if (!FlowStateManager.isCurrentAttempt(current, expectedCreatedAt, expectedState)) {
+ return 'stale';
+ }
+ return (await this.keyv.delete(flowKey)) ? 'updated' : 'missing';
+ }
+
+ /** Fails a flow only while it still represents the caller's observed attempt. */
+ async failFlowIfCurrent(
+ flowId: string,
+ type: string,
+ expectedCreatedAt: number,
+ expectedState: string,
+ error: Error | string,
+ ): Promise<GuardedMutationResult> {
+ const flowKey = this.getFlowKey(flowId, type);
+ const message = error instanceof Error ? error.message : error;
+ const failedAt = Date.now();
+ const redisKey = this.getRedisKey(flowKey);
+ if (redisKey) {
+ const result = await this.evalRedisScript(GUARDED_FAIL_FLOW, redisKey, [
+ String(expectedCreatedAt),
+ expectedState,
+ message,
+ String(failedAt),
+ String(this.ttl),
+ ]);
+ return FlowStateManager.guardedResult(result);
+ }
+
+ const memoryEntry = this.getInMemoryEntry(flowKey);
+ if (memoryEntry) {
+ const current = memoryEntry.envelope.value;
+ if (!FlowStateManager.isCurrentAttempt(current, expectedCreatedAt, expectedState)) {
+ return 'stale';
+ }
+ if (current.status === 'COMPLETED') {
+ return 'stale';
+ }
+ memoryEntry.envelope.value = {
+ ...current,
+ status: 'FAILED',
+ error: message,
+ failedAt,
+ };
+ memoryEntry.envelope.expires = failedAt + 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';
+ }
+ if (!FlowStateManager.isCurrentAttempt(current, expectedCreatedAt, expectedState)) {
+ return 'stale';
+ }
+ if (current.status === 'COMPLETED') {
+ return 'stale';
+ }
+ const updatedState: FlowState<T> = {
+ ...current,
+ status: 'FAILED',
+ error: message,
+ failedAt,
+ };
+ await this.keyv.set(flowKey, updatedState, this.ttl);
+ return 'updated';
+ }
+
+ /** Completes a flow only while it still represents the caller's observed attempt. */
+ async completeFlowIfCurrent(
+ 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_COMPLETE_FLOW, redisKey, [
+ String(expectedCreatedAt),
+ expectedState,
+ JSON.stringify(result) ?? 'null',
+ String(completedAt),
+ String(this.ttl),
+ ]);
+ return FlowStateManager.guardedResult(guardedResult);
+ }
+
+ const memoryEntry = this.getInMemoryEntry(flowKey);
+ if (memoryEntry) {
+ const current = memoryEntry.envelope.value;
+ if (!FlowStateManager.isCurrentAttempt(current, expectedCreatedAt, expectedState)) {
+ return 'stale';
+ }
+ if (current.status !== 'PENDING') {
+ return 'stale';
+ }
+ memoryEntry.envelope.value = { ...current, status: 'COMPLETED', result, completedAt };
+ 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';
+ }
+ if (!FlowStateManager.isCurrentAttempt(current, expectedCreatedAt, expectedState)) {
+ return 'stale';
+ }
+ if (current.status !== 'PENDING') {
+ return 'stale';
+ }
+ await this.keyv.set(
+ flowKey,
+ { ...current, status: 'COMPLETED', result, completedAt },
+ this.ttl,
+ );
+ return 'updated';
+ }
+
private isTokenExpired(flowState: FlowState<T> | undefined): boolean {
if (!flowState?.result || typeof flowState.result !== 'object') {
return false;
diff --git a/packages/api/src/flow/types.ts b/packages/api/src/flow/types.ts
index 3a4d295f67..edd9fad3b1 100644
--- a/packages/api/src/flow/types.ts
+++ b/packages/api/src/flow/types.ts
@@ -24,4 +24,8 @@ export interface FlowManagerOptions {
retainedFailureTypes?: readonly string[];
ci?: boolean;
logger?: Logger;
+ redisScriptExecutor?: (
+ script: string,
+ options: { keys: string[]; arguments: string[] },
+ ) => Promise<unknown>;
}
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index 4fed085da8..6e764f77a2 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -18,6 +18,7 @@ import type * as t from './types';
import {
MCPTokenStorage,
MCPOAuthHandler,
+ getMCPServerGeneration,
OboTokenResolutionError,
ReauthenticationRequiredError,
resolveOboToken,
@@ -55,6 +56,8 @@ type OAuthRecoveryPhase = 'silent-refresh' | 'interactive' | 'terminal';
export class MCPConnectionFactory {
protected readonly serverName: string;
protected readonly serverConfig: t.MCPOptions;
+ /** Unresolved definition used for lifecycle fencing across request-specific substitutions. */
+ protected readonly serverDefinition: t.MCPOptions;
protected readonly logPrefix: string;
protected readonly useOAuth: boolean;
protected readonly useSSRFProtection: boolean;
@@ -177,7 +180,9 @@ export class MCPConnectionFactory {
scopes: process.env.GRAPH_API_SCOPES,
});
- return serverConfig === basic.serverConfig ? basic : { ...basic, serverConfig };
+ return serverConfig === basic.serverConfig
+ ? basic
+ : { ...basic, serverConfig, serverDefinition: basic.serverDefinition ?? basic.serverConfig };
}
protected async discoverToolsInternal(): Promise<ToolDiscoveryResult> {
@@ -413,6 +418,7 @@ export class MCPConnectionFactory {
basic: t.BasicConnectionOptions,
options?: t.OAuthConnectionOptions | t.UserConnectionContext,
) {
+ this.serverDefinition = basic.serverDefinition ?? basic.serverConfig;
this.serverConfig = basic.skipEnvProcessing
? basic.serverConfig
: processMCPEnv({
@@ -1329,7 +1335,12 @@ export class MCPConnectionFactory {
}
// Store flow state BEFORE redirecting so the callback can find it
- const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: this.tenantId };
+ const metadataWithUrl = {
+ ...flowMetadata,
+ authorizationUrl,
+ tenantId: this.tenantId,
+ serverGeneration: getMCPServerGeneration(this.serverDefinition as t.ParsedServerConfig),
+ };
await this.flowManager!.initFlow(newFlowId, 'mcp_oauth', metadataWithUrl);
await MCPOAuthHandler.storeStateMapping(flowMetadata.state, newFlowId, this.flowManager!);
@@ -1732,7 +1743,12 @@ export class MCPConnectionFactory {
reusedClientCredentialSetId = flowMetadata.reusedClientCredentialSetId;
// Store flow state BEFORE redirecting so the callback can find it
- const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: this.tenantId };
+ const metadataWithUrl = {
+ ...flowMetadata,
+ authorizationUrl,
+ tenantId: this.tenantId,
+ serverGeneration: getMCPServerGeneration(this.serverDefinition as t.ParsedServerConfig),
+ };
await this.flowManager.initFlow(newFlowId, 'mcp_oauth', metadataWithUrl);
await MCPOAuthHandler.storeStateMapping(flowMetadata.state, newFlowId, this.flowManager);
diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.ts
index 5d6dd40f38..bf87869556 100644
--- a/packages/api/src/mcp/UserConnectionManager.ts
+++ b/packages/api/src/mcp/UserConnectionManager.ts
@@ -654,6 +654,9 @@ export abstract class UserConnectionManager {
});
const basic: t.BasicConnectionOptions = {
serverConfig: runtimeConfig,
+ /** Runtime OAuth detection enriches the connection config. Keep the durable definition
+ * separate so callback liveness compares against the config that actually owns it. */
+ serverDefinition: config,
serverName: serverName,
dbSourced: isUserSourced(runtimeConfig),
useSSRFProtection,
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 5183e731a3..4dfe5f26a2 100644
--- a/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
+++ b/packages/api/src/mcp/__tests__/MCPFlowRedis.cache_integration.spec.ts
@@ -76,4 +76,32 @@ describe('MCP OAuth flow state across Redis-backed instances', () => {
expect.objectContaining({ status: 'FAILED', error: 'provider rejected request' }),
);
});
+
+ it('does not delete a replacement attempt observed on another pod', async () => {
+ const flowId = createFlowId();
+ await podA.initFlow(flowId, FLOW_TYPE, { state: 'old-state' });
+ const oldFlow = await podA.getFlowState(flowId, FLOW_TYPE);
+
+ await podB.initFlow(flowId, FLOW_TYPE, { state: 'new-state' });
+
+ await expect(
+ podA.deleteFlowIfCurrent(flowId, FLOW_TYPE, oldFlow!.createdAt, 'old-state'),
+ ).resolves.toBe('stale');
+ await expect(podB.getFlowState(flowId, FLOW_TYPE)).resolves.toEqual(
+ expect.objectContaining({ status: 'PENDING', metadata: { state: 'new-state' } }),
+ );
+ });
+
+ it('fails the exact observed attempt across pods', async () => {
+ const flowId = createFlowId();
+ await podA.initFlow(flowId, FLOW_TYPE, { state: 'cancelled-state' });
+ const flow = await podB.getFlowState(flowId, FLOW_TYPE);
+
+ await expect(
+ podB.failFlowIfCurrent(flowId, FLOW_TYPE, flow!.createdAt, 'cancelled-state', 'cancelled'),
+ ).resolves.toBe('updated');
+ await expect(podA.getFlowState(flowId, FLOW_TYPE)).resolves.toEqual(
+ expect.objectContaining({ status: 'FAILED', error: 'cancelled' }),
+ );
+ });
});
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts
index e84731f25b..780c99b092 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts
@@ -826,6 +826,11 @@ describe('MCP OAuth Race Condition Fixes', () => {
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
const calls: string[] = [];
+ const guardedDeleteSpy = jest.spyOn(flowManager, 'deleteFlowIfCurrent');
+ guardedDeleteSpy.mockImplementation(async (id, type) => {
+ calls.push(`${type}:${id}`);
+ return 'updated';
+ });
const deleteFlowSpy = jest.spyOn(flowManager, 'deleteFlow');
deleteFlowSpy.mockImplementation(async (id, type) => {
calls.push(`${type}:${id}`);
@@ -869,13 +874,7 @@ describe('MCP OAuth Race Condition Fixes', () => {
await flowManager.initFlow(flowId, 'mcp_oauth', { state });
await MCPOAuthHandler.storeStateMapping(state, flowId, flowManager);
- const realDeleteFlow = flowManager.deleteFlow.bind(flowManager);
- jest.spyOn(flowManager, 'deleteFlow').mockImplementation(async (id, type) => {
- if (type === 'mcp_oauth') {
- return false;
- }
- return realDeleteFlow(id, type);
- });
+ jest.spyOn(flowManager, 'deleteFlowIfCurrent').mockResolvedValue('missing');
await expect(MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager)).rejects.toThrow(
'Failed to fully delete OAuth flow',
@@ -886,7 +885,7 @@ describe('MCP OAuth Race Condition Fixes', () => {
expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeTruthy();
});
- it('still deletes the flow and rejects when the metadata read hits a storage error', async () => {
+ it('does not blindly delete the flow when the metadata read hits a storage error', async () => {
const flowManager = createFlowManager();
const flowId = 'user1:test-server';
const state = 'unreadable-state-pqr678';
@@ -899,11 +898,10 @@ describe('MCP OAuth Race Condition Fixes', () => {
.mockRejectedValueOnce(new Error('read connection lost'));
await expect(MCPOAuthHandler.deleteFlowAndStateMapping(flowId, flowManager)).rejects.toThrow(
- 'Failed to fully delete OAuth flow',
+ 'read connection lost',
);
- /** The callback-capable flow must not survive token deletion */
- expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeFalsy();
+ expect(await flowManager.getFlowState(flowId, 'mcp_oauth')).toBeTruthy();
});
it('still deletes the flow when metadata carries no state', async () => {
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.ts
index c909437429..116d7b7edd 100644
--- a/packages/api/src/mcp/__tests__/handler.test.ts
+++ b/packages/api/src/mcp/__tests__/handler.test.ts
@@ -1724,6 +1724,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
metadata: {
serverName: 'test-server',
codeVerifier: 'test-verifier',
@@ -1731,7 +1732,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
metadata: {},
} as MCPOAuthFlowMetadata,
}),
- completeFlow: jest.fn(),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
} as unknown as FlowStateManager<MCPOAuthTokens>;
mockExchangeAuthorization.mockImplementation(async (_, options) => {
@@ -1749,9 +1750,11 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
const headers = mockFetch.mock.calls[0][1]?.headers as Headers;
expect(headers.get('foo')).toBe('bar');
expect(result.credential_set_id).toMatch(/^[a-f0-9]{32}$/);
- expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
+ expect(mockFlowManager.completeFlowIfCurrent).toHaveBeenCalledWith(
'test-flow-id',
'mcp_oauth',
+ expect.any(Number),
+ '',
expect.objectContaining({ credential_set_id: result.credential_set_id }),
);
});
@@ -1760,6 +1763,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
metadata: {
serverName: 'test-server',
codeVerifier: 'test-verifier',
@@ -1767,7 +1771,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
metadata: {},
} as MCPOAuthFlowMetadata,
}),
- completeFlow: jest.fn(),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
} as unknown as FlowStateManager<MCPOAuthTokens>;
mockExchangeAuthorization.mockResolvedValue({
access_token: 'test-token',
@@ -1789,15 +1793,96 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
expect(result.expires_at).toBe(123456);
expect(persistBeforeComplete.mock.invocationCallOrder[0]).toBeLessThan(
- (mockFlowManager.completeFlow as jest.Mock).mock.invocationCallOrder[0],
+ (mockFlowManager.completeFlowIfCurrent as jest.Mock).mock.invocationCallOrder[0],
);
- expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
+ expect(mockFlowManager.completeFlowIfCurrent).toHaveBeenCalledWith(
'test-flow-id',
'mcp_oauth',
+ expect.any(Number),
+ '',
result,
);
});
+ it('rolls back persisted tokens when teardown cancels the flow before settlement', async () => {
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: 123,
+ metadata: {
+ serverName: 'test-server',
+ serverUrl: 'https://example.com/mcp',
+ codeVerifier: 'test-verifier',
+ clientInfo: {},
+ metadata: {},
+ } as MCPOAuthFlowMetadata,
+ }),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('stale'),
+ failFlowIfCurrent: jest.fn().mockResolvedValue('stale'),
+ } as unknown as FlowStateManager<MCPOAuthTokens>;
+ mockExchangeAuthorization.mockResolvedValue({
+ access_token: 'test-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+ const persistBeforeComplete = jest.fn(async (tokens: MCPOAuthTokens) => tokens);
+ const rollbackPersistedTokens = jest.fn(async () => undefined);
+
+ await expect(
+ MCPOAuthHandler.completeOAuthFlow(
+ 'test-flow-id',
+ 'test-auth-code',
+ mockFlowManager,
+ {},
+ persistBeforeComplete,
+ rollbackPersistedTokens,
+ ),
+ ).rejects.toThrow('OAuth flow was cancelled before completion');
+
+ expect(rollbackPersistedTokens).toHaveBeenCalledWith(
+ expect.objectContaining({ access_token: 'test-token' }),
+ );
+ expect(mockFlowManager.completeFlowIfCurrent).toHaveBeenCalledWith(
+ 'test-flow-id',
+ 'mcp_oauth',
+ 123,
+ '',
+ expect.objectContaining({ access_token: 'test-token' }),
+ );
+ });
+
+ it('rejects a replaced callback attempt before exchanging its authorization code', async () => {
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: 456,
+ metadata: {
+ state: 'replacement-state',
+ serverName: 'test-server',
+ codeVerifier: 'replacement-verifier',
+ clientInfo: {},
+ metadata: {},
+ } as MCPOAuthFlowMetadata,
+ }),
+ failFlowIfCurrent: jest.fn(),
+ } as unknown as FlowStateManager<MCPOAuthTokens>;
+
+ await expect(
+ MCPOAuthHandler.completeOAuthFlow(
+ 'test-flow-id',
+ 'stale-auth-code',
+ mockFlowManager,
+ {},
+ undefined,
+ undefined,
+ { createdAt: 123, state: 'original-state' },
+ ),
+ ).rejects.toThrow('OAuth flow attempt was replaced before token exchange');
+
+ expect(mockExchangeAuthorization).not.toHaveBeenCalled();
+ expect(mockFlowManager.failFlowIfCurrent).not.toHaveBeenCalled();
+ });
+
it('passes headers to token refresh', async () => {
mockDiscoverAuthorizationServerMetadata.mockImplementation(async (_, options) => {
await options?.fetchFn?.('http://example.com/.well-known/oauth-authorization-server', {});
@@ -1848,6 +1933,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
metadata: {
serverName: 'test-server',
serverUrl: 'https://example.com/mcp',
@@ -1867,7 +1953,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
},
} as MCPOAuthFlowMetadata,
}),
- completeFlow: jest.fn(),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
} as unknown as FlowStateManager<MCPOAuthTokens>;
mockExchangeAuthorization.mockImplementation(async (_, options) => {
@@ -1917,6 +2003,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
metadata: {
serverName: 'test-server',
serverUrl: 'https://example.com/mcp',
@@ -1936,7 +2023,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
},
} as MCPOAuthFlowMetadata,
}),
- completeFlow: jest.fn(),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
} as unknown as FlowStateManager<MCPOAuthTokens>;
mockExchangeAuthorization.mockImplementation(async (_, options) => {
@@ -1966,6 +2053,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
metadata: {
serverName: 'test-server',
serverUrl: 'https://example.com/mcp',
@@ -1984,7 +2072,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
},
} as MCPOAuthFlowMetadata,
}),
- completeFlow: jest.fn(),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
} as unknown as FlowStateManager<MCPOAuthTokens>;
mockExchangeAuthorization.mockImplementation(async (_, options) => {
@@ -3046,11 +3134,12 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
// (vulnerable) code could still be in-flight at upgrade time with unvalidated
// resourceMetadata stored. completeOAuthFlow must re-assert the binding rather
// than blindly trusting stored state — and must still run the normal failure
- // bookkeeping (failFlow) so the flow manager doesn't leak a stuck PENDING entry.
+ // bookkeeping so the observed flow attempt doesn't leak a stuck PENDING entry.
const mockFailFlow = jest.fn();
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
+ createdAt: 123,
metadata: {
serverName: 'evil-server',
userId: 'user-123',
@@ -3066,7 +3155,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
},
} as MCPOAuthFlowMetadata,
}),
- failFlow: mockFailFlow,
+ failFlowIfCurrent: mockFailFlow,
} as unknown as FlowStateManager<MCPOAuthTokens>;
await expect(
@@ -3074,7 +3163,13 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
).rejects.toThrow(/does not match server URL/);
expect(mockExchangeAuthorization).not.toHaveBeenCalled();
- expect(mockFailFlow).toHaveBeenCalledWith('flow-id', expect.any(String), expect.any(Error));
+ expect(mockFailFlow).toHaveBeenCalledWith(
+ 'flow-id',
+ expect.any(String),
+ 123,
+ 'abc',
+ expect.any(Error),
+ );
});
it('falls back to origin-based discovery when the well-known endpoint returns no metadata', async () => {
diff --git a/packages/api/src/mcp/oauth/cleanup.test.ts b/packages/api/src/mcp/oauth/cleanup.test.ts
new file mode 100644
index 0000000000..53c8b08f2a
--- /dev/null
+++ b/packages/api/src/mcp/oauth/cleanup.test.ts
@@ -0,0 +1,268 @@
+import type { ParsedServerConfig } from '~/mcp/types';
+import { cleanupMCPServerOAuth, getMCPServerGeneration } from './cleanup';
+
+describe('getMCPServerGeneration', () => {
+ it('includes the durable database identity for user servers', () => {
+ const config = { type: 'streamable-http', url: 'https://example.com', dbId: 'server-1' };
+
+ expect(getMCPServerGeneration(config as ParsedServerConfig)).toMatch(/^db:server-1:/);
+ });
+
+ it('ignores inspection-only fields for config servers', () => {
+ const config = {
+ type: 'streamable-http',
+ url: 'https://example.com/mcp',
+ source: 'config',
+ initDuration: 12,
+ updatedAt: 100,
+ } as ParsedServerConfig;
+ const reinspected = { ...config, initDuration: 987, updatedAt: 200 };
+
+ expect(getMCPServerGeneration(reinspected)).toBe(getMCPServerGeneration(config));
+ });
+
+ it('changes when the stable server definition changes', () => {
+ const config = {
+ type: 'streamable-http',
+ url: 'https://example.com/mcp',
+ source: 'config',
+ } as ParsedServerConfig;
+
+ expect(getMCPServerGeneration({ ...config, url: 'https://other.example.com/mcp' })).not.toBe(
+ getMCPServerGeneration(config),
+ );
+ });
+
+ it('versions DB-backed servers when their definition changes', () => {
+ const config = {
+ type: 'streamable-http',
+ url: 'https://example.com/mcp',
+ dbId: 'server-1',
+ } as ParsedServerConfig;
+
+ expect(getMCPServerGeneration({ ...config, url: 'https://other.example.com/mcp' })).not.toBe(
+ getMCPServerGeneration(config),
+ );
+ });
+});
+
+describe('cleanupMCPServerOAuth', () => {
+ it('fails before deletion when a credential snapshot read fails', async () => {
+ const deleteTokens = jest.fn();
+
+ await expect(
+ cleanupMCPServerOAuth({
+ userId: 'user-1',
+ pluginKey: 'mcp_test-server',
+ dependencies: {
+ flowManager: { deleteFlow: jest.fn() } as never,
+ oauthHandler: {
+ generateFlowId: jest.fn(),
+ generateTokenFlowId: jest.fn(),
+ deleteFlowAndStateMapping: jest.fn(),
+ revokeOAuthToken: jest.fn(),
+ },
+ tokenStorage: {
+ deleteUserTokens: jest.fn(),
+ getClientInfoAndMetadata: jest.fn(),
+ getTokens: jest.fn(),
+ assertCredentialSetBinding: jest.fn(),
+ },
+ findToken: jest.fn().mockRejectedValue(new Error('database unavailable')),
+ deleteTokens,
+ getServerConfig: jest.fn(),
+ isRegisteredOAuthServer: jest.fn(),
+ },
+ }),
+ ).rejects.toThrow('database unavailable');
+
+ expect(deleteTokens).not.toHaveBeenCalled();
+ });
+
+ it('retries when callback persistence crosses the credential snapshot', async () => {
+ const deleteTokens = jest.fn();
+ let clientRead = 0;
+ const findToken = jest.fn(async ({ type }: { type?: string }) => {
+ const generation =
+ type === 'mcp_oauth_client' && clientRead++ === 0 ? 'old-generation' : 'new-generation';
+ return {
+ token: `encrypted-${generation}-${type}`,
+ metadata: { credential_set_id: generation },
+ } as never;
+ });
+ const deleteUserTokens = jest.fn(
+ async ({
+ userId,
+ serverName,
+ deleteToken,
+ }: {
+ userId: string;
+ serverName: string;
+ deleteToken: (filter: {
+ userId: string;
+ type: string;
+ identifier: string;
+ }) => Promise<void>;
+ }) => {
+ const identifier = `mcp:${serverName}`;
+ await Promise.all([
+ deleteToken({ userId, type: 'mcp_oauth_client', identifier: `${identifier}:client` }),
+ deleteToken({ userId, type: 'mcp_oauth', identifier }),
+ deleteToken({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ }),
+ ]);
+ },
+ );
+
+ await cleanupMCPServerOAuth({
+ userId: 'user-1',
+ pluginKey: 'mcp_test-server',
+ serverConfigOverride: { type: 'streamable-http', url: 'https://example.com/mcp' },
+ dependencies: {
+ flowManager: { deleteFlow: jest.fn() } as never,
+ oauthHandler: {
+ generateFlowId: jest.fn(() => 'user-1:test-server'),
+ generateTokenFlowId: jest.fn(() => 'user-1:test-server'),
+ deleteFlowAndStateMapping: jest.fn(),
+ revokeOAuthToken: jest.fn(),
+ },
+ tokenStorage: {
+ deleteUserTokens,
+ getClientInfoAndMetadata: jest.fn(),
+ getTokens: jest.fn(),
+ assertCredentialSetBinding: jest.fn(),
+ },
+ findToken: findToken as never,
+ deleteTokens,
+ getServerConfig: jest.fn(),
+ isRegisteredOAuthServer: jest.fn(),
+ },
+ });
+
+ expect(findToken).toHaveBeenCalledTimes(8);
+ expect(deleteTokens).toHaveBeenCalledTimes(3);
+ for (const [filter] of deleteTokens.mock.calls) {
+ expect(filter.token).toContain('new-generation');
+ }
+ });
+
+ it('deletes only token records snapshotted before flow cancellation', async () => {
+ const deleteTokens = jest.fn();
+ const findToken = jest.fn(async ({ type }: { type?: string }) =>
+ type === 'mcp_oauth' ? ({ token: 'encrypted-old-access' } as never) : null,
+ );
+ const deleteUserTokens = jest.fn(
+ async ({
+ userId,
+ serverName,
+ deleteToken,
+ }: {
+ userId: string;
+ serverName: string;
+ deleteToken: (filter: {
+ userId: string;
+ type: string;
+ identifier: string;
+ }) => Promise<void>;
+ }) => {
+ const identifier = `mcp:${serverName}`;
+ await deleteToken({
+ userId,
+ type: 'mcp_oauth_client',
+ identifier: `${identifier}:client`,
+ });
+ await deleteToken({ userId, type: 'mcp_oauth', identifier });
+ await deleteToken({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ });
+ },
+ );
+
+ await cleanupMCPServerOAuth({
+ userId: 'user-1',
+ pluginKey: 'mcp_test-server',
+ serverConfigOverride: {
+ type: 'streamable-http',
+ url: 'https://example.com/mcp',
+ oauth: {},
+ },
+ dependencies: {
+ flowManager: { deleteFlow: jest.fn() } as never,
+ oauthHandler: {
+ generateFlowId: jest.fn(() => 'user-1:test-server'),
+ generateTokenFlowId: jest.fn(() => 'user-1:test-server'),
+ deleteFlowAndStateMapping: jest.fn(),
+ revokeOAuthToken: jest.fn(),
+ },
+ tokenStorage: {
+ deleteUserTokens,
+ getClientInfoAndMetadata: jest.fn(async () => null),
+ getTokens: jest.fn(),
+ assertCredentialSetBinding: jest.fn(),
+ },
+ findToken: findToken as never,
+ deleteTokens,
+ getServerConfig: jest.fn(),
+ isRegisteredOAuthServer: jest.fn(),
+ },
+ });
+
+ expect(deleteTokens).toHaveBeenCalledTimes(1);
+ expect(deleteTokens).toHaveBeenCalledWith({
+ userId: 'user-1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:test-server',
+ token: 'encrypted-old-access',
+ });
+ });
+
+ it('does not revoke a credential generation created after the teardown snapshot', async () => {
+ const revokeOAuthToken = jest.fn();
+ const getTokens = jest.fn();
+ const deleteTokens = jest.fn();
+ const findToken = jest.fn(async ({ type }: { type?: string }) => ({
+ token: `encrypted-old-${type}`,
+ metadata: { credential_set_id: 'old-generation' },
+ })) as never;
+
+ await cleanupMCPServerOAuth({
+ userId: 'user-1',
+ pluginKey: 'mcp_test-server',
+ serverConfigOverride: {
+ type: 'streamable-http',
+ url: 'https://example.com/mcp',
+ oauth: {},
+ },
+ dependencies: {
+ flowManager: { deleteFlow: jest.fn() } as never,
+ oauthHandler: {
+ generateFlowId: jest.fn(() => 'user-1:test-server'),
+ generateTokenFlowId: jest.fn(() => 'user-1:test-server'),
+ deleteFlowAndStateMapping: jest.fn(),
+ revokeOAuthToken,
+ },
+ tokenStorage: {
+ deleteUserTokens: jest.fn(),
+ getClientInfoAndMetadata: jest.fn(async () => ({
+ clientInfo: { client_id: 'replacement-client' },
+ clientMetadata: { credential_set_id: 'replacement-generation' },
+ })),
+ getTokens,
+ assertCredentialSetBinding: jest.fn(),
+ },
+ findToken,
+ deleteTokens,
+ getServerConfig: jest.fn(),
+ isRegisteredOAuthServer: jest.fn(),
+ },
+ });
+
+ expect(getTokens).not.toHaveBeenCalled();
+ expect(revokeOAuthToken).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/mcp/oauth/cleanup.ts b/packages/api/src/mcp/oauth/cleanup.ts
new file mode 100644
index 0000000000..0bfec66f23
--- /dev/null
+++ b/packages/api/src/mcp/oauth/cleanup.ts
@@ -0,0 +1,506 @@
+import { logger, getTenantId } from '@librechat/data-schemas';
+import { Constants, PrincipalType, type MCPOptions } from 'librechat-data-provider';
+import type { TokenMethods } from '@librechat/data-schemas';
+import type { FlowStateManager } from '~/flow/manager';
+import type { ParsedServerConfig } from '~/mcp/types';
+import type { MCPOAuthTokens } from './types';
+import { getMCPAppToolsPublicationGeneration } from '~/mcp/toolsChanged';
+import { MCPOAuthHandler } from './handler';
+import { isOAuthServer } from '~/mcp/utils';
+import { MCPTokenStorage } from './tokens';
+
+export function getMCPServerGeneration(config: ParsedServerConfig): string {
+ const definitionGeneration = getMCPAppToolsPublicationGeneration(config);
+ if (config.dbId) {
+ return `db:${config.dbId}:${definitionGeneration}`;
+ }
+ return `config:${definitionGeneration}`;
+}
+
+interface CleanupConfig {
+ mcpSettings?: {
+ allowedDomains?: string[] | null;
+ allowedAddresses?: string[] | null;
+ };
+ mcpServers?: Record<string, MCPOptions>;
+}
+
+interface OAuthAclSubject {
+ principalType: string;
+ principalId?: { toString(): string } | string | null;
+}
+
+export interface MCPServerOAuthDeletionSnapshot {
+ tokenUserIds: string[];
+ aclEntries: OAuthAclSubject[];
+}
+
+interface PrepareDeletionParams {
+ getTokenUserIds: () => Promise<Array<{ toString(): string } | string>>;
+ getAclEntries: () => Promise<OAuthAclSubject[]>;
+}
+
+export async function prepareMCPServerOAuthDeletion({
+ getTokenUserIds,
+ getAclEntries,
+}: PrepareDeletionParams): Promise<MCPServerOAuthDeletionSnapshot> {
+ const [tokenUserIds, aclEntries] = await Promise.all([getTokenUserIds(), getAclEntries()]);
+ return { tokenUserIds: tokenUserIds.map(String), aclEntries };
+}
+
+interface CleanupDeletedUsersParams {
+ ownerUserId: string;
+ serverName: string;
+ serverConfig: MCPOptions;
+ snapshot: MCPServerOAuthDeletionSnapshot;
+ getTokenUserIds: () => Promise<Array<{ toString(): string } | string>>;
+ getUserPrincipals: (userId: string) => Promise<OAuthAclSubject[]>;
+ resolveAllowlists: (
+ userId: string,
+ ) => Promise<{ allowedDomains?: string[] | null; allowedAddresses?: string[] | null }>;
+ fenceAndDisconnectUser?: (userId: string) => Promise<void>;
+ uninstallOAuthMCP?: (
+ userId: string,
+ pluginKey: string,
+ appConfig: CleanupConfig,
+ serverConfig: MCPOptions,
+ ) => Promise<void>;
+}
+
+const OAUTH_CLEANUP_CONCURRENCY = 10;
+
+export async function cleanupDeletedMCPServerOAuthUsers({
+ ownerUserId,
+ serverName,
+ serverConfig,
+ snapshot,
+ getTokenUserIds,
+ getUserPrincipals,
+ resolveAllowlists,
+ fenceAndDisconnectUser,
+ uninstallOAuthMCP,
+}: CleanupDeletedUsersParams): Promise<void> {
+ const tokenUserIdsAfterDelete = (await getTokenUserIds()).map(String);
+ const candidateUserIds = [
+ ...new Set([ownerUserId, ...snapshot.tokenUserIds, ...tokenUserIdsAfterDelete]),
+ ];
+ const affectedUserIds = [ownerUserId];
+ const sharedCandidates = candidateUserIds.filter((userId) => userId !== ownerUserId);
+ const failures: unknown[] = [];
+
+ for (let offset = 0; offset < sharedCandidates.length; offset += OAUTH_CLEANUP_CONCURRENCY) {
+ const batch = sharedCandidates.slice(offset, offset + OAUTH_CLEANUP_CONCURRENCY);
+ const results = await Promise.allSettled(batch.map(getUserPrincipals));
+ for (let index = 0; index < results.length; index++) {
+ const result = results[index];
+ if (result.status === 'rejected') {
+ failures.push(result.reason);
+ logger.warn(
+ `[cleanupDeletedMCPServerOAuthUsers] Failed to resolve MCP principals for user ${batch[index]}:`,
+ result.reason,
+ );
+ continue;
+ }
+ const hadAccess = snapshot.aclEntries.some((entry) =>
+ result.value.some(
+ (principal) =>
+ principal.principalType === entry.principalType &&
+ (principal.principalType === PrincipalType.PUBLIC ||
+ principal.principalId?.toString() === entry.principalId?.toString()),
+ ),
+ );
+ if (hadAccess) {
+ affectedUserIds.push(batch[index]);
+ }
+ }
+ }
+
+ for (let offset = 0; offset < affectedUserIds.length; offset += OAUTH_CLEANUP_CONCURRENCY) {
+ const batch = affectedUserIds.slice(offset, offset + OAUTH_CLEANUP_CONCURRENCY);
+ const results = await Promise.allSettled(
+ batch.map(async (userId) => {
+ await fenceAndDisconnectUser?.(userId);
+ const { allowedDomains, allowedAddresses } = await resolveAllowlists(userId);
+ await uninstallOAuthMCP?.(
+ userId,
+ `${Constants.mcp_prefix}${serverName}`,
+ { mcpSettings: { allowedDomains, allowedAddresses } },
+ serverConfig,
+ );
+ }),
+ );
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ failures.push(result.reason);
+ logger.warn(
+ `[cleanupDeletedMCPServerOAuthUsers] OAuth cleanup failed for ${serverName}:`,
+ result.reason,
+ );
+ }
+ }
+ }
+ if (failures.length > 0) {
+ throw new Error(`OAuth cleanup failed for ${serverName} (${failures.length} operation(s))`);
+ }
+}
+
+export interface MCPOAuthCleanupDependencies {
+ flowManager: FlowStateManager<MCPOAuthTokens | null>;
+ oauthHandler: Pick<
+ typeof MCPOAuthHandler,
+ 'generateFlowId' | 'generateTokenFlowId' | 'deleteFlowAndStateMapping' | 'revokeOAuthToken'
+ >;
+ tokenStorage: Pick<
+ typeof MCPTokenStorage,
+ 'deleteUserTokens' | 'getClientInfoAndMetadata' | 'getTokens' | 'assertCredentialSetBinding'
+ >;
+ findToken: TokenMethods['findToken'];
+ deleteTokens: TokenMethods['deleteTokens'];
+ getServerConfig: (serverName: string, userId: string) => Promise<MCPOptions | undefined>;
+ isRegisteredOAuthServer: (serverName: string, userId: string) => Promise<boolean>;
+}
+
+interface ClearStateParams {
+ userId: string;
+ serverName: string;
+ dependencies: Pick<
+ MCPOAuthCleanupDependencies,
+ 'flowManager' | 'deleteTokens' | 'oauthHandler' | 'tokenStorage'
+ >;
+ skipOAuthFlows?: boolean;
+ credentialSetId?: string | null;
+ tokenSnapshot?: Map<string, string>;
+}
+
+const oauthTokenKeys = (serverName: string) => {
+ const identifier = `mcp:${serverName}`;
+ return [
+ { type: 'mcp_oauth_client', identifier: `${identifier}:client` },
+ { type: 'mcp_oauth', identifier },
+ { type: 'mcp_oauth_refresh', identifier: `${identifier}:refresh` },
+ ];
+};
+
+export async function clearStoredMCPOAuthState({
+ userId,
+ serverName,
+ dependencies,
+ skipOAuthFlows = false,
+ credentialSetId,
+ tokenSnapshot,
+}: ClearStateParams): Promise<void> {
+ try {
+ await dependencies.tokenStorage.deleteUserTokens({
+ userId,
+ serverName,
+ deleteToken: async (filter) => {
+ const snapshotToken = tokenSnapshot?.get(`${filter.type}:${filter.identifier}`);
+ if (tokenSnapshot && !snapshotToken) {
+ return;
+ }
+ await dependencies.deleteTokens({
+ ...filter,
+ ...(snapshotToken && { token: snapshotToken }),
+ ...(!tokenSnapshot &&
+ credentialSetId !== undefined && { metadataCredentialSetId: credentialSetId }),
+ });
+ },
+ });
+ } catch (error) {
+ logger.warn(
+ `[clearStoredMCPOAuthState] Failed to delete MCP OAuth tokens for ${serverName}:`,
+ error,
+ );
+ }
+
+ const tenantId = getTenantId();
+ const baseFlowId = dependencies.oauthHandler.generateFlowId(userId, serverName);
+ const flowDeletes = [
+ [dependencies.oauthHandler.generateTokenFlowId(userId, serverName, tenantId), 'mcp_get_tokens'],
+ [baseFlowId, 'mcp_get_tokens'],
+ ...(!skipOAuthFlows
+ ? ([
+ [dependencies.oauthHandler.generateFlowId(userId, serverName, tenantId), 'mcp_oauth'],
+ [baseFlowId, 'mcp_oauth'],
+ ] as Array<[string, string]>)
+ : []),
+ ] satisfies Array<[string, string]>;
+ const uniqueFlowDeletes = flowDeletes.filter(
+ ([flowId, type], index, deletes) =>
+ deletes.findIndex(
+ ([candidateId, candidateType]) => candidateId === flowId && candidateType === type,
+ ) === index,
+ );
+ const results = await Promise.allSettled(
+ uniqueFlowDeletes.map(([flowId, type]) =>
+ type === 'mcp_oauth'
+ ? dependencies.oauthHandler.deleteFlowAndStateMapping(flowId, dependencies.flowManager)
+ : dependencies.flowManager.deleteFlow(flowId, type),
+ ),
+ );
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ logger.warn(
+ `[clearStoredMCPOAuthState] Failed to clear MCP OAuth flow state for ${serverName}:`,
+ result.reason,
+ );
+ }
+ }
+}
+
+interface UninstallParams {
+ userId: string;
+ pluginKey: string;
+ appConfig?: CleanupConfig;
+ serverConfigOverride?: MCPOptions;
+ dependencies: MCPOAuthCleanupDependencies;
+}
+
+export async function cleanupMCPServerOAuth({
+ userId,
+ pluginKey,
+ appConfig,
+ serverConfigOverride,
+ dependencies,
+}: UninstallParams): Promise<void> {
+ if (!pluginKey.startsWith(Constants.mcp_prefix)) {
+ return;
+ }
+
+ const serverName = pluginKey.replace(Constants.mcp_prefix, '');
+ /** Snapshot exact encrypted values before cancelling the flow. Later cleanup can then remove
+ * this authorization without matching credentials written by a replacement attempt. */
+ const tokenKeys = oauthTokenKeys(serverName);
+ const clientTokenKey = tokenKeys[0];
+ type TokenRecord = Awaited<ReturnType<TokenMethods['findToken']>>;
+ const getCredentialSetId = (record: TokenRecord): string | undefined => {
+ if (!record) {
+ return undefined;
+ }
+ const metadata =
+ record.metadata instanceof Map
+ ? Object.fromEntries(record.metadata)
+ : (record.metadata ?? {});
+ return typeof metadata.credential_set_id === 'string' ? metadata.credential_set_id : undefined;
+ };
+ let tokenRecords = new Map<string, TokenRecord>();
+ /** The client record is the credential-set commit marker. Bookending the remaining reads with
+ * it prevents teardown from combining records on opposite sides of a concurrent callback. */
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const clientBefore = await dependencies.findToken({ userId, ...clientTokenKey });
+ const remainingRecords = await Promise.all(
+ tokenKeys
+ .slice(1)
+ .map(async (key) => [key, await dependencies.findToken({ userId, ...key })] as const),
+ );
+ const clientAfter = await dependencies.findToken({ userId, ...clientTokenKey });
+ const candidate = new Map<string, TokenRecord>([
+ [`${clientTokenKey.type}:${clientTokenKey.identifier}`, clientAfter],
+ ...remainingRecords.map(
+ ([key, record]) => [`${key.type}:${key.identifier}`, record] as const,
+ ),
+ ]);
+ const presentRecords = [...candidate.values()].filter(
+ (record): record is NonNullable<TokenRecord> => record != null,
+ );
+ const generations = presentRecords
+ .map(getCredentialSetId)
+ .filter((generation): generation is string => generation != null);
+ const clientUnchanged =
+ clientBefore?.token === clientAfter?.token &&
+ getCredentialSetId(clientBefore) === getCredentialSetId(clientAfter);
+ const generationCoherent =
+ generations.length === 0 ||
+ (generations.length === presentRecords.length && new Set(generations).size === 1);
+ if (clientUnchanged && generationCoherent) {
+ tokenRecords = candidate;
+ break;
+ }
+ }
+ if (tokenRecords.size === 0) {
+ throw new Error(`Unable to obtain a coherent OAuth credential snapshot for ${serverName}`);
+ }
+ const tokenSnapshot = new Map<string, string>();
+ const tokenGenerationSnapshot = new Map<string, string>();
+ for (const [key, record] of tokenRecords) {
+ if (!record?.token) {
+ continue;
+ }
+ tokenSnapshot.set(key, record.token);
+ const metadata =
+ record.metadata instanceof Map
+ ? Object.fromEntries(record.metadata)
+ : (record.metadata ?? {});
+ if (typeof metadata.credential_set_id === 'string') {
+ tokenGenerationSnapshot.set(key, metadata.credential_set_id);
+ }
+ }
+ const findSnapshottedToken: TokenMethods['findToken'] = async (query) => {
+ if (!query.type || !query.identifier) {
+ return null;
+ }
+ return tokenRecords.get(`${query.type}:${query.identifier}`) ?? null;
+ };
+ const serverConfig =
+ serverConfigOverride ??
+ (await dependencies.getServerConfig(serverName, userId)) ??
+ appConfig?.mcpServers?.[serverName];
+ const oauthServer = serverConfigOverride
+ ? isOAuthServer(serverConfigOverride)
+ : await dependencies.isRegisteredOAuthServer(serverName, userId);
+ let clientTokenData = null;
+ let tokens = null;
+ if (oauthServer && serverConfig) {
+ try {
+ clientTokenData = await dependencies.tokenStorage.getClientInfoAndMetadata({
+ userId,
+ serverName,
+ findToken: findSnapshottedToken,
+ });
+ const clientKey = `mcp_oauth_client:mcp:${serverName}:client`;
+ if (
+ clientTokenData?.clientMetadata.credential_set_id !== tokenGenerationSnapshot.get(clientKey)
+ ) {
+ clientTokenData = null;
+ }
+ } catch (error) {
+ logger.warn(
+ `[maybeUninstallOAuthMCP] Unable to load OAuth client metadata for ${serverName}; clearing local MCP OAuth state only.`,
+ error,
+ );
+ }
+ if (clientTokenData) {
+ try {
+ tokens = await dependencies.tokenStorage.getTokens({
+ userId,
+ serverName,
+ findToken: findSnapshottedToken,
+ });
+ if (tokens) {
+ dependencies.tokenStorage.assertCredentialSetBinding(
+ serverName,
+ tokens.credential_set_id,
+ clientTokenData.clientMetadata,
+ );
+ }
+ } catch (error) {
+ tokens = null;
+ logger.warn(
+ `[maybeUninstallOAuthMCP] Unable to load OAuth tokens for ${serverName}; clearing local token state.`,
+ error,
+ );
+ }
+ }
+ }
+ const flowIds = [
+ dependencies.oauthHandler.generateFlowId(userId, serverName, getTenantId()),
+ dependencies.oauthHandler.generateFlowId(userId, serverName),
+ ];
+ const flowResults = await Promise.allSettled(
+ [...new Set(flowIds)].map((flowId) =>
+ dependencies.oauthHandler.deleteFlowAndStateMapping(flowId, dependencies.flowManager),
+ ),
+ );
+ for (const result of flowResults) {
+ if (result.status === 'rejected') {
+ logger.warn(
+ `[clearStoredMCPOAuthState] Failed to clear MCP OAuth flow state for ${serverName}:`,
+ result.reason,
+ );
+ }
+ }
+
+ if (!oauthServer || !serverConfig) {
+ await clearStoredMCPOAuthState({
+ userId,
+ serverName,
+ dependencies,
+ skipOAuthFlows: true,
+ tokenSnapshot,
+ });
+ return;
+ }
+
+ if (!clientTokenData) {
+ await clearStoredMCPOAuthState({
+ userId,
+ serverName,
+ dependencies,
+ skipOAuthFlows: true,
+ tokenSnapshot,
+ });
+ return;
+ }
+
+ const { clientInfo, clientMetadata } = clientTokenData;
+ const credentialSetId = clientMetadata.credential_set_id;
+ const storedServerUrl = clientMetadata.server_url;
+ const storedClientSource = clientMetadata.client_source;
+ if (
+ typeof storedServerUrl !== 'string' ||
+ typeof clientMetadata.token_endpoint !== 'string' ||
+ typeof clientMetadata.revocation_endpoint !== 'string' ||
+ typeof credentialSetId !== 'string' ||
+ (storedClientSource !== 'configured' && storedClientSource !== 'dynamic')
+ ) {
+ logger.warn(
+ `[maybeUninstallOAuthMCP] Stored binding is incomplete for ${serverName}; clearing local state.`,
+ );
+ await clearStoredMCPOAuthState({
+ userId,
+ serverName,
+ dependencies,
+ skipOAuthFlows: true,
+ credentialSetId: typeof credentialSetId === 'string' ? credentialSetId : null,
+ tokenSnapshot,
+ });
+ return;
+ }
+
+ const revocationMetadata = {
+ serverUrl: storedServerUrl,
+ clientId: clientInfo.client_id,
+ clientSecret: clientInfo.client_secret ?? '',
+ revocationEndpoint: clientMetadata.revocation_endpoint,
+ revocationEndpointAuthMethodsSupported: Array.isArray(
+ clientMetadata.revocation_endpoint_auth_methods_supported,
+ )
+ ? clientMetadata.revocation_endpoint_auth_methods_supported.filter(
+ (method): method is string => typeof method === 'string',
+ )
+ : undefined,
+ };
+ const oauthHeaders = serverConfig.oauth_headers ?? {};
+ const allowedDomains = appConfig?.mcpSettings?.allowedDomains;
+ const allowedAddresses = appConfig?.mcpSettings?.allowedAddresses;
+ for (const [tokenType, token] of [
+ ['access', tokens?.access_token],
+ ['refresh', tokens?.refresh_token],
+ ] as const) {
+ if (!token) {
+ continue;
+ }
+ try {
+ await dependencies.oauthHandler.revokeOAuthToken(
+ serverName,
+ token,
+ tokenType,
+ revocationMetadata,
+ oauthHeaders,
+ allowedDomains,
+ allowedAddresses,
+ );
+ } catch (error) {
+ logger.error(`[maybeUninstallOAuthMCP] Error revoking ${tokenType} token:`, error);
+ }
+ }
+
+ await clearStoredMCPOAuthState({
+ userId,
+ serverName,
+ dependencies,
+ skipOAuthFlows: true,
+ credentialSetId,
+ tokenSnapshot,
+ });
+}
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index fa62c6024c..1035be76e3 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -25,6 +25,7 @@ import type {
OAuthMetadata,
} from './types';
import type { FlowStateManager } from '~/flow/manager';
+import type { FlowState } from '~/flow/types';
import {
resolveTokenEndpointAuthMethod,
getForcedTokenEndpointAuthMethod,
@@ -58,6 +59,7 @@ type PreconfiguredOAuthDiscoveryResult = {
};
const PRECONFIGURED_DISCOVERY_TIMEOUT_MS = 5_000;
+const OAUTH_REVOCATION_TIMEOUT_MS = 5_000;
export class MCPOAuthHandler {
private static readonly FLOW_TYPE = 'mcp_oauth';
@@ -1157,13 +1159,26 @@ export class MCPOAuthHandler {
flowManager: FlowStateManager<MCPOAuthTokens>,
oauthHeaders: Record<string, string>,
persistBeforeComplete?: (tokens: MCPOAuthTokens) => Promise<MCPOAuthTokens>,
+ rollbackPersistedTokens?: (tokens: MCPOAuthTokens) => Promise<void>,
+ expectedAttempt?: { createdAt: number; state: string },
): Promise<MCPOAuthTokens> {
+ let observedFlowState: FlowState<MCPOAuthTokens> | null = null;
try {
/** Flow state which contains our metadata */
const flowState = await flowManager.getFlowState(flowId, this.FLOW_TYPE);
if (!flowState) {
throw new Error('OAuth flow not found');
}
+ const currentState =
+ typeof flowState.metadata?.state === 'string' ? flowState.metadata.state : '';
+ if (
+ expectedAttempt &&
+ (flowState.createdAt !== expectedAttempt.createdAt ||
+ currentState !== expectedAttempt.state)
+ ) {
+ throw new Error('OAuth flow attempt was replaced before token exchange');
+ }
+ observedFlowState = flowState;
const flowMetadata = flowState.metadata as MCPOAuthFlowMetadata;
if (!flowMetadata) {
@@ -1231,12 +1246,32 @@ export class MCPOAuthHandler {
}
/** Now wake flow waiters with the persisted token snapshot. */
- await flowManager.completeFlow(flowId, this.FLOW_TYPE, mcpTokens);
+ 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');
+ }
return mcpTokens;
} catch (error) {
logger.error('[MCPOAuth] Failed to complete OAuth flow', { error, flowId });
- await flowManager.failFlow(flowId, this.FLOW_TYPE, error as Error);
+ if (observedFlowState) {
+ const observedMetadata = observedFlowState.metadata as MCPOAuthFlowMetadata | undefined;
+ await flowManager.failFlowIfCurrent(
+ flowId,
+ this.FLOW_TYPE,
+ observedFlowState.createdAt,
+ typeof observedMetadata?.state === 'string' ? observedMetadata.state : '',
+ error as Error,
+ );
+ }
throw error;
}
}
@@ -1444,40 +1479,55 @@ export class MCPOAuthHandler {
return flowManager.deleteFlow(state, this.STATE_MAP_TYPE);
}
+ /** Fails one observed OAuth attempt and makes its callback state unusable. */
+ static async failFlowAndDeleteStateMapping(
+ flowId: string,
+ flowState: FlowState<MCPOAuthTokens | null>,
+ flowManager: FlowStateManager<MCPOAuthTokens | null>,
+ error: Error | string,
+ ): Promise<void> {
+ const metadata = flowState.metadata as MCPOAuthFlowMetadata;
+ const state = typeof metadata.state === 'string' ? metadata.state : '';
+ await flowManager.failFlowIfCurrent(flowId, this.FLOW_TYPE, flowState.createdAt, state, error);
+ if (state) {
+ const mappingDeleted = await this.deleteStateMapping(state, flowManager);
+ if (!mappingDeleted) {
+ const mapping = await flowManager.getFlowState(state, this.STATE_MAP_TYPE);
+ if (mapping) {
+ throw new Error(`Failed to delete OAuth state mapping for ${flowId}`);
+ }
+ }
+ }
+ }
+
/**
* Deletes an OAuth flow together with its state mapping, for teardown paths
* that don't already hold the flow (e.g. server uninstall). The flow is
- * deleted first on purpose: it is what makes a provider callback
- * completable, and teardown runs after the server's tokens were removed, so
- * a surviving callback-capable flow could recreate credentials the user
- * just revoked. A failure between the two deletes leaves at worst an
- * orphaned mapping, which the callback's stored-state equality gates reduce
- * to a clean invalid_state. Both deletes are attempted regardless of the
- * other's outcome; any reported storage failure is surfaced as a rejection
- * for the caller's best-effort logging.
+ * guarded by the observed attempt identity so stale teardown cannot remove
+ * a concurrently created replacement. The old opaque mapping remains safe
+ * to delete because every attempt receives a distinct state value.
*/
static async deleteFlowAndStateMapping(
flowId: string,
flowManager: FlowStateManager<MCPOAuthTokens | null>,
): Promise<void> {
- /** A failed metadata read must not abort teardown: the flow is deleted
- * blindly and the unidentifiable mapping is left to the callback gates */
- let state: string | null = null;
- let metadataReadFailed = false;
- try {
- const flowState = await flowManager.getFlowState(flowId, this.FLOW_TYPE);
- const metadata = flowState?.metadata as MCPOAuthFlowMetadata | undefined;
- state = typeof metadata?.state === 'string' ? metadata.state : null;
- } catch {
- metadataReadFailed = true;
+ const flowState = await flowManager.getFlowState(flowId, this.FLOW_TYPE);
+ if (!flowState) {
+ return;
}
-
- const flowDeleted = await flowManager.deleteFlow(flowId, this.FLOW_TYPE);
+ const metadata = flowState.metadata as MCPOAuthFlowMetadata | undefined;
+ const state = typeof metadata?.state === 'string' ? metadata.state : '';
+ const flowResult = await flowManager.deleteFlowIfCurrent(
+ flowId,
+ this.FLOW_TYPE,
+ flowState.createdAt,
+ state,
+ );
const mappingDeleted = state ? await this.deleteStateMapping(state, flowManager) : true;
- if (metadataReadFailed || !flowDeleted || !mappingDeleted) {
+ if (flowResult === 'missing' || !mappingDeleted) {
throw new Error(
- `Failed to fully delete OAuth flow ${flowId} (metadata read ok: ${!metadataReadFailed}, flow deleted: ${flowDeleted}, state mapping deleted: ${mappingDeleted})`,
+ `Failed to fully delete OAuth flow ${flowId} (flow result: ${flowResult}, state mapping deleted: ${mappingDeleted})`,
);
}
}
@@ -2049,6 +2099,7 @@ export class MCPOAuthHandler {
method: 'POST',
body: body.toString(),
headers,
+ signal: AbortSignal.timeout(OAUTH_REVOCATION_TIMEOUT_MS),
});
if (!response.ok) {
diff --git a/packages/api/src/mcp/oauth/index.ts b/packages/api/src/mcp/oauth/index.ts
index eb3d65397f..2015020ecb 100644
--- a/packages/api/src/mcp/oauth/index.ts
+++ b/packages/api/src/mcp/oauth/index.ts
@@ -7,3 +7,4 @@ export * from './obo';
export * from './pending';
export * from './events';
export * from './resume';
+export * from './cleanup';
diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.ts
index e79660a98e..eed6d685bb 100644
--- a/packages/api/src/mcp/oauth/types.ts
+++ b/packages/api/src/mcp/oauth/types.ts
@@ -97,6 +97,8 @@ export interface MCPOAuthFlowMetadata extends FlowMetadata {
serverName: string;
userId: string;
serverUrl: string;
+ /** Identity of the effective server definition that admitted this authorization attempt. */
+ serverGeneration?: string;
state: string;
codeVerifier?: string;
clientInfo?: OAuthClientInformation;
diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.ts
index 6aa6bdf513..603dd24319 100644
--- a/packages/api/src/mcp/types/index.ts
+++ b/packages/api/src/mcp/types/index.ts
@@ -219,6 +219,8 @@ export type AddServerResult = {
export interface BasicConnectionOptions {
serverName: string;
serverConfig: MCPOptions;
+ /** Original unresolved definition retained across asynchronous credential preprocessing. */
+ serverDefinition?: MCPOptions;
useSSRFProtection?: boolean;
allowedDomains?: string[] | null;
/** Admin exemption list of host:port pairs that bypass the SSRF private-IP block */