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: Bind MCP OAuth Secrets to Trusted Endpoints (#14578)

Danny Aviladb6ba5392a30
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js
index 6086a5b871..d341b182ee 100644
--- a/api/server/controllers/UserController.js
+++ b/api/server/controllers/UserController.js
@@ -520,6 +520,21 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
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;
@@ -529,7 +544,15 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
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,
@@ -537,10 +560,8 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
}
// 3. revoke OAuth tokens at the provider
- const revocationEndpoint =
- serverConfig.oauth?.revocation_endpoint ?? clientMetadata.revocation_endpoint;
+ const revocationEndpoint = clientMetadata.revocation_endpoint;
const revocationEndpointAuthMethodsSupported =
- serverConfig.oauth?.revocation_endpoint_auth_methods_supported ??
clientMetadata.revocation_endpoint_auth_methods_supported;
const oauthHeaders = serverConfig.oauth_headers ?? {};
// Use the request's merged (tenant/principal-scoped) allowlists so admin-panel mcpSettings
@@ -555,7 +576,7 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
tokens.access_token,
'access',
{
- serverUrl: serverConfig.url,
+ serverUrl: storedServerUrl,
clientId: clientInfo.client_id,
clientSecret: clientInfo.client_secret ?? '',
revocationEndpoint,
@@ -580,7 +601,7 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
tokens.refresh_token,
'refresh',
{
- serverUrl: serverConfig.url,
+ serverUrl: storedServerUrl,
clientId: clientInfo.client_id,
clientSecret: clientInfo.client_secret ?? '',
revocationEndpoint,
diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
index e955369a2b..3fb7196266 100644
--- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
+++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
@@ -37,6 +37,7 @@ jest.mock('@librechat/api', () => ({
MCPTokenStorage: {
getClientInfoAndMetadata: jest.fn(),
getTokens: jest.fn(),
+ assertCredentialSetBinding: jest.fn(),
deleteUserTokens: jest.fn().mockResolvedValue(undefined),
},
normalizeHttpError: jest.fn((error) => error),
@@ -158,6 +159,15 @@ function setupMCPMocks() {
return { flowManager, mcpManager, registry };
}
+const credentialSetId = 'credential-set-a';
+const storedOAuthBinding = {
+ server_url: 'https://example.com/mcp',
+ token_endpoint: 'https://example.com/token',
+ revocation_endpoint: 'https://example.com/revoke',
+ client_source: 'dynamic',
+ credential_set_id: credentialSetId,
+};
+
beforeEach(() => {
jest.clearAllMocks();
getTenantId.mockReturnValue(undefined);
@@ -337,7 +347,7 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
const { flowManager } = setupMCPMocks();
MCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
clientInfo: { client_id: 'client-1' },
- clientMetadata: {},
+ clientMetadata: storedOAuthBinding,
});
MCPTokenStorage.getTokens.mockRejectedValue(new Error('token lookup failed'));
@@ -371,11 +381,15 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
setupMCPMocks();
MCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
clientInfo: { client_id: 'client-1', client_secret: 'secret-1' },
- clientMetadata: { revocation_endpoint: 'https://example.com/revoke' },
+ clientMetadata: {
+ ...storedOAuthBinding,
+ revocation_endpoint: 'https://example.com/revoke',
+ },
});
MCPTokenStorage.getTokens.mockResolvedValue({
access_token: 'access-token',
refresh_token: 'refresh-token',
+ credential_set_id: credentialSetId,
});
MCPOAuthHandler.revokeOAuthToken.mockResolvedValue();
@@ -388,6 +402,11 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
serverName: 'test-server',
findToken: mockFindToken,
});
+ expect(MCPTokenStorage.assertCredentialSetBinding).toHaveBeenCalledWith(
+ 'test-server',
+ credentialSetId,
+ expect.objectContaining({ credential_set_id: credentialSetId }),
+ );
expect(MCPOAuthHandler.revokeOAuthToken).toHaveBeenCalledWith(
'test-server',
'access-token',
@@ -429,10 +448,11 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
setupMCPMocks();
MCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
clientInfo: { client_id: 'client-1', client_secret: 'secret-1' },
- clientMetadata: {},
+ clientMetadata: storedOAuthBinding,
});
MCPTokenStorage.getTokens.mockResolvedValue({
access_token: 'access-token',
+ credential_set_id: credentialSetId,
});
MCPOAuthHandler.revokeOAuthToken.mockResolvedValue();
@@ -461,10 +481,11 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {
setupMCPMocks();
MCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
clientInfo: { client_id: 'client-1', client_secret: 'secret-1' },
- clientMetadata: {},
+ clientMetadata: storedOAuthBinding,
});
MCPTokenStorage.getTokens.mockResolvedValue({
refresh_token: 'refresh-token',
+ credential_set_id: credentialSetId,
});
MCPOAuthHandler.revokeOAuthToken.mockResolvedValue();
diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
index d09c792f22..fb46382ff6 100644
--- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
+++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
@@ -1,6 +1,11 @@
const mockGetTokens = jest.fn();
const mockDeleteUserTokens = jest.fn();
const mockGetClientInfoAndMetadata = jest.fn();
+const mockAssertCredentialSetBinding = jest.fn((serverName, tokenCredentialSetId, metadata) => {
+ if (!tokenCredentialSetId || tokenCredentialSetId !== metadata?.credential_set_id) {
+ throw new Error(`credential set mismatch for ${serverName}`);
+ }
+});
const mockRevokeOAuthToken = jest.fn();
const mockGetServerConfig = jest.fn();
const mockGetOAuthServers = jest.fn();
@@ -39,6 +44,7 @@ jest.mock('@librechat/api', () => {
MCPTokenStorage: {
getTokens: (...args) => mockGetTokens(...args),
getClientInfoAndMetadata: (...args) => mockGetClientInfoAndMetadata(...args),
+ assertCredentialSetBinding: (...args) => mockAssertCredentialSetBinding(...args),
deleteUserTokens: (...args) => mockDeleteUserTokens(...args),
},
normalizeHttpError: jest.fn(),
@@ -149,7 +155,15 @@ const appConfig = {
};
const clientInfo = { client_id: 'cid', client_secret: 'csec' };
-const clientMetadata = {};
+const credentialSetId = 'credential-set-a';
+const clientMetadata = {
+ credential_set_id: credentialSetId,
+ server_url: 'https://acme.example.com',
+ token_endpoint: 'https://acme.example.com/token',
+ client_source: 'dynamic',
+ revocation_endpoint: 'https://acme.example.com/revoke',
+ revocation_endpoint_auth_methods_supported: ['client_secret_basic'],
+};
function setupOAuthServerFound() {
mockGetServerConfig.mockResolvedValue(serverConfig);
@@ -162,6 +176,13 @@ function setupOAuthServerFound() {
describe('maybeUninstallOAuthMCP', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockAssertCredentialSetBinding.mockImplementation(
+ (currentServerName, tokenCredentialSetId, metadata) => {
+ if (!tokenCredentialSetId || tokenCredentialSetId !== metadata?.credential_set_id) {
+ throw new Error(`credential set mismatch for ${currentServerName}`);
+ }
+ },
+ );
mockGetTenantId.mockReturnValue(undefined);
});
@@ -244,6 +265,7 @@ describe('maybeUninstallOAuthMCP', () => {
mockGetTokens.mockResolvedValue({
access_token: 'access-abc',
refresh_token: 'refresh-xyz',
+ credential_set_id: credentialSetId,
});
mockRevokeOAuthToken.mockResolvedValue(undefined);
mockDeleteUserTokens.mockResolvedValue(undefined);
@@ -266,6 +288,80 @@ describe('maybeUninstallOAuthMCP', () => {
expect(mockDeleteFlowAndStateMapping).toHaveBeenCalledWith('user-123:acme', expect.anything());
});
+ test('does not revoke tokens from a concurrently replaced credential generation', async () => {
+ setupOAuthServerFound();
+ mockGetTokens.mockResolvedValue({
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ credential_set_id: 'credential-set-b',
+ });
+
+ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);
+
+ expect(mockAssertCredentialSetBinding).toHaveBeenCalledWith(
+ serverName,
+ 'credential-set-b',
+ expect.objectContaining({ credential_set_id: credentialSetId }),
+ );
+ expect(mockRevokeOAuthToken).not.toHaveBeenCalled();
+ expect(mockDeleteUserTokens).toHaveBeenCalledTimes(1);
+ expect(mockLoggerWarn).toHaveBeenCalledWith(
+ `[maybeUninstallOAuthMCP] Unable to load OAuth tokens for ${serverName}; clearing local token state.`,
+ expect.any(Error),
+ );
+ });
+
+ test('uses the stored revocation binding instead of an edited server configuration', async () => {
+ setupOAuthServerFound();
+ mockGetServerConfig.mockResolvedValue({
+ ...serverConfig,
+ url: 'https://attacker.example.com/mcp',
+ oauth: {
+ revocation_endpoint: 'https://attacker.example.com/revoke',
+ revocation_endpoint_auth_methods_supported: ['client_secret_post'],
+ },
+ });
+ mockGetTokens.mockResolvedValue({
+ access_token: 'access-abc',
+ credential_set_id: credentialSetId,
+ });
+ mockRevokeOAuthToken.mockResolvedValue(undefined);
+
+ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);
+
+ expect(mockRevokeOAuthToken).toHaveBeenCalledWith(
+ serverName,
+ 'access-abc',
+ 'access',
+ expect.objectContaining({
+ serverUrl: 'https://acme.example.com',
+ revocationEndpoint: 'https://acme.example.com/revoke',
+ revocationEndpointAuthMethodsSupported: ['client_secret_basic'],
+ }),
+ { 'X-Tenant': 'acme' },
+ undefined,
+ undefined,
+ );
+ });
+
+ test('skips remote revocation for legacy metadata without a stored revocation endpoint', async () => {
+ setupOAuthServerFound();
+ mockGetClientInfoAndMetadata.mockResolvedValue({
+ clientInfo,
+ clientMetadata: {
+ server_url: 'https://acme.example.com',
+ token_endpoint: 'https://acme.example.com/token',
+ client_source: 'dynamic',
+ },
+ });
+
+ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);
+
+ expect(mockGetTokens).not.toHaveBeenCalled();
+ expect(mockRevokeOAuthToken).not.toHaveBeenCalled();
+ expect(mockDeleteUserTokens).toHaveBeenCalledTimes(1);
+ });
+
test('skips revocation but still runs cleanup when token retrieval fails', async () => {
setupOAuthServerFound();
mockGetTokens.mockRejectedValue(new Error('missing'));
@@ -304,7 +400,10 @@ describe('maybeUninstallOAuthMCP', () => {
test('continues cleanup when only one token type is present', async () => {
setupOAuthServerFound();
- mockGetTokens.mockResolvedValue({ access_token: 'only-access' });
+ mockGetTokens.mockResolvedValue({
+ access_token: 'only-access',
+ credential_set_id: credentialSetId,
+ });
mockRevokeOAuthToken.mockResolvedValue(undefined);
mockDeleteUserTokens.mockResolvedValue(undefined);
mockDeleteFlow.mockResolvedValue(undefined);
@@ -323,6 +422,7 @@ describe('maybeUninstallOAuthMCP', () => {
mockGetTokens.mockResolvedValue({
access_token: 'a',
refresh_token: 'r',
+ credential_set_id: credentialSetId,
});
mockRevokeOAuthToken.mockRejectedValue(new Error('network down'));
mockDeleteUserTokens.mockResolvedValue(undefined);
diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.js
index fcd18805cb..923dbf013a 100644
--- a/api/server/controllers/mcp.js
+++ b/api/server/controllers/mcp.js
@@ -17,6 +17,7 @@ const {
redactAllServerSecrets,
isMCPDomainNotAllowedError,
isMCPInspectionFailedError,
+ isMCPOAuthSecretReentryRequiredError,
} = require('@librechat/api');
const {
Constants,
@@ -59,6 +60,13 @@ function handleMCPError(error, res) {
});
}
+ if (isMCPOAuthSecretReentryRequiredError(error)) {
+ return res.status(error.statusCode).json({
+ error: error.code,
+ message: error.message,
+ });
+ }
+
// Fallback for legacy string-based error handling (backwards compatibility)
if (error.message?.startsWith(MCPErrorCodes.DOMAIN_NOT_ALLOWED)) {
return res.status(403).json({
@@ -74,6 +82,13 @@ function handleMCPError(error, res) {
});
}
+ if (error.message?.startsWith(MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED)) {
+ return res.status(400).json({
+ error: MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED,
+ message: error.message,
+ });
+ }
+
return null;
}
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js
index afe275b671..634a1878c6 100644
--- a/api/server/routes/__tests__/mcp.spec.js
+++ b/api/server/routes/__tests__/mcp.spec.js
@@ -77,9 +77,12 @@ jest.mock('@librechat/api', () => {
// Error handling utilities (from @librechat/api mcp/errors)
isMCPDomainNotAllowedError: (error) => error?.code === 'MCP_DOMAIN_NOT_ALLOWED',
isMCPInspectionFailedError: (error) => error?.code === 'MCP_INSPECTION_FAILED',
+ isMCPOAuthSecretReentryRequiredError: (error) =>
+ error?.code === 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
MCPErrorCodes: {
DOMAIN_NOT_ALLOWED: 'MCP_DOMAIN_NOT_ALLOWED',
INSPECTION_FAILED: 'MCP_INSPECTION_FAILED',
+ OAUTH_SECRET_REENTRY_REQUIRED: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
},
};
});
@@ -165,6 +168,17 @@ jest.mock('~/server/services/Tools/mcp', () => ({
reinitMCPServer: jest.fn(),
}));
+const mockOAuthCompletion = (tokens) => {
+ const { MCPOAuthHandler } = require('@librechat/api');
+ MCPOAuthHandler.completeOAuthFlow.mockImplementation(
+ async (flowId, _code, flowManager, _headers, persistBeforeComplete) => {
+ const storedTokens = await persistBeforeComplete(tokens);
+ await flowManager.completeFlow(flowId, 'mcp_oauth', storedTokens);
+ return storedTokens;
+ },
+ );
+};
+
describe('MCP Routes', () => {
let app;
let mongoServer;
@@ -820,7 +834,7 @@ describe('MCP Routes', () => {
clientInfo: {},
codeVerifier: 'current-verifier',
});
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({ access_token: 'test-token' });
+ mockOAuthCompletion({ access_token: 'test-token' });
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
@@ -880,7 +894,7 @@ describe('MCP Routes', () => {
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({
+ mockOAuthCompletion({
access_token: 'test-token',
});
MCPTokenStorage.storeTokens.mockResolvedValue();
@@ -934,7 +948,7 @@ describe('MCP Routes', () => {
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({
+ mockOAuthCompletion({
access_token: 'test-token',
});
MCPTokenStorage.storeTokens.mockResolvedValue();
@@ -1001,7 +1015,7 @@ describe('MCP Routes', () => {
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({
+ mockOAuthCompletion({
access_token: 'test-token',
});
MCPTokenStorage.storeTokens.mockResolvedValue();
@@ -1066,7 +1080,7 @@ describe('MCP Routes', () => {
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({
+ mockOAuthCompletion({
access_token: 'test-token',
});
MCPTokenStorage.storeTokens.mockResolvedValue();
@@ -1185,7 +1199,7 @@ describe('MCP Routes', () => {
};
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
@@ -1232,6 +1246,7 @@ describe('MCP Routes', () => {
'test-auth-code',
mockFlowManager,
{},
+ expect.any(Function),
);
expect(MCPTokenStorage.storeTokens).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1243,7 +1258,9 @@ describe('MCP Routes', () => {
}),
);
const storeInvocation = MCPTokenStorage.storeTokens.mock.invocationCallOrder[0];
+ const flowCompletionInvocation = mockFlowManager.completeFlow.mock.invocationCallOrder[0];
const connectInvocation = mockMcpManager.getUserConnection.mock.invocationCallOrder[0];
+ expect(storeInvocation).toBeLessThan(flowCompletionInvocation);
expect(storeInvocation).toBeLessThan(connectInvocation);
expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
'tool-flow-123',
@@ -1281,7 +1298,7 @@ describe('MCP Routes', () => {
};
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -1350,10 +1367,14 @@ describe('MCP Routes', () => {
access_token: 'fresh-access-token',
refresh_token: 'fresh-refresh-token',
};
+ const storedTokens = {
+ ...mockTokens,
+ credential_set_id: 'persisted-generation',
+ };
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
- MCPTokenStorage.storeTokens.mockResolvedValue();
+ mockOAuthCompletion(mockTokens);
+ MCPTokenStorage.storeTokens.mockResolvedValue(storedTokens);
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
require('~/config').getOAuthReconnectionManager.mockReturnValue({
@@ -1383,7 +1404,7 @@ describe('MCP Routes', () => {
expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
'tenant:tenant-a:test-user-id:test-server',
'mcp_get_tokens',
- mockTokens,
+ storedTokens,
);
expect(mockFlowManager.deleteFlow).not.toHaveBeenCalledWith(
'tenant:tenant-a:test-user-id:test-server',
@@ -1410,7 +1431,7 @@ describe('MCP Routes', () => {
const mockTokens = { access_token: 'tok', refresh_token: 'ref' };
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
@@ -1439,6 +1460,7 @@ describe('MCP Routes', () => {
'auth-code',
mockFlowManager,
{ 'X-Custom-Auth': 'header-value' },
+ expect.any(Function),
);
expect(mockRegistryInstance.getServerConfig).not.toHaveBeenCalled();
});
@@ -1460,7 +1482,7 @@ describe('MCP Routes', () => {
const mockTokens = { access_token: 'tok', refresh_token: 'ref' };
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({
oauth_headers: { 'X-Registry-Header': 'from-registry' },
@@ -1492,6 +1514,7 @@ describe('MCP Routes', () => {
'auth-code',
mockFlowManager,
{ 'X-Registry-Header': 'from-registry' },
+ expect.any(Function),
);
expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
'test-server',
@@ -1539,7 +1562,7 @@ describe('MCP Routes', () => {
};
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
@@ -1583,7 +1606,7 @@ describe('MCP Routes', () => {
};
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
@@ -1636,7 +1659,7 @@ describe('MCP Routes', () => {
};
MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockRejectedValue(new Error('store failed'));
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
@@ -1661,6 +1684,7 @@ describe('MCP Routes', () => {
expect(response.status).toBe(302);
expect(response.headers.location).toBe(`${basePath}/oauth/error?error=callback_failed`);
+ expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();
expect(mockMcpManager.getUserConnection).not.toHaveBeenCalled();
});
@@ -1696,7 +1720,7 @@ describe('MCP Routes', () => {
.mockResolvedValueOnce(flowState);
MCPOAuthHandler.getFlowState.mockResolvedValue(flowState);
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
getLogStores.mockReturnValue({});
@@ -2627,7 +2651,8 @@ describe('MCP Routes', () => {
clientInfo: {},
codeVerifier: 'test-verifier',
});
- MCPOAuthHandler.completeOAuthFlow = jest.fn().mockResolvedValue(mockTokens);
+ MCPOAuthHandler.completeOAuthFlow = jest.fn();
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
@@ -2655,7 +2680,7 @@ describe('MCP Routes', () => {
const basePath = getBasePath();
- expect(mockFlowManager.completeFlow).not.toHaveBeenCalled();
+ expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(flowId, 'mcp_oauth', mockTokens);
expect(response.headers.location).toContain(`${basePath}/oauth/success`);
});
@@ -2687,7 +2712,7 @@ describe('MCP Routes', () => {
clientInfo: {},
codeVerifier: 'test-verifier',
});
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);
+ mockOAuthCompletion(mockTokens);
MCPTokenStorage.storeTokens.mockResolvedValue();
mockRegistryInstance.getServerConfig.mockResolvedValue({});
@@ -2745,7 +2770,7 @@ describe('MCP Routes', () => {
clientInfo: {},
codeVerifier: 'test-verifier',
});
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({
+ mockOAuthCompletion({
access_token: 'token',
token_type: 'bearer',
});
@@ -2782,7 +2807,7 @@ describe('MCP Routes', () => {
clientInfo: {},
codeVerifier: 'test-verifier',
});
- MCPOAuthHandler.completeOAuthFlow.mockResolvedValue({
+ mockOAuthCompletion({
access_token: 'token',
token_type: 'bearer',
});
@@ -3560,6 +3585,40 @@ describe('MCP Routes', () => {
expect(response.body.env).toBeUndefined();
});
+ it('should require secret re-entry when OAuth credential bindings change', async () => {
+ const error = Object.assign(
+ new Error(
+ 'Re-enter oauth.client_secret when changing OAuth credential binding fields: oauth.token_url',
+ ),
+ {
+ code: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
+ statusCode: 400,
+ },
+ );
+ mockRegistryInstance.updateServer.mockRejectedValue(error);
+
+ const response = await request(app)
+ .patch('/api/mcp/servers/test-server')
+ .send({
+ config: {
+ type: 'sse',
+ url: 'https://mcp-server.example.com/sse',
+ oauth: {
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://attacker.example.com/token',
+ client_id: 'client-id',
+ },
+ },
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.body).toEqual({
+ error: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
+ message:
+ 'Re-enter oauth.client_secret when changing OAuth credential binding fields: oauth.token_url',
+ });
+ });
+
it('should return 400 for invalid configuration', async () => {
const invalidConfig = {
type: 'sse',
diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.js
index 71a905fe10..c044a67372 100644
--- a/api/server/routes/mcp.js
+++ b/api/server/routes/mcp.js
@@ -403,62 +403,71 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
code,
flowManager,
oauthHeaders,
- );
- logger.info('[MCP OAuth] OAuth flow completed, tokens received in callback route');
-
- /** Persist tokens immediately so reconnection uses fresh credentials */
- if (flowState?.userId && tokens) {
- try {
- await MCPTokenStorage.storeTokens({
- userId: flowState.userId,
- serverName,
- tokens,
- createToken: db.createToken,
- updateToken: db.updateToken,
- findToken: db.findToken,
- clientInfo: flowState.clientInfo,
- metadata: MCPOAuthHandler.buildStoredClientMetadata(
- flowState.metadata,
- flowState.resourceMetadata,
- ),
- });
- logger.debug('[MCP OAuth] Stored OAuth tokens prior to reconnection', {
- serverName,
- userId: flowState.userId,
- });
- } catch (error) {
- logger.error('[MCP OAuth] Failed to store OAuth tokens after callback', error);
- throw error;
- }
+ async (exchangedTokens) => {
+ if (!flowState?.userId) {
+ return exchangedTokens;
+ }
- /**
- * Clear any cached `mcp_get_tokens` flow result so subsequent lookups
- * re-fetch the freshly stored credentials instead of returning stale nulls.
- */
- if (typeof flowManager?.deleteFlow === 'function') {
+ let storedTokens;
try {
- const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(
- flowState.userId,
+ storedTokens =
+ (await MCPTokenStorage.storeTokens({
+ userId: flowState.userId,
+ serverName,
+ tokens: exchangedTokens,
+ createToken: db.createToken,
+ updateToken: db.updateToken,
+ deleteTokens: db.deleteTokens,
+ findToken: db.findToken,
+ clientInfo: flowState.clientInfo,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ flowState.metadata,
+ flowState.resourceMetadata,
+ flowState.serverUrl,
+ flowState.clientSource,
+ ),
+ })) ?? exchangedTokens;
+ logger.debug('[MCP OAuth] Stored OAuth tokens before completing callback flow', {
serverName,
- flowState.tenantId,
- );
- await clearGetTokensFlow({
- flowManager,
- flowId: tokenFlowId,
- tokens,
+ userId: flowState.userId,
});
- if (tokenFlowId !== flowId) {
+ } catch (error) {
+ logger.error('[MCP OAuth] Failed to store OAuth tokens before flow completion', error);
+ throw error;
+ }
+
+ /**
+ * Clear any cached `mcp_get_tokens` flow result before the OAuth flow wakes its
+ * waiters, so they cannot observe stale credentials after completion.
+ */
+ if (typeof flowManager?.deleteFlow === 'function') {
+ try {
+ const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(
+ flowState.userId,
+ serverName,
+ flowState.tenantId,
+ );
await clearGetTokensFlow({
flowManager,
- flowId,
- tokens,
+ flowId: tokenFlowId,
+ tokens: storedTokens,
});
+ if (tokenFlowId !== flowId) {
+ await clearGetTokensFlow({
+ flowManager,
+ flowId,
+ tokens: storedTokens,
+ });
+ }
+ } catch (error) {
+ logger.warn('[MCP OAuth] Failed to clear cached token flow state', error);
}
- } catch (error) {
- logger.warn('[MCP OAuth] Failed to clear cached token flow state', error);
}
- }
- }
+
+ return storedTokens;
+ },
+ );
+ logger.info('[MCP OAuth] OAuth flow completed, tokens received in callback route');
try {
const mcpManager = getMCPManager(flowState.userId);
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/hooks/useMCPServerForm.ts b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/hooks/useMCPServerForm.ts
index b677ed8bfc..78034b59f3 100644
--- a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/hooks/useMCPServerForm.ts
+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/hooks/useMCPServerForm.ts
@@ -9,6 +9,7 @@ import {
useDeleteMCPServerMutation,
} from '~/data-provider/MCP';
import { extractServerNameFromUrl, isValidUrl, normalizeUrl } from '../utils/urlUtils';
+import { getMCPServerErrorMessage } from '../utils/error';
import { getOAuthConfig } from '../utils/oauth';
import { useLocalize } from '~/hooks';
@@ -238,12 +239,9 @@ export function useMCPServerForm({ server, onSuccess, onClose }: UseMCPServerFor
if (error && typeof error === 'object' && 'response' in error) {
const axiosError = error as { response?: { data?: { error?: string } } };
- if (axiosError.response?.data?.error === 'MCP_INSPECTION_FAILED') {
- errorMessage = localize('com_ui_mcp_server_connection_failed');
- } else if (axiosError.response?.data?.error === 'MCP_DOMAIN_NOT_ALLOWED') {
- errorMessage = localize('com_ui_mcp_domain_not_allowed');
- } else if (axiosError.response?.data?.error) {
- errorMessage = axiosError.response.data.error;
+ const errorCode = axiosError.response?.data?.error;
+ if (errorCode) {
+ errorMessage = getMCPServerErrorMessage(errorCode, localize);
}
} else if (error instanceof Error) {
errorMessage = error.message;
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts
new file mode 100644
index 0000000000..6eb70924cd
--- /dev/null
+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts
@@ -0,0 +1,19 @@
+import type { TranslationKeys } from '~/hooks';
+
+import { getMCPServerErrorMessage } from './error';
+
+const localize = (key: TranslationKeys): string => `localized:${key}`;
+
+describe('getMCPServerErrorMessage', () => {
+ it.each([
+ ['MCP_INSPECTION_FAILED', 'com_ui_mcp_server_connection_failed'],
+ ['MCP_DOMAIN_NOT_ALLOWED', 'com_ui_mcp_domain_not_allowed'],
+ ['MCP_OAUTH_SECRET_REENTRY_REQUIRED', 'com_ui_mcp_oauth_secret_reentry_required'],
+ ] as const)('localizes %s', (errorCode, messageKey) => {
+ expect(getMCPServerErrorMessage(errorCode, localize)).toBe(`localized:${messageKey}`);
+ });
+
+ it('returns an unknown server error unchanged', () => {
+ expect(getMCPServerErrorMessage('UNKNOWN_ERROR', localize)).toBe('UNKNOWN_ERROR');
+ });
+});
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts
new file mode 100644
index 0000000000..6eadc6374e
--- /dev/null
+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts
@@ -0,0 +1,14 @@
+import type { TranslationKeys } from '~/hooks';
+
+type Localize = (key: TranslationKeys) => string;
+
+const MCP_ERROR_MESSAGE_KEYS: Record<string, TranslationKeys> = {
+ MCP_INSPECTION_FAILED: 'com_ui_mcp_server_connection_failed',
+ MCP_DOMAIN_NOT_ALLOWED: 'com_ui_mcp_domain_not_allowed',
+ MCP_OAUTH_SECRET_REENTRY_REQUIRED: 'com_ui_mcp_oauth_secret_reentry_required',
+};
+
+export function getMCPServerErrorMessage(errorCode: string, localize: Localize): string {
+ const messageKey = MCP_ERROR_MESSAGE_KEYS[errorCode];
+ return messageKey ? localize(messageKey) : errorCode;
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 80ad8ea141..fdf9e6e464 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1366,6 +1366,7 @@
"com_ui_mcp_oauth_description": "Continue to authenticate, or copy the link to open it on another device.",
"com_ui_mcp_oauth_qr_code_description": "QR code to open the OAuth login on another device",
"com_ui_mcp_oauth_scan_qr": "Scan to open on your phone",
+ "com_ui_mcp_oauth_secret_reentry_required": "OAuth settings changed. Re-enter the client secret to save this MCP server.",
"com_ui_mcp_oauth_timeout": "OAuth login timed out for {{0}}",
"com_ui_mcp_programmatic": "Programmatic",
"com_ui_mcp_programmatic_all": "Mark all as programmatic",
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index c5f5180035..34d42f55a7 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'crypto';
import { logger, getTenantId, tenantStorage } from '@librechat/data-schemas';
import type { OAuthClientInformation } from '@modelcontextprotocol/sdk/shared/auth.js';
import type { TokenMethods, TenantContext } from '@librechat/data-schemas';
@@ -7,6 +8,8 @@ import type {
OAuthMetadata,
MCPOAuthFlowMetadata,
OAuthProtectedResourceMetadata,
+ OAuthStoredClientMetadata,
+ OAuthClientSource,
} from '~/mcp/oauth';
import type { OboTokenResolver, OboTrustChecker } from '~/mcp/oauth/obo';
import type { FlowStateManager } from '~/flow/manager';
@@ -80,7 +83,7 @@ export class MCPConnectionFactory {
/**
* Process-local in-flight silent refresh promises, keyed by
- * `tenantId:userId:serverName`. Coalesces concurrent `attemptSilentTokenRefresh`
+ * `tenantId:userId:serverName:bindingDigest`. Coalesces concurrent `attemptSilentTokenRefresh`
* calls within this process so a single refresh-token redemption serves every
* waiter in the same tenant — important when multiple connections (or repeated
* 401s) race the same refresh and the OAuth provider rotates refresh tokens.
@@ -556,6 +559,23 @@ export class MCPConnectionFactory {
return MCPOAuthHandler.generateTokenFlowId(this.userId!, this.serverName, this.tenantId);
}
+ private getOAuthBindingDigest(): string {
+ const oauth = this.serverConfig.oauth;
+ return createHash('sha256')
+ .update(
+ JSON.stringify([
+ (this.serverConfig as t.SSEOptions | t.StreamableHTTPOptions).url,
+ oauth?.client_id,
+ oauth?.client_secret,
+ oauth?.authorization_url,
+ oauth?.token_url,
+ oauth?.token_exchange_method,
+ oauth?.token_endpoint_auth_methods_supported,
+ ]),
+ )
+ .digest('base64url');
+ }
+
/** Retrieves existing OAuth tokens from storage or returns null */
protected async getOAuthTokens(): Promise<MCPOAuthTokens | null> {
if (!this.tokenMethods?.findToken) return null;
@@ -575,13 +595,47 @@ export class MCPConnectionFactory {
updateToken: this.tokenMethods!.updateToken,
deleteTokens: this.tokenMethods!.deleteTokens,
refreshTokens: this.createRefreshTokensFunction(),
+ singleFlightScope: this.getOAuthBindingDigest(),
}),
);
},
this.signal,
);
- if (tokens) logger.info(`${this.logPrefix} Loaded OAuth tokens`);
+ if (tokens) {
+ const [isCurrentAccessToken, storedClient] = await this.runWithCapturedTenant(() =>
+ Promise.all([
+ MCPTokenStorage.isCurrentAccessToken({
+ userId: this.userId!,
+ serverName: this.serverName,
+ accessToken: tokens.access_token,
+ credentialSetId: tokens.credential_set_id,
+ findToken: this.tokenMethods!.findToken!,
+ }),
+ MCPTokenStorage.getClientInfoAndMetadata({
+ userId: this.userId!,
+ serverName: this.serverName,
+ findToken: this.tokenMethods!.findToken!,
+ }),
+ ]),
+ );
+ if (!isCurrentAccessToken) {
+ throw new Error(`${this.logPrefix} Cached OAuth access token is stale`);
+ }
+ MCPTokenStorage.assertCredentialSetBinding(
+ this.serverName,
+ tokens.credential_set_id,
+ storedClient?.clientMetadata,
+ );
+ MCPOAuthHandler.assertStoredClientBinding(
+ this.serverName,
+ (this.serverConfig as t.SSEOptions | t.StreamableHTTPOptions).url,
+ storedClient?.clientInfo,
+ storedClient?.clientMetadata as Partial<OAuthStoredClientMetadata> | undefined,
+ this.serverConfig.oauth,
+ );
+ logger.info(`${this.logPrefix} Loaded OAuth tokens`);
+ }
return tokens;
} catch (error) {
if (error instanceof ReauthenticationRequiredError) {
@@ -603,6 +657,8 @@ export class MCPConnectionFactory {
clientInfo?: OAuthClientInformation;
storedTokenEndpoint?: string;
storedAuthMethods?: string[];
+ storedServerUrl?: string;
+ clientSource?: OAuthClientSource;
resource?: string;
},
signal?: AbortSignal,
@@ -616,6 +672,8 @@ export class MCPConnectionFactory {
clientInfo: metadata.clientInfo,
storedTokenEndpoint: metadata.storedTokenEndpoint,
storedAuthMethods: metadata.storedAuthMethods,
+ storedServerUrl: metadata.storedServerUrl,
+ clientSource: metadata.clientSource,
resource: metadata.resource,
},
this.serverConfig.oauth_headers ?? {},
@@ -646,11 +704,10 @@ export class MCPConnectionFactory {
return null;
}
- // Scope the lock by tenant so two tenants that share the same `userId`
- // and `serverName` (common with username-based IDs in multi-tenant setups)
- // can never join each other's refresh and have those tokens applied to the
- // wrong connection.
- const lockKey = `${this.tenantId ?? ''}:${this.userId ?? ''}:${this.serverName}`;
+ // Scope the lock by tenant and OAuth binding so neither another tenant nor a
+ // same-name server whose URL/client configuration changed can join the refresh.
+ const bindingDigest = this.getOAuthBindingDigest();
+ const lockKey = `${this.tenantId ?? ''}:${this.userId ?? ''}:${this.serverName}:${bindingDigest}`;
const inflight = MCPConnectionFactory.inflightSilentRefreshes.get(lockKey);
if (inflight) {
logger.debug(`${this.logPrefix} Joining in-flight silent refresh attempt`);
@@ -661,7 +718,7 @@ export class MCPConnectionFactory {
const abortController = new AbortController();
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let abortGraceTimeoutId: ReturnType<typeof setTimeout> | null = null;
- const refreshPromise = this.runSilentRefresh(abortController.signal);
+ const refreshPromise = this.runSilentRefresh(abortController.signal, bindingDigest);
const promise = new Promise<MCPOAuthTokens | null>((resolve) => {
timeoutId = setTimeout(() => {
abortController.abort();
@@ -706,7 +763,10 @@ export class MCPConnectionFactory {
* persists the new tokens. Called by `attemptSilentTokenRefresh` under the
* `inflightSilentRefreshes` coalescing lock.
*/
- private async runSilentRefresh(signal: AbortSignal): Promise<MCPOAuthTokens | null> {
+ private async runSilentRefresh(
+ signal: AbortSignal,
+ singleFlightScope: string,
+ ): Promise<MCPOAuthTokens | null> {
try {
const tokens = await this.runWithCapturedTenant(async () =>
MCPTokenStorage.forceRefreshTokens({
@@ -717,6 +777,7 @@ export class MCPConnectionFactory {
updateToken: this.tokenMethods!.updateToken,
deleteTokens: this.tokenMethods!.deleteTokens,
refreshTokens: this.createRefreshTokensFunction(),
+ singleFlightScope,
signal,
/**
* Drop any previously cached `mcp_get_tokens` result so the next
@@ -818,6 +879,32 @@ export class MCPConnectionFactory {
return flowTenantId === this.tenantId;
}
+ /** Prevents server-name keyed OAuth flow cache entries from crossing config bindings. */
+ private isCurrentServerOAuthFlow(meta: MCPOAuthFlowMetadata | undefined): boolean {
+ const currentServerUrl = (this.serverConfig as t.SSEOptions | t.StreamableHTTPOptions).url;
+ try {
+ MCPOAuthHandler.assertStoredClientBinding(
+ this.serverName,
+ currentServerUrl,
+ meta?.clientInfo,
+ MCPOAuthHandler.buildStoredClientMetadata(
+ meta?.metadata,
+ meta?.resourceMetadata,
+ meta?.serverUrl,
+ meta?.clientSource,
+ ),
+ this.serverConfig.oauth,
+ );
+ return true;
+ } catch (error) {
+ logger.info(
+ `${this.logPrefix} Cached OAuth flow binding is stale; starting a new flow`,
+ error,
+ );
+ return false;
+ }
+ }
+
private getOAuthRequiredStatusCode(data: OAuthRequiredEvent): number | undefined {
if (typeof data.status === 'number') {
return data.status;
@@ -940,12 +1027,12 @@ export class MCPConnectionFactory {
const pendingAge = existingFlow.createdAt
? Date.now() - existingFlow.createdAt
: Infinity;
+ const flowMeta = existingFlow.metadata as MCPOAuthFlowMetadata | undefined;
- if (pendingAge < PENDING_STALE_MS) {
+ if (pendingAge < PENDING_STALE_MS && this.isCurrentServerOAuthFlow(flowMeta)) {
logger.debug(
`${this.logPrefix} Recent PENDING OAuth flow exists (${Math.round(pendingAge / 1000)}s old), skipping new initiation`,
);
- const flowMeta = existingFlow.metadata as MCPOAuthFlowMetadata | undefined;
const storedAuthUrl = flowMeta?.authorizationUrl;
if (storedAuthUrl && typeof this.oauthStart === 'function') {
const expiresAt = this.getOAuthReplayExpiresAt(existingFlow.createdAt);
@@ -1009,7 +1096,10 @@ export class MCPConnectionFactory {
this.flowManager!.createFlow(newFlowId, 'mcp_oauth', {}, this.signal).catch(
async (error) => {
logger.debug(`${this.logPrefix} OAuth flow monitor ended`, error);
- await this.clearStaleClientIfRejected(flowMetadata.reusedStoredClient, error);
+ await this.clearStaleClientIfRejected(
+ flowMetadata.reusedClientCredentialSetId,
+ error,
+ );
},
);
@@ -1030,33 +1120,63 @@ export class MCPConnectionFactory {
// Normal OAuth handling - wait for completion
const result = await this.handleOAuthRequired();
- if (result?.tokens && this.tokenMethods?.createToken) {
+ if (result?.tokens) {
const { tokens } = result;
try {
- connection.setOAuthTokens(tokens);
- await this.runWithCapturedTenant(() =>
- MCPTokenStorage.storeTokens({
- userId: this.userId!,
- serverName: this.serverName,
- tokens,
- createToken: this.tokenMethods!.createToken,
- updateToken: this.tokenMethods!.updateToken,
- findToken: this.tokenMethods!.findToken,
- clientInfo: result.clientInfo,
- metadata: MCPOAuthHandler.buildStoredClientMetadata(
- result.metadata,
- result.resourceMetadata,
- ),
- }),
+ if (
+ !this.tokenMethods?.findToken ||
+ typeof tokens.credential_set_id !== 'string' ||
+ tokens.credential_set_id.length === 0
+ ) {
+ throw new ReauthenticationRequiredError(this.serverName, 'binding');
+ }
+
+ const [isCurrentAccessToken, storedClient] = await this.runWithCapturedTenant(() =>
+ Promise.all([
+ MCPTokenStorage.isCurrentAccessToken({
+ userId: this.userId!,
+ serverName: this.serverName,
+ accessToken: tokens.access_token,
+ credentialSetId: tokens.credential_set_id,
+ findToken: this.tokenMethods!.findToken!,
+ }),
+ MCPTokenStorage.getClientInfoAndMetadata({
+ userId: this.userId!,
+ serverName: this.serverName,
+ findToken: this.tokenMethods!.findToken!,
+ }),
+ ]),
+ );
+ if (!isCurrentAccessToken || !storedClient) {
+ throw new ReauthenticationRequiredError(this.serverName, 'binding');
+ }
+ MCPTokenStorage.assertCredentialSetBinding(
+ this.serverName,
+ tokens.credential_set_id,
+ storedClient.clientMetadata,
+ );
+ MCPOAuthHandler.assertStoredClientBinding(
+ this.serverName,
+ (this.serverConfig as t.SSEOptions | t.StreamableHTTPOptions).url,
+ storedClient.clientInfo,
+ storedClient.clientMetadata as Partial<OAuthStoredClientMetadata> | undefined,
+ this.serverConfig.oauth,
);
+
+ connection.setOAuthTokens(tokens);
// Same rationale as the silent-refresh success path: invalidate the
// `mcp_get_tokens` cache so the next `getOAuthTokens` reads the
// freshly stored tokens rather than the just-rejected ones the
// interactive flow replaced.
await this.invalidateGetTokensFlow(tokens);
- logger.info(`${this.logPrefix} OAuth tokens saved to storage`);
+ logger.info(`${this.logPrefix} Verified OAuth callback tokens in storage`);
} catch (error) {
- logger.error(`${this.logPrefix} Failed to save OAuth tokens to storage`, error);
+ logger.error(`${this.logPrefix} Failed to verify OAuth callback tokens`, error);
+ connection.emit(
+ 'oauthFailed',
+ error instanceof Error ? error : new Error('OAuth token verification failed'),
+ );
+ return;
}
}
@@ -1064,7 +1184,7 @@ export class MCPConnectionFactory {
if (result?.tokens) {
connection.emit('oauthHandled');
} else {
- await this.clearStaleClientIfRejected(result?.reusedStoredClient, result?.error);
+ await this.clearStaleClientIfRejected(result?.reusedClientCredentialSetId, result?.error);
logger.warn(`${this.logPrefix} OAuth failed, emitting oauthFailed event`);
connection.emit('oauthFailed', new Error('OAuth authentication failed'));
}
@@ -1170,10 +1290,10 @@ export class MCPConnectionFactory {
/** Clears stored client registration if the error indicates client rejection */
private async clearStaleClientIfRejected(
- reusedStoredClient: boolean | undefined,
+ reusedClientCredentialSetId: string | undefined,
error: unknown,
): Promise<void> {
- if (!reusedStoredClient || !this.tokenMethods?.deleteTokens) {
+ if (!reusedClientCredentialSetId || !this.tokenMethods?.deleteTokens) {
return;
}
if (!MCPConnectionFactory.isClientRejection(error)) {
@@ -1184,6 +1304,7 @@ export class MCPConnectionFactory {
userId: this.userId!,
serverName: this.serverName,
deleteTokens: this.tokenMethods!.deleteTokens,
+ credentialSetId: reusedClientCredentialSetId,
}),
).catch((err) => {
logger.warn(`${this.logPrefix} Failed to clear stale client registration`, err);
@@ -1254,7 +1375,9 @@ export class MCPConnectionFactory {
clientInfo?: OAuthClientInformation;
metadata?: OAuthMetadata;
resourceMetadata?: OAuthProtectedResourceMetadata;
+ clientSource?: OAuthClientSource;
reusedStoredClient?: boolean;
+ reusedClientCredentialSetId?: string;
error?: unknown;
} | null> {
const serverUrl = (this.serverConfig as t.SSEOptions | t.StreamableHTTPOptions).url;
@@ -1271,6 +1394,7 @@ export class MCPConnectionFactory {
}
let reusedStoredClient = false;
+ let reusedClientCredentialSetId: string | undefined;
try {
logger.debug(`${this.logPrefix} Checking for existing OAuth flow for ${this.serverName}...`);
@@ -1289,7 +1413,7 @@ export class MCPConnectionFactory {
? Date.now() - existingFlow.createdAt
: Infinity;
- if (pendingAge < PENDING_STALE_MS) {
+ if (pendingAge < PENDING_STALE_MS && this.isCurrentServerOAuthFlow(flowMeta)) {
logger.debug(
`${this.logPrefix} Found recent PENDING OAuth flow (${Math.round(pendingAge / 1000)}s old), joining instead of creating new one`,
);
@@ -1307,6 +1431,7 @@ export class MCPConnectionFactory {
}
reusedStoredClient = flowMeta?.reusedStoredClient === true;
+ reusedClientCredentialSetId = flowMeta?.reusedClientCredentialSetId;
const tokens = await this.flowManager.createFlow(flowId, 'mcp_oauth', {}, this.signal);
if (typeof this.oauthEnd === 'function') {
await this.oauthEnd();
@@ -1319,7 +1444,9 @@ export class MCPConnectionFactory {
clientInfo: flowMeta?.clientInfo,
metadata: flowMeta?.metadata,
resourceMetadata: flowMeta?.resourceMetadata,
+ clientSource: flowMeta?.clientSource,
reusedStoredClient,
+ reusedClientCredentialSetId,
};
}
@@ -1337,7 +1464,12 @@ export class MCPConnectionFactory {
cachedTokens?.expires_at != null &&
normalizeExpiresAt(cachedTokens.expires_at) < Date.now();
- if (completedAge <= PENDING_STALE_MS && cachedTokens !== undefined && !isTokenExpired) {
+ if (
+ completedAge <= PENDING_STALE_MS &&
+ cachedTokens !== undefined &&
+ !isTokenExpired &&
+ this.isCurrentServerOAuthFlow(flowMeta)
+ ) {
logger.debug(
`${this.logPrefix} Found non-stale COMPLETED OAuth flow, reusing cached tokens`,
);
@@ -1346,6 +1478,9 @@ export class MCPConnectionFactory {
clientInfo: flowMeta?.clientInfo,
metadata: flowMeta?.metadata,
resourceMetadata: flowMeta?.resourceMetadata,
+ clientSource: flowMeta?.clientSource,
+ reusedStoredClient: flowMeta?.reusedStoredClient,
+ reusedClientCredentialSetId: flowMeta?.reusedClientCredentialSetId,
};
}
}
@@ -1384,6 +1519,7 @@ export class MCPConnectionFactory {
);
reusedStoredClient = flowMetadata.reusedStoredClient === true;
+ reusedClientCredentialSetId = flowMetadata.reusedClientCredentialSetId;
// Store flow state BEFORE redirecting so the callback can find it
const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: this.tenantId };
@@ -1412,11 +1548,13 @@ export class MCPConnectionFactory {
clientInfo: flowMetadata.clientInfo,
metadata: flowMetadata.metadata,
resourceMetadata: flowMetadata.resourceMetadata,
+ clientSource: flowMetadata.clientSource,
reusedStoredClient,
+ reusedClientCredentialSetId,
};
} catch (error) {
logger.error(`${this.logPrefix} Failed to complete OAuth flow for ${this.serverName}`, error);
- return { tokens: null, reusedStoredClient, error };
+ return { tokens: null, reusedStoredClient, reusedClientCredentialSetId, error };
}
}
}
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
index e087ab9f20..4ea28e1363 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
@@ -139,6 +139,8 @@ async function storeTokens(
grant_types_supported: ['authorization_code', 'refresh_token'],
token_endpoint_auth_methods_supported: ['none'],
scopes_supported: scope.split(/\s+/).filter(Boolean),
+ server_url: server.url,
+ client_source: 'dynamic',
resource: server.resourceUrl,
};
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
index 01339baaea..b4700b8bc1 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -60,6 +60,18 @@ class InspectableMCPConnectionFactory extends MCPConnectionFactory {
await this.attemptToConnect(connection);
}
+ public async getOAuthTokensForTest(): Promise<MCPOAuthTokens | null> {
+ return await this.getOAuthTokens();
+ }
+
+ public async attemptSilentTokenRefreshForTest(): Promise<MCPOAuthTokens | null> {
+ return await this.attemptSilentTokenRefresh();
+ }
+
+ public async handleOAuthRequiredForTest() {
+ return await this.handleOAuthRequired();
+ }
+
public getRequestScopedOAuthState(): {
signal?: AbortSignal;
oauthStart?: (authURL: string) => Promise<void>;
@@ -137,14 +149,25 @@ describe('MCPConnectionFactory', () => {
},
);
mockMCPOAuthHandler.buildStoredClientMetadata.mockImplementation(
- (metadata, resourceMetadata) =>
- metadata
+ (metadata, resourceMetadata, serverUrl, clientSource) =>
+ metadata && serverUrl && clientSource
? {
...metadata,
+ server_url: serverUrl,
+ client_source: clientSource,
...(resourceMetadata?.resource && { resource: resourceMetadata.resource }),
}
: undefined,
);
+ mockMCPOAuthHandler.assertStoredClientBinding.mockImplementation(() => undefined);
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValue(true);
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
+ clientInfo: { client_id: 'persisted-client' },
+ clientMetadata: {
+ server_url: 'https://api.example.com',
+ credential_set_id: 'persisted-generation',
+ },
+ });
mockTenantStorage.getStore.mockReturnValue(undefined);
mockTenantStorage.run.mockImplementation((_context, fn: () => Promise<unknown>) => fn());
(getTenantId as jest.Mock).mockReturnValue(undefined);
@@ -308,6 +331,7 @@ describe('MCPConnectionFactory', () => {
refresh_token: 'refresh123',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'callback-generation',
};
mockFlowManager.createFlowWithHandler.mockResolvedValue(mockTokens);
@@ -393,6 +417,292 @@ describe('MCPConnectionFactory', () => {
expect(mockFlowManager.createFlowWithHandler).not.toHaveBeenCalled();
});
+ it('rejects a cached access token before it reaches a differently bound connection', async () => {
+ const currentConfig = {
+ type: 'sse' as const,
+ url: 'https://server-b.example.com/mcp',
+ initTimeout: 5000,
+ } as t.SSEOptions;
+ mockProcessMCPEnv.mockReturnValue(currentConfig);
+ mockFlowManager.createFlowWithHandler.mockResolvedValue({
+ access_token: 'server-a-access-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ });
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
+ clientInfo: { client_id: 'dynamic-client' },
+ clientMetadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ server_url: 'https://server-a.example.com/mcp',
+ client_source: 'dynamic',
+ },
+ });
+ mockMCPOAuthHandler.assertStoredClientBinding.mockImplementationOnce(
+ (_serverName, serverUrl, _clientInfo, storedMetadata) => {
+ if (storedMetadata?.server_url !== serverUrl) {
+ throw new Error('stale OAuth binding');
+ }
+ },
+ );
+
+ const factory = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: currentConfig },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+ mockConnectionInstance.isConnected.mockResolvedValue(true);
+
+ await expect(factory.createConnectionForTest()).resolves.toBe(mockConnectionInstance);
+ expect(mockMCPTokenStorage.isCurrentAccessToken).toHaveBeenCalledWith(
+ expect.objectContaining({ accessToken: 'server-a-access-token' }),
+ );
+ expect(mockMCPTokenStorage.getClientInfoAndMetadata).toHaveBeenCalled();
+ expect(mockMCPOAuthHandler.assertStoredClientBinding).toHaveBeenCalledWith(
+ 'test-server',
+ 'https://server-b.example.com/mcp',
+ expect.objectContaining({ client_id: 'dynamic-client' }),
+ expect.objectContaining({ server_url: 'https://server-a.example.com/mcp' }),
+ undefined,
+ );
+ expect(mockMCPConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ serverName: 'test-server',
+ serverConfig: currentConfig,
+ oauthTokens: null,
+ }),
+ );
+ });
+
+ it('rejects a cached token when the client generation changes after access validation', async () => {
+ const currentConfig = {
+ type: 'sse' as const,
+ url: 'https://server.example.com/mcp',
+ initTimeout: 5000,
+ } as t.SSEOptions;
+ mockProcessMCPEnv.mockReturnValue(currentConfig);
+ mockFlowManager.createFlowWithHandler.mockResolvedValue({
+ access_token: 'generation-a-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'credential-set-a',
+ });
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValueOnce(true);
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
+ clientInfo: { client_id: 'client-b' },
+ clientMetadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ server_url: 'https://server.example.com/mcp',
+ client_source: 'dynamic',
+ credential_set_id: 'credential-set-b',
+ },
+ });
+ mockMCPTokenStorage.assertCredentialSetBinding.mockImplementationOnce(
+ (_serverName, tokenCredentialSetId, clientMetadata) => {
+ if (tokenCredentialSetId !== clientMetadata?.credential_set_id) {
+ throw new Error('mixed OAuth credential generations');
+ }
+ },
+ );
+
+ const factory = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: currentConfig },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+
+ await expect(factory.getOAuthTokensForTest()).resolves.toBeNull();
+ expect(mockMCPTokenStorage.isCurrentAccessToken).toHaveBeenCalledWith(
+ expect.objectContaining({
+ accessToken: 'generation-a-access',
+ credentialSetId: 'credential-set-a',
+ }),
+ );
+ expect(mockMCPTokenStorage.assertCredentialSetBinding).toHaveBeenCalledWith(
+ 'test-server',
+ 'credential-set-a',
+ expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ );
+ });
+
+ it('starts access and client binding verification in parallel', async () => {
+ const currentConfig = {
+ type: 'sse' as const,
+ url: 'https://server.example.com/mcp',
+ initTimeout: 5000,
+ } as t.SSEOptions;
+ mockProcessMCPEnv.mockReturnValue(currentConfig);
+ mockFlowManager.createFlowWithHandler.mockResolvedValue({
+ access_token: 'generation-a-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'credential-set-a',
+ });
+
+ let resolveAccessVerification!: (value: boolean) => void;
+ const accessVerification = new Promise<boolean>((resolve) => {
+ resolveAccessVerification = resolve;
+ });
+ const verificationStarts: string[] = [];
+ mockMCPTokenStorage.isCurrentAccessToken.mockImplementationOnce(() => {
+ verificationStarts.push('access');
+ return accessVerification;
+ });
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockImplementationOnce(async () => {
+ verificationStarts.push('client');
+ return {
+ clientInfo: { client_id: 'client-a' },
+ clientMetadata: {
+ server_url: 'https://server.example.com/mcp',
+ credential_set_id: 'credential-set-a',
+ },
+ };
+ });
+
+ const factory = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: currentConfig },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+
+ const tokenRead = factory.getOAuthTokensForTest();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(verificationStarts).toEqual(['access', 'client']);
+
+ resolveAccessVerification(true);
+ await expect(tokenRead).resolves.toMatchObject({
+ access_token: 'generation-a-access',
+ credential_set_id: 'credential-set-a',
+ });
+ });
+
+ it.each(['PENDING', 'COMPLETED'] as const)(
+ 'replaces a recent %s OAuth flow bound to another server URL',
+ async (status) => {
+ const currentConfig = {
+ type: 'sse' as const,
+ url: 'https://server-b.example.com/mcp',
+ initTimeout: 5000,
+ } as t.SSEOptions;
+ const staleMetadata = {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://server-a.example.com/mcp',
+ state: 'stale-state',
+ authorizationUrl: 'https://auth.example.com/old-authorize',
+ clientInfo: { client_id: 'old-dynamic-client' },
+ clientSource: 'dynamic' as const,
+ metadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ },
+ };
+ const staleTokens: MCPOAuthTokens = {
+ access_token: 'server-a-access-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ const freshTokens: MCPOAuthTokens = {
+ access_token: 'server-b-access-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ const oauthStart = jest.fn();
+
+ mockProcessMCPEnv.mockReturnValue(currentConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPOAuthHandler.assertStoredClientBinding.mockImplementation(
+ (_serverName, serverUrl, _clientInfo, storedMetadata) => {
+ if (storedMetadata?.server_url !== serverUrl) {
+ throw new Error('stale OAuth binding');
+ }
+ },
+ );
+ mockFlowManager.getFlowState.mockResolvedValue({
+ status,
+ type: 'mcp_oauth',
+ metadata: staleMetadata,
+ createdAt: Date.now(),
+ ...(status === 'COMPLETED' && {
+ completedAt: Date.now(),
+ result: staleTokens,
+ }),
+ });
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com/fresh-authorize',
+ flowId: 'fresh-flow',
+ flowMetadata: {
+ ...staleMetadata,
+ serverUrl: currentConfig.url,
+ state: 'fresh-state',
+ authorizationUrl: 'https://auth.example.com/fresh-authorize',
+ clientInfo: { client_id: 'fresh-dynamic-client' },
+ },
+ });
+ mockFlowManager.createFlow.mockResolvedValue(freshTokens);
+
+ const factory = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: currentConfig },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+
+ const result = await factory.handleOAuthRequiredForTest();
+
+ expect(result?.tokens).toEqual(freshTokens);
+ expect(result?.tokens).not.toEqual(staleTokens);
+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('flow123', 'mcp_oauth');
+ expect(mockMCPOAuthHandler.deleteStateMapping).toHaveBeenCalledWith(
+ 'stale-state',
+ mockFlowManager,
+ );
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();
+ expect(oauthStart).toHaveBeenCalledWith('https://auth.example.com/fresh-authorize');
+ expect(oauthStart).not.toHaveBeenCalledWith(
+ 'https://auth.example.com/old-authorize',
+ expect.anything(),
+ );
+ },
+ );
+
it('should handle token retrieval errors gracefully', async () => {
const basicOptions = {
serverName: 'test-server',
@@ -563,6 +873,7 @@ describe('MCPConnectionFactory', () => {
state: 'random-state',
clientInfo: { client_id: 'stale-client' },
reusedStoredClient: true,
+ reusedClientCredentialSetId: 'credential-generation-a',
},
};
@@ -596,6 +907,7 @@ describe('MCPConnectionFactory', () => {
expect.objectContaining({
userId: 'user123',
serverName: 'test-server',
+ credentialSetId: 'credential-generation-a',
}),
);
});
@@ -895,6 +1207,7 @@ describe('MCPConnectionFactory', () => {
refresh_token: 'refresh123',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'blocking-callback-generation',
};
// processMCPEnv must return config with url so handleOAuthRequired proceeds
@@ -1149,6 +1462,7 @@ describe('MCPConnectionFactory', () => {
access_token: 'interactive-access',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'interactive-generation',
};
mockProcessMCPEnv.mockReturnValue(sseConfig);
@@ -1517,6 +1831,65 @@ describe('MCPConnectionFactory', () => {
expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(refreshedTokens);
});
+ it('does not coalesce silent refreshes across different server bindings', async () => {
+ const makeConfig = (url: string): t.SSEOptions => ({
+ type: 'sse',
+ url,
+ initTimeout: 15000,
+ });
+ const tokenMethods = {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ };
+ mockProcessMCPEnv.mockImplementation(({ options }) => options as t.MCPOptions);
+
+ const factoryA = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: makeConfig('https://server-a.example.com/mcp') },
+ { useOAuth: true, user: mockUser, flowManager: mockFlowManager, tokenMethods },
+ );
+ const factoryB = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: makeConfig('https://server-b.example.com/mcp') },
+ { useOAuth: true, user: mockUser, flowManager: mockFlowManager, tokenMethods },
+ );
+
+ const resolutions: Array<(tokens: MCPOAuthTokens) => void> = [];
+ mockMCPTokenStorage.forceRefreshTokens.mockImplementation(
+ () =>
+ new Promise<MCPOAuthTokens>((resolve) => {
+ resolutions.push(resolve);
+ }),
+ );
+
+ const attemptA = factoryA.attemptSilentTokenRefreshForTest();
+ await Promise.resolve();
+ const attemptB = factoryB.attemptSilentTokenRefreshForTest();
+ await Promise.resolve();
+
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);
+ const scopeA = mockMCPTokenStorage.forceRefreshTokens.mock.calls[0][0].singleFlightScope;
+ const scopeB = mockMCPTokenStorage.forceRefreshTokens.mock.calls[1][0].singleFlightScope;
+ expect(scopeA).toEqual(expect.any(String));
+ expect(scopeB).toEqual(expect.any(String));
+ expect(scopeA).not.toBe(scopeB);
+ const tokensA: MCPOAuthTokens = {
+ access_token: 'server-a-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ const tokensB: MCPOAuthTokens = {
+ access_token: 'server-b-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ resolutions[0](tokensA);
+ resolutions[1](tokensB);
+
+ await expect(attemptA).resolves.toEqual(tokensA);
+ await expect(attemptB).resolves.toEqual(tokensB);
+ });
+
it('should keep the in-flight silent-refresh lock until the aborted refresh settles', async () => {
// A timed-out caller should fall back to interactive OAuth immediately,
// but the shared lock must remain briefly while the underlying abortable
@@ -2122,6 +2495,7 @@ describe('MCPConnectionFactory', () => {
access_token: 'callback-access',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'callback-generation',
};
mockProcessMCPEnv.mockReturnValue(sseConfig);
@@ -2761,6 +3135,7 @@ describe('MCPConnectionFactory', () => {
access_token: 'interactive-access',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'interactive-generation',
};
mockProcessMCPEnv.mockReturnValue(sseConfig);
@@ -2820,6 +3195,405 @@ describe('MCPConnectionFactory', () => {
// `getOAuthTokens` reads the freshly persisted interactive tokens.
expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('flow123', 'mcp_get_tokens');
});
+
+ it('does not persist callback tokens a second time after the route stored them', async () => {
+ const sseConfig = {
+ ...mockServerConfig,
+ url: 'https://api.example.com',
+ type: 'sse' as const,
+ } as t.SSEOptions;
+ const callbackTokens: MCPOAuthTokens = {
+ access_token: 'interactive-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'callback-generation',
+ };
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart: jest.fn(),
+ oauthEnd: jest.fn(),
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+
+ mockProcessMCPEnv.mockReturnValue(sseConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com',
+ flowId: 'flow123',
+ flowMetadata: {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://api.example.com',
+ state: 'fresh-csrf-state',
+ clientInfo: { client_id: 'client-a' },
+ metadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ },
+ clientSource: 'dynamic',
+ },
+ });
+ mockFlowManager.getFlowState.mockResolvedValue(null);
+ mockFlowManager.createFlow.mockResolvedValue(callbackTokens);
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValue(true);
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
+ clientInfo: { client_id: 'client-a' },
+ clientMetadata: {
+ server_url: 'https://api.example.com',
+ credential_set_id: 'callback-generation',
+ },
+ });
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+
+ let oauthRequiredHandler!: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+
+ try {
+ await MCPConnectionFactory.create(
+ { serverName: 'test-server', serverConfig: sseConfig },
+ oauthOptions,
+ );
+ } catch {
+ // Expected: the mocked connection never becomes connected.
+ }
+ await oauthRequiredHandler({ serverUrl: 'https://api.example.com' });
+
+ expect(mockMCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(callbackTokens);
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled');
+ });
+
+ it('rejects callback tokens that do not identify a persisted credential generation', async () => {
+ const sseConfig = {
+ ...mockServerConfig,
+ url: 'https://api.example.com',
+ type: 'sse' as const,
+ } as t.SSEOptions;
+ const callbackTokens: MCPOAuthTokens = {
+ access_token: 'unbound-interactive-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart: jest.fn(),
+ oauthEnd: jest.fn(),
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+
+ mockProcessMCPEnv.mockReturnValue(sseConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com',
+ flowId: 'flow123',
+ flowMetadata: {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://api.example.com',
+ state: 'fresh-csrf-state',
+ clientInfo: { client_id: 'client-a' },
+ metadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ },
+ clientSource: 'dynamic',
+ },
+ });
+ mockFlowManager.getFlowState.mockResolvedValue(null);
+ mockFlowManager.createFlow.mockResolvedValue(callbackTokens);
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+
+ let oauthRequiredHandler!: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+
+ try {
+ await MCPConnectionFactory.create(
+ { serverName: 'test-server', serverConfig: sseConfig },
+ oauthOptions,
+ );
+ } catch {
+ // Expected: the mocked connection never becomes connected.
+ }
+ await oauthRequiredHandler({ serverUrl: 'https://api.example.com' });
+
+ expect(mockMCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ expect(mockMCPTokenStorage.isCurrentAccessToken).not.toHaveBeenCalled();
+ expect(mockMCPTokenStorage.getClientInfoAndMetadata).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.setOAuthTokens).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthFailed', expect.any(Error));
+ expect(mockConnectionInstance.emit).not.toHaveBeenCalledWith('oauthHandled');
+ });
+
+ it('does not resurrect an ID-bearing callback after a newer generation wins', async () => {
+ const sseConfig = {
+ ...mockServerConfig,
+ url: 'https://api.example.com',
+ type: 'sse' as const,
+ } as t.SSEOptions;
+ const callbackTokens: MCPOAuthTokens = {
+ access_token: 'stale-interactive-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'stale-callback-generation',
+ };
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart: jest.fn(),
+ oauthEnd: jest.fn(),
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+
+ mockProcessMCPEnv.mockReturnValue(sseConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com',
+ flowId: 'flow123',
+ flowMetadata: {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://api.example.com',
+ state: 'fresh-csrf-state',
+ clientInfo: { client_id: 'client-a' },
+ metadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ },
+ clientSource: 'dynamic',
+ },
+ });
+ mockFlowManager.getFlowState.mockResolvedValue(null);
+ mockFlowManager.createFlow.mockResolvedValue(callbackTokens);
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValueOnce(false);
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
+ clientInfo: { client_id: 'client-b' },
+ clientMetadata: {
+ server_url: 'https://api.example.com',
+ credential_set_id: 'newer-generation',
+ },
+ });
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+
+ let oauthRequiredHandler!: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+
+ try {
+ await MCPConnectionFactory.create(
+ { serverName: 'test-server', serverConfig: sseConfig },
+ oauthOptions,
+ );
+ } catch {
+ // Expected: the mocked connection never becomes connected.
+ }
+ await oauthRequiredHandler({ serverUrl: 'https://api.example.com' });
+
+ expect(mockMCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.setOAuthTokens).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthFailed', expect.any(Error));
+ expect(mockConnectionInstance.emit).not.toHaveBeenCalledWith('oauthHandled');
+ });
+
+ it('rejects already-persisted callback tokens when the server binding changed', async () => {
+ const sseConfig = {
+ ...mockServerConfig,
+ url: 'https://current.example.com/mcp',
+ type: 'sse' as const,
+ } as t.SSEOptions;
+ const callbackTokens: MCPOAuthTokens = {
+ access_token: 'interactive-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'callback-generation',
+ };
+ const bindingError = new Error('stale OAuth server binding');
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart: jest.fn(),
+ oauthEnd: jest.fn(),
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+
+ mockProcessMCPEnv.mockReturnValue(sseConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com',
+ flowId: 'flow123',
+ flowMetadata: {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://old.example.com/mcp',
+ state: 'fresh-csrf-state',
+ clientInfo: { client_id: 'client-a' },
+ metadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ },
+ clientSource: 'dynamic',
+ },
+ });
+ mockFlowManager.getFlowState.mockResolvedValue(null);
+ mockFlowManager.createFlow.mockResolvedValue(callbackTokens);
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValue(true);
+ mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
+ clientInfo: { client_id: 'client-a' },
+ clientMetadata: {
+ server_url: 'https://old.example.com/mcp',
+ credential_set_id: 'callback-generation',
+ },
+ });
+ mockMCPOAuthHandler.assertStoredClientBinding.mockImplementationOnce(() => {
+ throw bindingError;
+ });
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+
+ let oauthRequiredHandler!: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+
+ try {
+ await MCPConnectionFactory.create(
+ { serverName: 'test-server', serverConfig: sseConfig },
+ oauthOptions,
+ );
+ } catch {
+ // Expected: the mocked connection never becomes connected.
+ }
+ await oauthRequiredHandler({ serverUrl: 'https://current.example.com/mcp' });
+
+ expect(mockMCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.setOAuthTokens).not.toHaveBeenCalled();
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthFailed', bindingError);
+ expect(mockConnectionInstance.emit).not.toHaveBeenCalledWith('oauthHandled');
+ });
+
+ it('should complete PENDING token waiters with the persisted interactive credential generation', async () => {
+ const sseConfig = {
+ ...mockServerConfig,
+ url: 'https://api.example.com',
+ type: 'sse' as const,
+ } as t.SSEOptions;
+ const basicOptions = {
+ serverName: 'test-server',
+ serverConfig: sseConfig,
+ };
+ const oauthOptions = {
+ useOAuth: true as const,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart: jest.fn(),
+ oauthEnd: jest.fn(),
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ };
+ const callbackTokens: MCPOAuthTokens = {
+ access_token: 'interactive-access',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'persisted-generation',
+ };
+
+ mockProcessMCPEnv.mockReturnValue(sseConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com',
+ flowId: 'flow123',
+ flowMetadata: {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://api.example.com',
+ state: 'fresh-csrf-state',
+ },
+ });
+ mockFlowManager.getFlowState
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({
+ status: 'PENDING' as const,
+ type: 'mcp_get_tokens',
+ metadata: {},
+ createdAt: Date.now(),
+ });
+ mockFlowManager.createFlow.mockResolvedValue(callbackTokens);
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+
+ let oauthRequiredHandler: (data: Record<string, unknown>) => Promise<void>;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+
+ try {
+ await MCPConnectionFactory.create(basicOptions, oauthOptions);
+ } catch {
+ // Expected
+ }
+ await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });
+
+ expect(mockMCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
+ 'flow123',
+ 'mcp_get_tokens',
+ callbackTokens,
+ );
+ expect(mockFlowManager.deleteFlow).not.toHaveBeenCalledWith('flow123', 'mcp_get_tokens');
+ });
});
describe('connection retry logic', () => {
@@ -3252,6 +4026,7 @@ describe('MCPConnectionFactory', () => {
access_token: 'bq-token',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'bq-generation',
};
const mockFlowData = {
@@ -3306,6 +4081,7 @@ describe('MCPConnectionFactory', () => {
access_token: 'drive-token',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'drive-generation',
};
mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow-drive');
@@ -3522,6 +4298,7 @@ describe('MCPConnectionFactory', () => {
access_token: 'cleanup-token',
token_type: 'Bearer',
obtained_at: Date.now(),
+ credential_set_id: 'cleanup-generation',
};
mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow-cleanup');
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthAudience.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthAudience.test.ts
index 80790da57d..06496fc5d8 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthAudience.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthAudience.test.ts
@@ -10,10 +10,10 @@
* request body it receives.
*/
-import * as http from 'http';
import * as net from 'net';
-import type { Socket } from 'net';
+import * as http from 'http';
import { TokenExchangeMethodEnum } from 'librechat-data-provider';
+import type { Socket } from 'net';
import { MCPOAuthHandler } from '~/mcp/oauth';
jest.mock('@librechat/data-schemas', () => ({
@@ -172,7 +172,10 @@ describe('MCP OAuth audience parameter', () => {
client_id: 'test-client',
client_secret: 'test-secret',
redirect_uris: ['http://localhost/callback'],
+ token_endpoint_auth_method: 'client_secret_post',
},
+ storedTokenEndpoint: `${recorder.url}token`,
+ storedAuthMethods: ['client_secret_post'],
},
{},
{
@@ -200,7 +203,10 @@ describe('MCP OAuth audience parameter', () => {
client_id: 'test-client',
client_secret: 'test-secret',
redirect_uris: ['http://localhost/callback'],
+ token_endpoint_auth_method: 'client_secret_post',
},
+ storedTokenEndpoint: `${recorder.url}token`,
+ storedAuthMethods: ['client_secret_post'],
},
{},
{
@@ -229,7 +235,10 @@ describe('MCP OAuth audience parameter', () => {
client_id: 'test-client',
client_secret: 'test-secret',
redirect_uris: ['http://localhost/callback'],
+ token_endpoint_auth_method: 'client_secret_post',
},
+ storedTokenEndpoint: `${recorder.url}token`,
+ storedAuthMethods: ['client_secret_post'],
},
{},
{
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthClientRegistrationReuse.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthClientRegistrationReuse.test.ts
index 68723ea099..fa4ada0443 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthClientRegistrationReuse.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthClientRegistrationReuse.test.ts
@@ -124,7 +124,7 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
expect(server.registeredClients.size).toBe(1);
const firstClientId = firstResult.flowMetadata.clientInfo?.client_id;
- await MCPTokenStorage.storeTokens({
+ const storedTokens = await MCPTokenStorage.storeTokens({
userId: 'user-1',
serverName: 'test-server',
tokens: { access_token: 'test-token', token_type: 'Bearer' },
@@ -132,7 +132,12 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
updateToken: tokenStore.updateToken,
findToken: tokenStore.findToken,
clientInfo: firstResult.flowMetadata.clientInfo,
- metadata: firstResult.flowMetadata.metadata,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ firstResult.flowMetadata.metadata,
+ firstResult.flowMetadata.resourceMetadata,
+ firstResult.flowMetadata.serverUrl,
+ firstResult.flowMetadata.clientSource,
+ ),
});
const secondResult = await MCPOAuthHandler.initiateOAuthFlow(
@@ -148,6 +153,51 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
expect(server.registeredClients.size).toBe(1);
expect(secondResult.flowMetadata.clientInfo?.client_id).toBe(firstClientId);
expect(secondResult.flowMetadata.reusedStoredClient).toBe(true);
+ expect(secondResult.flowMetadata.reusedClientCredentialSetId).toBe(
+ storedTokens.credential_set_id,
+ );
+ });
+
+ it('should re-register a legacy stored client without a credential generation', async () => {
+ server = await createOAuthMCPServer({ tokenTTLMs: 60000 });
+ const tokenStore = new InMemoryTokenStore();
+ const initialResult = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ );
+ const legacyClientInfo = initialResult.flowMetadata.clientInfo;
+ const binding = MCPOAuthHandler.buildStoredClientMetadata(
+ initialResult.flowMetadata.metadata,
+ initialResult.flowMetadata.resourceMetadata,
+ initialResult.flowMetadata.serverUrl,
+ initialResult.flowMetadata.clientSource,
+ );
+
+ await tokenStore.createToken({
+ userId: 'user-1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:test-server:client',
+ token: `enc:${JSON.stringify(legacyClientInfo)}`,
+ expiresIn: 86400,
+ metadata: binding ? { ...binding } : undefined,
+ });
+
+ const result = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ undefined,
+ undefined,
+ tokenStore.findToken,
+ );
+
+ expect(server.registeredClients.size).toBe(2);
+ expect(result.flowMetadata.clientInfo?.client_id).not.toBe(legacyClientInfo?.client_id);
+ expect(result.flowMetadata.reusedStoredClient).toBeUndefined();
+ expect(result.flowMetadata.reusedClientCredentialSetId).toBeUndefined();
});
it('should reuse the same client when two reconnections fire concurrently with pre-seeded token', async () => {
@@ -173,7 +223,12 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
updateToken: tokenStore.updateToken,
findToken: tokenStore.findToken,
clientInfo: initialResult.flowMetadata.clientInfo,
- metadata: initialResult.flowMetadata.metadata,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ initialResult.flowMetadata.metadata,
+ initialResult.flowMetadata.resourceMetadata,
+ initialResult.flowMetadata.serverUrl,
+ initialResult.flowMetadata.clientSource,
+ ),
});
const [resultA, resultB] = await Promise.all([
@@ -203,6 +258,55 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
expect(resultB.flowMetadata.clientInfo?.client_id).toBe(storedClientId);
});
+ it.each([
+ ['server URL', 'server_url', 'https://different-resource.example.com/mcp'],
+ ['token endpoint', 'token_endpoint', 'https://different-auth.example.com/token'],
+ ['resource indicator', 'resource', 'https://different-resource.example.com/'],
+ ['client provenance', 'client_source', 'configured'],
+ ] as const)('should re-register for a stored %s mismatch', async (_label, field, badValue) => {
+ server = await createOAuthMCPServer({ tokenTTLMs: 60000 });
+ const tokenStore = new InMemoryTokenStore();
+ const initialResult = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ );
+ const initialClientId = initialResult.flowMetadata.clientInfo?.client_id;
+ const completeBinding = MCPOAuthHandler.buildStoredClientMetadata(
+ initialResult.flowMetadata.metadata,
+ initialResult.flowMetadata.resourceMetadata,
+ initialResult.flowMetadata.serverUrl,
+ initialResult.flowMetadata.clientSource,
+ );
+ expect(completeBinding).toBeDefined();
+
+ await MCPTokenStorage.storeTokens({
+ userId: 'user-1',
+ serverName: 'test-server',
+ tokens: { access_token: 'old-token', token_type: 'Bearer' },
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ findToken: tokenStore.findToken,
+ clientInfo: initialResult.flowMetadata.clientInfo,
+ metadata: { ...completeBinding, [field]: badValue },
+ });
+
+ const result = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ undefined,
+ undefined,
+ tokenStore.findToken,
+ );
+
+ expect(server.registeredClients.size).toBe(2);
+ expect(result.flowMetadata.clientInfo?.client_id).not.toBe(initialClientId);
+ expect(result.flowMetadata.reusedStoredClient).toBeUndefined();
+ });
+
it('should re-register when stored redirect_uri differs from current', async () => {
server = await createOAuthMCPServer({ tokenTTLMs: 60000 });
const tokenStore = new InMemoryTokenStore();
@@ -293,7 +397,7 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
// Seed a stored client with a client_id that the OAuth server doesn't recognize,
// but with matching issuer and redirect_uri so reuse logic accepts it
const serverIssuer = `http://127.0.0.1:${server.port}`;
- await MCPTokenStorage.storeTokens({
+ const storedTokens = await MCPTokenStorage.storeTokens({
userId: 'user-1',
serverName: 'test-server',
tokens: { access_token: 'old-token', token_type: 'Bearer' },
@@ -309,6 +413,9 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
issuer: serverIssuer,
authorization_endpoint: `${serverIssuer}/authorize`,
token_endpoint: `${serverIssuer}/token`,
+ server_url: server.url,
+ client_source: 'dynamic',
+ resource: server.resourceUrl,
},
});
@@ -326,6 +433,9 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
'stale-client-that-oauth-server-deleted',
);
expect(firstResult.flowMetadata.reusedStoredClient).toBe(true);
+ expect(firstResult.flowMetadata.reusedClientCredentialSetId).toBe(
+ storedTokens.credential_set_id,
+ );
expect(server.registeredClients.size).toBe(0);
// Simulate what MCPConnectionFactory does on failure when reusedStoredClient is set:
@@ -334,6 +444,7 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
userId: 'user-1',
serverName: 'test-server',
deleteTokens: tokenStore.deleteTokens,
+ credentialSetId: firstResult.flowMetadata.reusedClientCredentialSetId,
});
// Second attempt (retry after failure): should do a fresh DCR
@@ -354,9 +465,101 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
expect(secondResult.flowMetadata.reusedStoredClient).toBeUndefined();
});
+ it('should not let a stale rejected flow delete a newer client generation', async () => {
+ server = await createOAuthMCPServer({ tokenTTLMs: 60000 });
+ const tokenStore = new InMemoryTokenStore();
+
+ const registeredA = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ );
+ const storedA = await MCPTokenStorage.storeTokens({
+ userId: 'user-1',
+ serverName: 'test-server',
+ tokens: { access_token: 'access-a', token_type: 'Bearer' },
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ findToken: tokenStore.findToken,
+ clientInfo: registeredA.flowMetadata.clientInfo,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ registeredA.flowMetadata.metadata,
+ registeredA.flowMetadata.resourceMetadata,
+ registeredA.flowMetadata.serverUrl,
+ registeredA.flowMetadata.clientSource,
+ ),
+ });
+ const staleFlowA = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ undefined,
+ undefined,
+ tokenStore.findToken,
+ );
+ expect(staleFlowA.flowMetadata.reusedClientCredentialSetId).toBe(storedA.credential_set_id);
+
+ const registeredB = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ );
+ const storedB = await MCPTokenStorage.storeTokens({
+ userId: 'user-1',
+ serverName: 'test-server',
+ tokens: { access_token: 'access-b', token_type: 'Bearer' },
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ findToken: tokenStore.findToken,
+ clientInfo: registeredB.flowMetadata.clientInfo,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ registeredB.flowMetadata.metadata,
+ registeredB.flowMetadata.resourceMetadata,
+ registeredB.flowMetadata.serverUrl,
+ registeredB.flowMetadata.clientSource,
+ ),
+ });
+
+ await MCPTokenStorage.deleteClientRegistration({
+ userId: 'user-1',
+ serverName: 'test-server',
+ deleteTokens: tokenStore.deleteTokens,
+ credentialSetId: staleFlowA.flowMetadata.reusedClientCredentialSetId,
+ });
+
+ const currentClient = await MCPTokenStorage.getClientInfoAndMetadata({
+ userId: 'user-1',
+ serverName: 'test-server',
+ findToken: tokenStore.findToken,
+ });
+ expect(currentClient?.clientInfo.client_id).toBe(
+ registeredB.flowMetadata.clientInfo?.client_id,
+ );
+ expect(currentClient?.clientMetadata?.credential_set_id).toBe(storedB.credential_set_id);
+
+ const nextFlow = await MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ server.url,
+ 'user-1',
+ {},
+ undefined,
+ undefined,
+ tokenStore.findToken,
+ );
+ expect(server.registeredClients.size).toBe(2);
+ expect(nextFlow.flowMetadata.clientInfo?.client_id).toBe(
+ registeredB.flowMetadata.clientInfo?.client_id,
+ );
+ expect(nextFlow.flowMetadata.reusedClientCredentialSetId).toBe(storedB.credential_set_id);
+ });
+
it('should re-register when stored client was issued by a different authorization server', async () => {
server = await createOAuthMCPServer({ tokenTTLMs: 60000 });
const tokenStore = new InMemoryTokenStore();
+ const currentIssuer = `http://127.0.0.1:${server.port}`;
// Seed a stored client that was registered with a different issuer
await MCPTokenStorage.storeTokens({
@@ -373,8 +576,11 @@ describe('MCPOAuthHandler - client registration reuse on reconnection', () => {
} as OAuthClientInformation & { redirect_uris: string[] },
metadata: {
issuer: 'https://old-auth-server.example.com',
- authorization_endpoint: 'https://old-auth-server.example.com/authorize',
- token_endpoint: 'https://old-auth-server.example.com/token',
+ authorization_endpoint: `${currentIssuer}/authorize`,
+ token_endpoint: `${currentIssuer}/token`,
+ server_url: server.url,
+ client_source: 'dynamic',
+ resource: server.resourceUrl,
},
});
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthFlow.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthFlow.test.ts
index 545540ee57..d7507c1036 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthFlow.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthFlow.test.ts
@@ -5,14 +5,14 @@
* using a real test OAuth server (not mocked SDK functions).
*/
-import { createHash } from 'crypto';
import { Keyv } from 'keyv';
+import { createHash } from 'crypto';
import { TokenExchangeMethodEnum } from 'librechat-data-provider';
-import { MCPTokenStorage, MCPOAuthHandler } from '~/mcp/oauth';
-import { FlowStateManager } from '~/flow/manager';
-import { createOAuthMCPServer, MockKeyv, InMemoryTokenStore } from './helpers/oauthTestServer';
import type { OAuthTestServer } from './helpers/oauthTestServer';
import type { MCPOAuthTokens } from '~/mcp/oauth';
+import { createOAuthMCPServer, MockKeyv, InMemoryTokenStore } from './helpers/oauthTestServer';
+import { MCPTokenStorage, MCPOAuthHandler } from '~/mcp/oauth';
+import { FlowStateManager } from '~/flow/manager';
jest.mock('@librechat/data-schemas', () => ({
logger: {
@@ -89,7 +89,10 @@ describe('MCP OAuth Flow — Real HTTP Server', () => {
clientInfo: {
...clientInfo,
redirect_uris: ['http://localhost/callback'],
+ token_endpoint_auth_method: 'client_secret_post',
},
+ storedTokenEndpoint: `${server.url}token`,
+ storedAuthMethods: ['client_secret_post'],
},
{},
{
@@ -272,6 +275,13 @@ describe('MCP OAuth Flow — Real HTTP Server', () => {
serverName: 'test-srv',
tokens: initial,
createToken: tokenStore.createToken,
+ clientInfo: { client_id: 'test-client' },
+ metadata: {
+ authorization_endpoint: `${server.url}authorize`,
+ token_endpoint: `${server.url}token`,
+ server_url: server.url,
+ client_source: 'dynamic',
+ },
});
// 3. Retrieve — should succeed
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts
index 71e0c49f0b..169eb2b423 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts
@@ -744,6 +744,7 @@ describe('MCP OAuth Race Condition Fixes', () => {
it('should not throw when access token is valid', async () => {
const futureDate = new Date(Date.now() + 3600000);
+ const credentialSetId = 'valid-access-credential-set';
const findToken = jest.fn().mockImplementation(async (filter: { type?: string }) => {
if (filter.type === 'mcp_oauth') {
@@ -751,11 +752,24 @@ describe('MCP OAuth Race Condition Fixes', () => {
token: 'enc:valid-access-token',
expiresAt: futureDate,
createdAt: new Date(),
+ metadata: { credential_set_id: credentialSetId },
};
}
if (filter.type === 'mcp_oauth_refresh') {
return null;
}
+ if (filter.type === 'mcp_oauth_client') {
+ return {
+ token: 'enc:{"client_id":"test-client"}',
+ metadata: {
+ credential_set_id: credentialSetId,
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ server_url: 'https://mcp.example.com/',
+ client_source: 'dynamic',
+ },
+ };
+ }
return null;
});
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts
index d50e29eab7..0911c81975 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthSecurity.test.ts
@@ -12,8 +12,8 @@
* exempts trusted domains from SSRF checks, including auto-discovery paths.
*/
-import * as http from 'http';
import * as net from 'net';
+import * as http from 'http';
import { TokenExchangeMethodEnum } from 'librechat-data-provider';
import type { Socket } from 'net';
import type { OAuthTestServer } from './helpers/oauthTestServer';
@@ -142,7 +142,10 @@ describe('MCP OAuth SSRF protection', () => {
clientInfo: {
...clientInfo,
redirect_uris: ['http://localhost/callback'],
+ token_endpoint_auth_method: 'client_secret_post',
},
+ storedTokenEndpoint: ssrfTokenUrl,
+ storedAuthMethods: ['client_secret_post'],
},
{},
{
@@ -358,6 +361,8 @@ describe('MCP OAuth allowedDomains SSRF exemption for admin-trusted hosts', () =
client_secret: 'client-secret',
redirect_uris: ['http://localhost:3080/callback'],
},
+ storedTokenEndpoint: 'http://localhost:8080/token',
+ storedAuthMethods: ['client_secret_basic'],
},
{},
{
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
index dad34d31be..340d11dee8 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
@@ -32,6 +32,30 @@ jest.mock('@librechat/data-schemas', () => ({
decryptV2: jest.fn(async (val: string) => val.replace(/^enc:/, '')),
}));
+const credentialSetId = 'token-expiry-credential-set';
+const tokenMetadata = { credential_set_id: credentialSetId };
+
+function bindingMetadata(serverUrl: string) {
+ return {
+ authorization_endpoint: new URL('authorize', serverUrl).href,
+ token_endpoint: new URL('token', serverUrl).href,
+ server_url: new URL(serverUrl).href,
+ client_source: 'dynamic' as const,
+ resource: new URL(serverUrl).href,
+ };
+}
+
+async function seedStoredClient(tokenStore: InMemoryTokenStore, serverUrl: string) {
+ await tokenStore.createToken({
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:test-srv:client',
+ token: 'enc:{"client_id":"test-client"}',
+ expiresIn: 86400,
+ metadata: { ...tokenMetadata, ...bindingMetadata(serverUrl) },
+ });
+}
+
describe('MCP OAuth Token Expiry Scenarios', () => {
afterEach(() => {
jest.clearAllMocks();
@@ -75,6 +99,7 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv',
token: `enc:${initial.access_token}`,
expiresIn: -1,
+ metadata: tokenMetadata,
});
await tokenStore.createToken({
userId: 'u1',
@@ -82,7 +107,9 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv:refresh',
token: `enc:${initial.refresh_token}`,
expiresIn: 86400,
+ metadata: tokenMetadata,
});
+ await seedStoredClient(tokenStore, server.url);
const refreshCallback = async (refreshToken: string): Promise<MCPOAuthTokens> => {
const res = await fetch(`${server.url}token`, {
@@ -174,6 +201,7 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv',
token: `enc:${initial.access_token}`,
expiresIn: -1,
+ metadata: tokenMetadata,
});
await tokenStore.createToken({
userId: 'u1',
@@ -181,7 +209,9 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv:refresh',
token: `enc:${initial.refresh_token}`,
expiresIn: 86400,
+ metadata: tokenMetadata,
});
+ await seedStoredClient(tokenStore, server.url);
// Simulate server revoking the refresh token
server.issuedRefreshTokens.clear();
@@ -226,6 +256,7 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv',
token: 'enc:expired-token',
expiresIn: -1,
+ metadata: tokenMetadata,
});
await tokenStore.createToken({
userId: 'u1',
@@ -233,7 +264,9 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv:refresh',
token: 'enc:some-refresh-token',
expiresIn: 86400,
+ metadata: tokenMetadata,
});
+ await seedStoredClient(tokenStore, 'https://mcp.example.com/');
const refreshCallback = jest
.fn()
@@ -408,6 +441,8 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
serverName: 'test-srv',
tokens: initial,
createToken: tokenStore.createToken,
+ clientInfo: { client_id: 'test-client' },
+ metadata: bindingMetadata(server.url),
});
// Step 3: Verify tokens work
@@ -498,6 +533,8 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
createToken: tokenStore.createToken,
updateToken: tokenStore.updateToken,
findToken: tokenStore.findToken,
+ clientInfo: { client_id: 'test-client' },
+ metadata: bindingMetadata(server.url),
});
// Step 11: Verify new tokens work
@@ -542,6 +579,7 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv',
token: 'enc:expired-token',
expiresIn: -1,
+ metadata: tokenMetadata,
});
await tokenStore.createToken({
userId: 'u1',
@@ -549,7 +587,9 @@ describe('MCP OAuth Token Expiry Scenarios', () => {
identifier: 'mcp:test-srv:refresh',
token: 'enc:valid-refresh',
expiresIn: 86400,
+ metadata: tokenMetadata,
});
+ await seedStoredClient(tokenStore, 'https://mcp.example.com/');
let refreshCallCount = 0;
const refreshCallback = jest.fn().mockImplementation(async () => {
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
index 628ca202b4..eb75db12de 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts
@@ -10,6 +10,26 @@ import type { MCPOAuthTokens } from '~/mcp/oauth';
import { MCPTokenStorage, ReauthenticationRequiredError } from '~/mcp/oauth';
import { InMemoryTokenStore } from './helpers/oauthTestServer';
+const credentialSetId = 'credential-set-a';
+const storedTokenMetadata = { credential_set_id: credentialSetId };
+const storedBindingMetadata = {
+ ...storedTokenMetadata,
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ server_url: 'https://mcp.example.com/',
+ client_source: 'dynamic',
+} as const;
+
+function createBoundToken(
+ store: InMemoryTokenStore,
+ data: Parameters<InMemoryTokenStore['createToken']>[0],
+) {
+ return store.createToken({
+ ...data,
+ metadata: { ...storedTokenMetadata, ...(data.metadata ?? {}) },
+ });
+}
+
jest.mock('@librechat/data-schemas', () => ({
logger: {
info: jest.fn(),
@@ -30,7 +50,537 @@ describe('MCPTokenStorage', () => {
jest.clearAllMocks();
});
+ describe('isCurrentAccessToken', () => {
+ it('rejects a flow-cached token after persistent storage has rotated it', async () => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:new-token',
+ expiresIn: 3600,
+ });
+
+ await expect(
+ MCPTokenStorage.isCurrentAccessToken({
+ userId: 'u1',
+ serverName: 'srv1',
+ accessToken: 'old-cached-token',
+ credentialSetId,
+ findToken: store.findToken,
+ }),
+ ).resolves.toBe(false);
+ await expect(
+ MCPTokenStorage.isCurrentAccessToken({
+ userId: 'u1',
+ serverName: 'srv1',
+ accessToken: 'new-token',
+ credentialSetId,
+ findToken: store.findToken,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it('rejects the same token value after its credential generation changes', async () => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:same-token',
+ expiresIn: 3600,
+ metadata: { credential_set_id: 'credential-set-b' },
+ });
+
+ await expect(
+ MCPTokenStorage.isCurrentAccessToken({
+ userId: 'u1',
+ serverName: 'srv1',
+ accessToken: 'same-token',
+ credentialSetId,
+ findToken: store.findToken,
+ }),
+ ).resolves.toBe(false);
+ });
+ });
+
describe('storeTokens', () => {
+ it('keeps the trusted flow generation when provider metadata supplies a conflicting ID', async () => {
+ const result = await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'at1',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'credential-set-from-flow',
+ },
+ createToken: store.createToken,
+ clientInfo: { client_id: 'client-id' },
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'credential-set-from-metadata',
+ },
+ });
+
+ expect(result.credential_set_id).toBe('credential-set-from-flow');
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ metadata: expect.objectContaining({
+ credential_set_id: 'credential-set-from-flow',
+ }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ metadata: expect.objectContaining({
+ credential_set_id: 'credential-set-from-flow',
+ }),
+ }),
+ ]),
+ );
+ });
+
+ it('does not adopt a provider metadata generation when callback tokens lack one', async () => {
+ const result = await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: { access_token: 'at1', token_type: 'Bearer' },
+ createToken: store.createToken,
+ clientInfo: { client_id: 'client-id' },
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'provider-controlled-generation',
+ },
+ });
+
+ expect(result.credential_set_id).toEqual(expect.any(String));
+ expect(result.credential_set_id).not.toBe('provider-controlled-generation');
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ metadata: expect.objectContaining({
+ credential_set_id: result.credential_set_id,
+ }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ metadata: expect.objectContaining({
+ credential_set_id: result.credential_set_id,
+ }),
+ }),
+ ]),
+ );
+ });
+
+ it('rejects metadata that conflicts with the expected refresh generation', async () => {
+ const createToken = jest.fn();
+
+ await expect(
+ MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: { access_token: 'at1', token_type: 'Bearer' },
+ createToken,
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'different-generation',
+ },
+ expectedCredentialSetId: credentialSetId,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+ expect(createToken).not.toHaveBeenCalled();
+ });
+
+ it('rejects a stale write when the generation changes after prevalidation', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-a-access',
+ refresh_token: 'generation-a-refresh',
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ });
+
+ let replaced = false;
+ const interleavedUpdate = jest.fn(async (...args: Parameters<typeof store.updateToken>) => {
+ if (!replaced) {
+ replaced = true;
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-b',
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-b', client_secret: 'secret-b' },
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'credential-set-b',
+ },
+ });
+ }
+ return await store.updateToken(...args);
+ }) as typeof store.updateToken;
+
+ await expect(
+ MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'late-generation-a-access',
+ refresh_token: 'late-generation-a-refresh',
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: interleavedUpdate,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ expectedCredentialSetId: credentialSetId,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+
+ expect(interleavedUpdate).toHaveBeenCalledTimes(1);
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ token: 'enc:generation-b-access',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_refresh',
+ token: 'enc:generation-b-refresh',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ token: expect.stringContaining('client-b'),
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ ]),
+ );
+ });
+
+ it('rolls back callback access when an interleaved refresh wins the next CAS', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-a-refreshed-access',
+ refresh_token: 'generation-a-refresh',
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ deleteTokens: store.deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ });
+
+ let injectedRefresh = false;
+ const interleavedUpdate = jest.fn(async (...args: Parameters<typeof store.updateToken>) => {
+ const updated = await store.updateToken(...args);
+ const [query] = args;
+ if (updated && !injectedRefresh && query.type === 'mcp_oauth') {
+ injectedRefresh = true;
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ token: 'enc:generation-a-refresh',
+ metadataCredentialSetId: credentialSetId,
+ },
+ {
+ token: 'enc:generation-a-rotated-refresh',
+ metadata: storedTokenMetadata,
+ },
+ );
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ metadataCredentialSetId: credentialSetId,
+ },
+ {
+ token: 'enc:{"client_id":"client-a-rotated","client_secret":"secret-a"}',
+ metadata: storedBindingMetadata,
+ },
+ );
+ }
+ return updated;
+ }) as typeof store.updateToken;
+
+ await expect(
+ MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-b',
+ },
+ createToken: store.createToken,
+ updateToken: interleavedUpdate,
+ deleteTokens: store.deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-b', client_secret: 'secret-b' },
+ metadata: storedBindingMetadata,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ token: 'enc:generation-a-refreshed-access',
+ metadata: expect.objectContaining({ credential_set_id: credentialSetId }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_refresh',
+ token: 'enc:generation-a-rotated-refresh',
+ metadata: expect.objectContaining({ credential_set_id: credentialSetId }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ token: expect.stringContaining('client-a-rotated'),
+ metadata: expect.objectContaining({ credential_set_id: credentialSetId }),
+ }),
+ ]),
+ );
+ });
+
+ it('does not roll back over a newer writer that supersedes the callback anchor', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-a-access',
+ refresh_token: 'generation-a-refresh',
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ deleteTokens: store.deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ });
+
+ let injectedNewerWriter = false;
+ const interleavedUpdate = jest.fn(async (...args: Parameters<typeof store.updateToken>) => {
+ const updated = await store.updateToken(...args);
+ const [query] = args;
+ if (updated && !injectedNewerWriter && query.type === 'mcp_oauth') {
+ injectedNewerWriter = true;
+ const generationCMetadata = { credential_set_id: 'credential-set-c' };
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:generation-b-access',
+ metadataCredentialSetId: 'credential-set-b',
+ },
+ { token: 'enc:generation-c-access', metadata: generationCMetadata },
+ );
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ metadataCredentialSetId: credentialSetId,
+ },
+ { token: 'enc:generation-c-refresh', metadata: generationCMetadata },
+ );
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ metadataCredentialSetId: credentialSetId,
+ },
+ {
+ token: 'enc:{"client_id":"client-c","client_secret":"secret-c"}',
+ metadata: { ...storedBindingMetadata, ...generationCMetadata },
+ },
+ );
+ }
+ return updated;
+ }) as typeof store.updateToken;
+
+ await expect(
+ MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-b',
+ },
+ createToken: store.createToken,
+ updateToken: interleavedUpdate,
+ deleteTokens: store.deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-b', client_secret: 'secret-b' },
+ metadata: storedBindingMetadata,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ token: 'enc:generation-c-access',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-c' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_refresh',
+ token: 'enc:generation-c-refresh',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-c' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ token: expect.stringContaining('client-c'),
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-c' }),
+ }),
+ ]),
+ );
+ });
+
+ it('fails closed without writes when access and client generations are already mixed', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-a-access',
+ refresh_token: 'generation-a-refresh',
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ deleteTokens: store.deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ });
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:generation-a-access',
+ metadataCredentialSetId: credentialSetId,
+ },
+ {
+ token: 'enc:crash-left-generation-b-access',
+ metadata: { credential_set_id: 'credential-set-b' },
+ },
+ );
+
+ const createToken = jest.fn(store.createToken);
+ const updateToken = jest.fn(store.updateToken);
+ const deleteTokens = jest.fn(store.deleteTokens);
+
+ await expect(
+ MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-c-access',
+ refresh_token: 'generation-c-refresh',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-c',
+ },
+ createToken,
+ updateToken,
+ deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-c', client_secret: 'secret-c' },
+ metadata: storedBindingMetadata,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+
+ expect(createToken).not.toHaveBeenCalled();
+ expect(updateToken).not.toHaveBeenCalled();
+ expect(deleteTokens).not.toHaveBeenCalled();
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ token: 'enc:crash-left-generation-b-access',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_refresh',
+ token: 'enc:generation-a-refresh',
+ metadata: expect.objectContaining({ credential_set_id: credentialSetId }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ token: expect.stringContaining('client-a'),
+ metadata: expect.objectContaining({ credential_set_id: credentialSetId }),
+ }),
+ ]),
+ );
+ });
+
+ it('deletes its own created records when a later create fails', async () => {
+ const createToken = jest.fn(async (data) => {
+ if (data.type === 'mcp_oauth_refresh') {
+ throw new Error('refresh create failed');
+ }
+ return await store.createToken(data);
+ }) as typeof store.createToken;
+ const deleteTokens = jest.fn(store.deleteTokens);
+
+ await expect(
+ MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'new-access',
+ refresh_token: 'new-refresh',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-new',
+ },
+ createToken,
+ deleteTokens,
+ }),
+ ).rejects.toThrow('refresh create failed');
+
+ expect(store.getAll()).toHaveLength(0);
+ expect(deleteTokens).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ token: 'enc:new-access',
+ metadataCredentialSetId: 'credential-set-new',
+ }),
+ );
+ });
+
it('should create new access token with expires_in', async () => {
await MCPTokenStorage.storeTokens({
userId: 'u1',
@@ -94,7 +644,7 @@ describe('MCPTokenStorage', () => {
});
it('should update existing access token', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
@@ -222,8 +772,19 @@ describe('MCPTokenStorage', () => {
});
describe('getTokens', () => {
+ beforeEach(async () => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ token: 'enc:{"client_id":"cid"}',
+ expiresIn: 86400,
+ metadata: storedBindingMetadata,
+ });
+ });
+
it('should return valid non-expired tokens', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
@@ -242,15 +803,60 @@ describe('MCPTokenStorage', () => {
expect(result!.token_type).toBe('Bearer');
});
+ it('rejects an access token read before a concurrent client generation replacement', async () => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:generation-a-access',
+ expiresIn: 3600,
+ });
+ let replaced = false;
+ const interleavedFind = jest.fn(async (query) => {
+ const result = await store.findToken(query);
+ if (!replaced && query.type === 'mcp_oauth') {
+ replaced = true;
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:generation-b-access',
+ expiresIn: 3600,
+ metadata: { credential_set_id: 'credential-set-b' },
+ });
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ token: 'enc:{"client_id":"client-b"}',
+ expiresIn: 86400,
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'credential-set-b',
+ },
+ });
+ }
+ return result;
+ }) as typeof store.findToken;
+
+ await expect(
+ MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: interleavedFind,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+ });
+
it('should return tokens with refresh token when available', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:at',
expiresIn: 3600,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -268,7 +874,7 @@ describe('MCPTokenStorage', () => {
});
it('should return tokens without refresh token field when none stored', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
@@ -286,7 +892,7 @@ describe('MCPTokenStorage', () => {
});
it('should throw ReauthenticationRequiredError when expired and no refresh', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
@@ -314,14 +920,14 @@ describe('MCPTokenStorage', () => {
});
it('should refresh expired access token when refresh token and callback are available', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -356,14 +962,14 @@ describe('MCPTokenStorage', () => {
});
it('should return null when refresh fails', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -386,14 +992,14 @@ describe('MCPTokenStorage', () => {
});
it('should return null when no refreshTokens callback provided', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -411,14 +1017,14 @@ describe('MCPTokenStorage', () => {
});
it('should return null when no createToken callback provided', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -437,26 +1043,27 @@ describe('MCPTokenStorage', () => {
});
it('should pass client info to refreshTokens metadata', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
token: 'enc:rt',
expiresIn: 86400,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_client',
identifier: 'mcp:srv1:client',
token: 'enc:{"client_id":"cid","client_secret":"csec"}',
expiresIn: 86400,
+ metadata: storedBindingMetadata,
});
const refreshTokens = jest.fn().mockResolvedValue({
@@ -486,14 +1093,14 @@ describe('MCPTokenStorage', () => {
it('should handle unauthorized_client refresh error', async () => {
const { logger } = await import('@librechat/data-schemas');
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -518,26 +1125,27 @@ describe('MCPTokenStorage', () => {
});
it('should delete client registration and refresh token on invalid_client when deleteTokens provided', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
token: 'enc:rt',
expiresIn: 86400,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_client',
identifier: 'mcp:srv1:client',
token: 'enc:{"client_id":"cid"}',
expiresIn: 86400,
+ metadata: storedBindingMetadata,
});
const refreshTokens = jest.fn().mockRejectedValue(new Error('invalid_client'));
@@ -576,14 +1184,14 @@ describe('MCPTokenStorage', () => {
it('should return null and log warning on invalid_client when deleteTokens not provided', async () => {
const { logger } = await import('@librechat/data-schemas');
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -608,26 +1216,27 @@ describe('MCPTokenStorage', () => {
});
it('should handle client_not_found and other vendor-specific rejection patterns', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
token: 'enc:rt',
expiresIn: 86400,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_client',
identifier: 'mcp:srv1:client',
token: 'enc:{"client_id":"cid"}',
expiresIn: 86400,
+ metadata: storedBindingMetadata,
});
const refreshTokens = jest.fn().mockRejectedValue(new Error('client not found'));
@@ -660,14 +1269,14 @@ describe('MCPTokenStorage', () => {
});
it('should handle case-insensitive error messages for client rejection', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -690,14 +1299,14 @@ describe('MCPTokenStorage', () => {
});
it('should still throw ReauthenticationRequiredError when deleteClientRegistration fails', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
token: 'enc:expired-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -722,31 +1331,314 @@ describe('MCPTokenStorage', () => {
});
describe('forceRefreshTokens', () => {
- it('should refresh and store tokens even when access token is not locally expired', async () => {
- // Access token still has time on the clock (1 hour), but the server has
- // invalidated it (we simulate a mid-session 401 by calling forceRefreshTokens
- // directly). The local `expires_at` must be ignored — the 401 is the signal.
- await store.createToken({
+ beforeEach(async () => {
+ await createBoundToken(store, {
userId: 'u1',
- type: 'mcp_oauth',
- identifier: 'mcp:srv1',
- token: 'enc:stale-access-token',
- expiresIn: 3600,
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ token: 'enc:{"client_id":"cid"}',
+ expiresIn: 86400,
+ metadata: storedBindingMetadata,
});
- await store.createToken({
+ });
+
+ it('fails closed before invoking refresh for legacy client metadata', async () => {
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
token: 'enc:rt',
expiresIn: 86400,
});
-
- const refreshTokens = jest.fn().mockResolvedValue({
- access_token: 'new-access-token',
- refresh_token: 'new-rt',
- token_type: 'Bearer',
- expires_in: 3600,
- obtained_at: Date.now(),
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ token: 'enc:{"client_id":"legacy-client"}',
+ expiresIn: 86400,
+ });
+ const refreshTokens = jest.fn();
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ createToken: store.createToken,
+ refreshTokens,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it('does not send a refresh token read before a concurrent client generation replacement', async () => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ token: 'enc:generation-a-refresh',
+ expiresIn: 86400,
+ });
+ let replaced = false;
+ const interleavedFind = jest.fn(async (query) => {
+ const result = await store.findToken(query);
+ if (!replaced && query.type === 'mcp_oauth_refresh') {
+ replaced = true;
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:srv1:client',
+ token: 'enc:{"client_id":"client-b","client_secret":"secret-b"}',
+ expiresIn: 86400,
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'credential-set-b',
+ },
+ });
+ }
+ return result;
+ }) as typeof store.findToken;
+ const refreshTokens = jest.fn();
+
+ await expect(
+ MCPTokenStorage.forceRefreshTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: interleavedFind,
+ createToken: store.createToken,
+ refreshTokens,
+ }),
+ ).rejects.toThrow(ReauthenticationRequiredError);
+
+ expect(refreshTokens).not.toHaveBeenCalled();
+ });
+
+ it('does not persist a late refresh after interactive authorization replaces its generation', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-a-access',
+ refresh_token: 'generation-a-refresh',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ });
+
+ let markRefreshStarted!: () => void;
+ const refreshStarted = new Promise<void>((resolve) => {
+ markRefreshStarted = resolve;
+ });
+ let finishRefresh!: (tokens: MCPOAuthTokens) => void;
+ const refreshResponse = new Promise<MCPOAuthTokens>((resolve) => {
+ finishRefresh = resolve;
+ });
+ const refreshTokens = jest.fn(async () => {
+ markRefreshStarted();
+ return await refreshResponse;
+ });
+ const staleCreateToken = jest.fn(store.createToken);
+ const staleUpdateToken = jest.fn(store.updateToken);
+
+ const staleRefresh = MCPTokenStorage.forceRefreshTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ createToken: staleCreateToken,
+ updateToken: staleUpdateToken,
+ refreshTokens,
+ });
+ let staleRefreshError: unknown;
+ const observedStaleRefresh = staleRefresh.catch((error) => {
+ staleRefreshError = error;
+ });
+ await refreshStarted;
+
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ credential_set_id: 'credential-set-b',
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-b', client_secret: 'secret-b' },
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'credential-set-b',
+ },
+ });
+
+ finishRefresh({
+ access_token: 'late-generation-a-access',
+ refresh_token: 'late-generation-a-refresh',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ });
+ await observedStaleRefresh;
+ expect(staleRefreshError).toBeInstanceOf(ReauthenticationRequiredError);
+
+ expect(staleCreateToken).not.toHaveBeenCalled();
+ expect(staleUpdateToken).not.toHaveBeenCalled();
+ const storedRecords = store.getAll().filter((record) => record.userId === 'u1');
+ expect(storedRecords).toHaveLength(3);
+ expect(storedRecords).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ token: 'enc:generation-b-access',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_refresh',
+ token: 'enc:generation-b-refresh',
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ token: expect.stringContaining('client-b'),
+ metadata: expect.objectContaining({ credential_set_id: 'credential-set-b' }),
+ }),
+ ]),
+ );
+ await expect(
+ MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ }),
+ ).resolves.toMatchObject({
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ credential_set_id: 'credential-set-b',
+ });
+ });
+
+ it('does not delete a newer generation when a late refresh rejects the old client', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-a-access',
+ refresh_token: 'generation-a-refresh',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-a', client_secret: 'secret-a' },
+ metadata: storedBindingMetadata,
+ });
+
+ let markRefreshStarted!: () => void;
+ const refreshStarted = new Promise<void>((resolve) => {
+ markRefreshStarted = resolve;
+ });
+ let rejectRefresh!: (error: Error) => void;
+ const refreshResponse = new Promise<MCPOAuthTokens>((_resolve, reject) => {
+ rejectRefresh = reject;
+ });
+ const refreshTokens = jest.fn(async () => {
+ markRefreshStarted();
+ return await refreshResponse;
+ });
+ const deleteTokens = jest.fn(store.deleteTokens);
+ const staleRefresh = MCPTokenStorage.forceRefreshTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ deleteTokens,
+ refreshTokens,
+ });
+ let staleRefreshError: unknown;
+ const observedStaleRefresh = staleRefresh.catch((error) => {
+ staleRefreshError = error;
+ });
+ await refreshStarted;
+
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ credential_set_id: 'credential-set-b',
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'client-b', client_secret: 'secret-b' },
+ metadata: {
+ ...storedBindingMetadata,
+ credential_set_id: 'credential-set-b',
+ },
+ });
+
+ rejectRefresh(new Error('invalid_client'));
+ await observedStaleRefresh;
+ expect(staleRefreshError).toBeInstanceOf(ReauthenticationRequiredError);
+
+ expect(deleteTokens).toHaveBeenCalledTimes(2);
+ expect(deleteTokens).toHaveBeenCalledWith(
+ expect.objectContaining({ metadataCredentialSetId: credentialSetId }),
+ );
+ await expect(
+ MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ }),
+ ).resolves.toMatchObject({
+ access_token: 'generation-b-access',
+ refresh_token: 'generation-b-refresh',
+ credential_set_id: 'credential-set-b',
+ });
+ expect(store.getAll().filter((record) => record.userId === 'u1')).toHaveLength(3);
+ });
+
+ it('should refresh and store tokens even when access token is not locally expired', async () => {
+ // Access token still has time on the clock (1 hour), but the server has
+ // invalidated it (we simulate a mid-session 401 by calling forceRefreshTokens
+ // directly). The local `expires_at` must be ignored — the 401 is the signal.
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:srv1',
+ token: 'enc:stale-access-token',
+ expiresIn: 3600,
+ });
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ token: 'enc:rt',
+ expiresIn: 86400,
+ });
+
+ const refreshTokens = jest.fn().mockResolvedValue({
+ access_token: 'new-access-token',
+ refresh_token: 'new-rt',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ obtained_at: Date.now(),
});
const result = await MCPTokenStorage.forceRefreshTokens({
@@ -761,6 +1653,8 @@ describe('MCPTokenStorage', () => {
expect(result).not.toBeNull();
expect(result!.access_token).toBe('new-access-token');
+ expect(result!.credential_set_id).toEqual(expect.any(String));
+ expect(result!.credential_set_id).not.toBe(credentialSetId);
expect(refreshTokens).toHaveBeenCalledWith(
'rt',
expect.objectContaining({
@@ -778,12 +1672,34 @@ describe('MCPTokenStorage', () => {
identifier: 'mcp:srv1',
});
expect(saved!.token).toBe('enc:new-access-token');
+ expect(store.getAll()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mcp_oauth',
+ metadata: expect.objectContaining({
+ credential_set_id: result!.credential_set_id,
+ }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_refresh',
+ metadata: expect.objectContaining({
+ credential_set_id: result!.credential_set_id,
+ }),
+ }),
+ expect.objectContaining({
+ type: 'mcp_oauth_client',
+ metadata: expect.objectContaining({
+ credential_set_id: result!.credential_set_id,
+ }),
+ }),
+ ]),
+ );
});
it('should return null when no refresh token is stored', async () => {
// Access token exists locally, but no refresh token. Silent refresh is
// not possible — the caller must fall back to interactive OAuth.
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: 'mcp:srv1',
@@ -806,7 +1722,7 @@ describe('MCPTokenStorage', () => {
});
it('should return null when refresh callback throws non-client-rejection error', async () => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
@@ -830,19 +1746,20 @@ describe('MCPTokenStorage', () => {
it('should throw ReauthenticationRequiredError when refresh fails with invalid_client', async () => {
// Mirrors the contract that getTokens has on stale client registration —
// forceRefreshTokens cleans up the stale state and signals re-auth.
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: 'mcp:srv1:refresh',
token: 'enc:rt',
expiresIn: 86400,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_client',
identifier: 'mcp:srv1:client',
token: 'enc:{"client_id":"cid"}',
expiresIn: 86400,
+ metadata: storedBindingMetadata,
});
const refreshTokens = jest.fn().mockRejectedValue(new Error('invalid_client'));
@@ -869,22 +1786,30 @@ describe('MCPTokenStorage', () => {
});
describe('forceRefreshTokens concurrent coalescing (single-flight)', () => {
- /** Seeds an expired access token plus a refresh token for `serverName`. */
+ /** Seeds one coherent expired OAuth credential generation for `serverName`. */
const seedRefreshableTokens = async (serverName = 'srv1', refreshToken = 'rt-1') => {
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth',
identifier: `mcp:${serverName}`,
token: 'enc:expired-access-token',
expiresIn: -1,
});
- await store.createToken({
+ await createBoundToken(store, {
userId: 'u1',
type: 'mcp_oauth_refresh',
identifier: `mcp:${serverName}:refresh`,
token: `enc:${refreshToken}`,
expiresIn: 86400,
});
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: `mcp:${serverName}:client`,
+ token: 'enc:{"client_id":"cid","client_secret":"secret"}',
+ expiresIn: 86400,
+ metadata: storedBindingMetadata,
+ });
};
const rotatedTokens = (generation: number): MCPOAuthTokens => ({
@@ -901,6 +1826,7 @@ describe('MCPTokenStorage', () => {
findToken: store.findToken,
createToken: store.createToken,
updateToken: store.updateToken,
+ deleteTokens: store.deleteTokens,
refreshTokens,
});
@@ -1031,6 +1957,81 @@ describe('MCPTokenStorage', () => {
expect(result!.access_token).toBe('at-3');
});
+ it('re-reads an access token installed after the missing-token probe', async () => {
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:late-access-srv:refresh',
+ token: 'enc:rt-1',
+ expiresIn: 86400,
+ });
+ await createBoundToken(store, {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:late-access-srv:client',
+ token: 'enc:{"client_id":"cid","client_secret":"secret"}',
+ expiresIn: 86400,
+ metadata: storedBindingMetadata,
+ });
+
+ let accessProbeSeen = false;
+ const findToken = (async (filter: { type?: string }) => {
+ if (filter.type !== 'mcp_oauth' || accessProbeSeen) {
+ return store.findToken(filter as Parameters<InMemoryTokenStore['findToken']>[0]);
+ }
+
+ accessProbeSeen = true;
+ const generationB = { credential_set_id: 'credential-set-b' };
+ await store.createToken({
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:late-access-srv',
+ token: 'enc:interactive-access',
+ expiresIn: -1,
+ metadata: generationB,
+ });
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:late-access-srv:refresh',
+ metadataCredentialSetId: credentialSetId,
+ },
+ { token: 'enc:interactive-refresh', metadata: generationB },
+ );
+ await store.updateToken(
+ {
+ userId: 'u1',
+ type: 'mcp_oauth_client',
+ identifier: 'mcp:late-access-srv:client',
+ metadataCredentialSetId: credentialSetId,
+ },
+ {
+ token: 'enc:{"client_id":"cid","client_secret":"secret"}',
+ metadata: { ...storedBindingMetadata, ...generationB },
+ },
+ );
+ return null;
+ }) as TokenMethods['findToken'];
+ const createToken = jest.fn(store.createToken);
+ const refreshTokens = jest.fn().mockResolvedValue(rotatedTokens(3));
+
+ const result = await MCPTokenStorage.getTokens({
+ ...refreshParams(refreshTokens, 'late-access-srv'),
+ findToken,
+ createToken,
+ });
+
+ expect(result).toMatchObject({ access_token: 'at-3' });
+ expect(refreshTokens).toHaveBeenCalledWith(
+ 'interactive-refresh',
+ expect.any(Object),
+ expect.any(AbortSignal),
+ );
+ expect(createToken).not.toHaveBeenCalled();
+ expect(store.getAll().filter((token) => token.type === 'mcp_oauth')).toHaveLength(1);
+ });
+
it('does not cache results: a refresh after settlement triggers a fresh redemption', async () => {
await seedRefreshableTokens('sequential-srv');
@@ -1083,6 +2084,34 @@ describe('MCPTokenStorage', () => {
expect(secondResult!.access_token).toBe('at-5');
});
+ it('does not coalesce refreshes across different OAuth binding scopes', async () => {
+ await seedRefreshableTokens('scoped-srv');
+
+ const resolutions: Array<(tokens: MCPOAuthTokens) => void> = [];
+ const refreshTokens = jest.fn(
+ () =>
+ new Promise<MCPOAuthTokens>((resolve) => {
+ resolutions.push(resolve);
+ }),
+ );
+ const params = refreshParams(refreshTokens, 'scoped-srv');
+ const first = MCPTokenStorage.forceRefreshTokens({
+ ...params,
+ singleFlightScope: 'binding-a',
+ });
+ const second = MCPTokenStorage.forceRefreshTokens({
+ ...params,
+ singleFlightScope: 'binding-b',
+ });
+
+ await waitFor(() => refreshTokens.mock.calls.length === 2);
+ resolutions[0](rotatedTokens(2));
+ await expect(first).resolves.toMatchObject({ access_token: 'at-2' });
+ resolutions[1](rotatedTokens(3));
+ await expect(second).rejects.toThrow(ReauthenticationRequiredError);
+ expect(refreshTokens).toHaveBeenCalledTimes(2);
+ });
+
it('propagates refresh failure to all joined callers and releases the single-flight slot', async () => {
await seedRefreshableTokens('fail-srv');
@@ -1205,8 +2234,21 @@ describe('MCPTokenStorage', () => {
resolveRefresh(rotatedTokens(2));
await waitFor(() => onRefreshSuccess.mock.calls.length === 1);
expect(onRefreshSuccess).toHaveBeenCalledWith(
- expect.objectContaining({ access_token: 'at-2' }),
+ expect.objectContaining({
+ access_token: 'at-2',
+ credential_set_id: expect.any(String),
+ }),
);
+ const callbackTokens = onRefreshSuccess.mock.calls[0][0];
+ const storedAccess = store
+ .getAll()
+ .find((token) => token.type === 'mcp_oauth' && token.identifier === 'mcp:hook-srv');
+ const storedCredentialSetId =
+ storedAccess!.metadata instanceof Map
+ ? storedAccess!.metadata.get('credential_set_id')
+ : storedAccess!.metadata?.credential_set_id;
+ expect(callbackTokens.credential_set_id).toBe(storedCredentialSetId);
+ expect(callbackTokens.credential_set_id).not.toBe(credentialSetId);
});
it("an initiator's abort resolves only its own wait, not the shared redemption", async () => {
@@ -1270,13 +2312,6 @@ describe('MCPTokenStorage', () => {
it('propagates ReauthenticationRequiredError to concurrent callers', async () => {
await seedRefreshableTokens('reauth-srv');
- await store.createToken({
- userId: 'u1',
- type: 'mcp_oauth_client',
- identifier: 'mcp:reauth-srv:client',
- token: 'enc:{"client_id":"cid"}',
- expiresIn: 86400,
- });
let rejectRefresh!: (error: Error) => void;
const refreshTokens = jest.fn(
@@ -1327,6 +2362,125 @@ describe('MCPTokenStorage', () => {
expect(result!.token_type).toBe('Bearer');
expect(result!.obtained_at).toBeDefined();
expect(result!.expires_at).toBeDefined();
+ expect(result!.credential_set_id).toEqual(expect.any(String));
+ });
+
+ it('keeps a new access token usable while omitting a stale refresh generation', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'old-access',
+ refresh_token: 'old-refresh',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ clientInfo: { client_id: 'old-client', client_secret: 'old-secret' },
+ metadata: storedBindingMetadata,
+ });
+
+ const { credential_set_id: _oldCredentialSetId, ...newBindingMetadata } =
+ storedBindingMetadata;
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: { access_token: 'new-access', token_type: 'Bearer', expires_in: 3600 },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'new-client', client_secret: 'new-secret' },
+ metadata: newBindingMetadata,
+ });
+
+ const result = await MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ });
+ const refreshRecord = await store.findToken({
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ });
+
+ expect(result).toMatchObject({ access_token: 'new-access' });
+ expect(result!.refresh_token).toBeUndefined();
+ expect(result!.credential_set_id).not.toBe(credentialSetId);
+ expect(refreshRecord?.metadata).toMatchObject({ credential_set_id: credentialSetId });
+ });
+
+ it('removes the stale refresh generation after an interactive callback commits', async () => {
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'old-access',
+ refresh_token: 'old-refresh',
+ token_type: 'Bearer',
+ credential_set_id: credentialSetId,
+ },
+ createToken: store.createToken,
+ clientInfo: { client_id: 'old-client', client_secret: 'old-secret' },
+ metadata: storedBindingMetadata,
+ });
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'intermediate-access',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-b',
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'intermediate-client', client_secret: 'intermediate-secret' },
+ metadata: storedBindingMetadata,
+ });
+ const deleteTokens = jest.fn(store.deleteTokens);
+
+ const result = await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ tokens: {
+ access_token: 'new-access',
+ token_type: 'Bearer',
+ credential_set_id: 'credential-set-c',
+ },
+ createToken: store.createToken,
+ updateToken: store.updateToken,
+ deleteTokens,
+ findToken: store.findToken,
+ clientInfo: { client_id: 'new-client', client_secret: 'new-secret' },
+ metadata: storedBindingMetadata,
+ });
+
+ expect(deleteTokens).toHaveBeenCalledWith({
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ token: 'enc:old-refresh',
+ metadataCredentialSetId: credentialSetId,
+ });
+ await expect(
+ store.findToken({
+ userId: 'u1',
+ type: 'mcp_oauth_refresh',
+ identifier: 'mcp:srv1:refresh',
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'srv1',
+ findToken: store.findToken,
+ }),
+ ).resolves.toMatchObject({
+ access_token: 'new-access',
+ credential_set_id: result.credential_set_id,
+ });
});
});
});
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.ts
index d73a66a87b..c909437429 100644
--- a/packages/api/src/mcp/__tests__/handler.test.ts
+++ b/packages/api/src/mcp/__tests__/handler.test.ts
@@ -155,6 +155,12 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
expect(result.flowMetadata.resourceMetadata).toEqual(
expect.objectContaining({ resource: mockServerUrl }),
);
+ expect(result.flowMetadata.metadata).toEqual(
+ expect.objectContaining({
+ token_endpoint: baseConfig.token_url,
+ token_endpoint_auth_methods_supported: ['client_secret_post'],
+ }),
+ );
});
it('should discover capabilities from the configured authorization server origin', async () => {
@@ -458,6 +464,27 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
);
});
+ it('stores configured revocation metadata with the OAuth flow', async () => {
+ const result = await MCPOAuthHandler.initiateOAuthFlow(
+ mockServerName,
+ mockServerUrl,
+ mockUserId,
+ {},
+ {
+ ...baseConfig,
+ revocation_endpoint: 'https://auth.example.com/oauth/revoke',
+ revocation_endpoint_auth_methods_supported: ['client_secret_post'],
+ },
+ );
+
+ expect(result.flowMetadata.metadata).toEqual(
+ expect.objectContaining({
+ revocation_endpoint: 'https://auth.example.com/oauth/revoke',
+ revocation_endpoint_auth_methods_supported: ['client_secret_post'],
+ }),
+ );
+ });
+
it('should use custom code_challenge_methods_supported when provided', async () => {
const config = {
...baseConfig,
@@ -644,7 +671,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
client_secret: 'configured-client-secret',
},
),
- ).rejects.toThrow(/cannot be used with auto-discovered token endpoints/);
+ ).rejects.toThrow(/missing its bound token endpoint/);
expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();
});
@@ -677,20 +704,10 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
grant_types: ['authorization_code', 'refresh_token'],
scope: 'read write',
},
+ storedTokenEndpoint: 'https://auth.example.com/oauth/token',
+ storedAuthMethods: ['client_secret_post'],
};
- // Mock OAuth metadata discovery
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({
- issuer: 'https://auth.example.com',
- authorization_endpoint: 'https://auth.example.com/oauth/authorize',
- token_endpoint: 'https://auth.example.com/oauth/token',
- token_endpoint_auth_methods_supported: ['client_secret_post'],
- response_types_supported: ['code'],
- jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- } as AuthorizationServerMetadata);
-
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -813,20 +830,10 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
grant_types: ['authorization_code', 'refresh_token'],
scope: 'read write',
},
+ storedTokenEndpoint: 'https://auth.example.com/oauth/token',
+ storedAuthMethods: ['client_secret_basic'],
};
- // Mock OAuth metadata discovery
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({
- issuer: 'https://auth.example.com',
- authorization_endpoint: 'https://auth.example.com/oauth/authorize',
- token_endpoint: 'https://auth.example.com/oauth/token',
- token_endpoint_auth_methods_supported: ['client_secret_basic'],
- response_types_supported: ['code'],
- jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- } as AuthorizationServerMetadata);
-
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -862,20 +869,10 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
client_secret: 'test-client-secret',
grant_types: ['authorization_code', 'refresh_token'],
},
+ storedTokenEndpoint: 'https://auth.example.com/oauth/token',
+ storedAuthMethods: ['client_secret_post', 'client_secret_basic'],
};
- // Mock OAuth metadata discovery
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({
- issuer: 'https://auth.example.com',
- authorization_endpoint: 'https://auth.example.com/oauth/authorize',
- token_endpoint: 'https://auth.example.com/oauth/token',
- token_endpoint_auth_methods_supported: ['client_secret_post', 'client_secret_basic'],
- response_types_supported: ['code'],
- jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- } as AuthorizationServerMetadata);
-
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -909,20 +906,9 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
client_secret: 'test-client-secret',
grant_types: ['authorization_code', 'refresh_token'],
},
+ storedTokenEndpoint: 'https://auth.example.com/oauth/token',
};
- // Mock OAuth metadata discovery with no auth methods specified
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({
- issuer: 'https://auth.example.com',
- authorization_endpoint: 'https://auth.example.com/oauth/authorize',
- token_endpoint: 'https://auth.example.com/oauth/token',
- // No token_endpoint_auth_methods_supported field
- response_types_supported: ['code'],
- jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- } as AuthorizationServerMetadata);
-
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -1126,14 +1112,10 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
client_secret: 'test-client-secret',
grant_types: ['authorization_code', 'refresh_token'],
},
+ storedTokenEndpoint: 'https://auth.example.com/oauth/token',
+ storedAuthMethods: ['client_secret_post'],
};
- // Mock OAuth metadata discovery
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({
- token_endpoint: 'https://auth.example.com/oauth/token',
- token_endpoint_auth_methods_supported: ['client_secret_post'],
- } as AuthorizationServerMetadata);
-
mockFetch.mockResolvedValueOnce({
ok: false,
status: 400,
@@ -1149,11 +1131,11 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
);
});
- describe('stored token endpoint fallback', () => {
- it('uses stored token endpoint when discovery fails (stored clientInfo)', async () => {
+ describe('stored token endpoint binding', () => {
+ it('rejects a replacement confidential client binding before discovery or fetch', async () => {
const metadata = {
serverName: 'test-server',
- serverUrl: 'https://mcp.example.com',
+ serverUrl: 'https://attacker.example.com/mcp',
clientInfo: {
client_id: 'test-client-id',
client_secret: 'test-client-secret',
@@ -1162,29 +1144,240 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
storedAuthMethods: ['client_secret_basic'],
};
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce(undefined);
+ await expect(
+ MCPOAuthHandler.refreshOAuthTokens(
+ 'test-refresh-token',
+ metadata,
+ {},
+ {
+ token_url: 'https://attacker.example.com/token',
+ client_id: 'replacement-client-id',
+ client_secret: 'replacement-client-secret',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ token_endpoint_auth_methods_supported: ['client_secret_post'],
+ },
+ ),
+ ).rejects.toThrow('no longer matches current OAuth client configuration');
+
+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('rejects a transition from a stored confidential client to an explicit public client', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://mcp.example.com',
+ clientInfo: {
+ client_id: 'old-client-id',
+ client_secret: 'old-client-secret',
+ },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['client_secret_basic'],
+ };
+
+ await expect(
+ MCPOAuthHandler.refreshOAuthTokens(
+ 'test-refresh-token',
+ metadata,
+ {},
+ {
+ token_url: 'https://auth.example.com/token',
+ client_id: 'public-client-id',
+ },
+ ),
+ ).rejects.toThrow('no longer matches current OAuth client configuration');
+
+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('uses the stored endpoint and auth policy when the confidential binding still matches', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://mcp.example.com',
+ clientInfo: {
+ client_id: 'test-client-id',
+ client_secret: 'test-client-secret',
+ token_endpoint_auth_method: 'client_secret_basic',
+ },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['client_secret_basic'],
+ };
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
access_token: 'new-access-token',
- refresh_token: 'new-refresh-token',
expires_in: 3600,
}),
} as Response);
- const result = await MCPOAuthHandler.refreshOAuthTokens(
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'test-refresh-token',
+ metadata,
+ {},
+ {
+ token_url: 'https://auth.example.com:443/token',
+ client_id: 'test-client-id',
+ client_secret: 'test-client-secret',
+ token_exchange_method: TokenExchangeMethodEnum.BasicAuthHeader,
+ token_endpoint_auth_methods_supported: ['client_secret_post'],
+ },
+ );
+
+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://auth.example.com/token',
+ expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({
+ Authorization: `Basic ${Buffer.from('test-client-id:test-client-secret').toString(
+ 'base64',
+ )}`,
+ }),
+ }),
+ );
+ });
+
+ it('retains the discovered auth method when unchanged config has no explicit method policy', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://mcp.example.com',
+ clientInfo: {
+ client_id: 'test-client-id',
+ client_secret: 'test-client-secret',
+ token_endpoint_auth_method: 'client_secret_post',
+ },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['client_secret_post'],
+ };
+
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ access_token: 'new-access-token', expires_in: 3600 }),
+ } as Response);
+
+ await MCPOAuthHandler.refreshOAuthTokens(
'test-refresh-token',
metadata,
{},
+ {
+ token_url: 'https://auth.example.com/token',
+ client_id: 'test-client-id',
+ client_secret: 'test-client-secret',
+ },
+ );
+
+ const request = mockFetch.mock.calls[0][1];
+ expect(new Headers(request?.headers).has('Authorization')).toBe(false);
+ const body = request?.body as URLSearchParams;
+ expect(body.get('client_id')).toBe('test-client-id');
+ expect(body.get('client_secret')).toBe('test-client-secret');
+ });
+
+ it('rejects a dynamically registered client after the MCP server URL changes', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://attacker.example.com/mcp',
+ clientInfo: {
+ client_id: 'dynamically-registered-client-id',
+ client_secret: 'dynamically-registered-client-secret',
+ token_endpoint_auth_method: 'client_secret_post',
+ },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['client_secret_post'],
+ storedServerUrl: 'https://mcp.example.com/mcp',
+ clientSource: 'dynamic' as const,
+ };
+
+ await expect(
+ MCPOAuthHandler.refreshOAuthTokens('test-refresh-token', metadata, {}, undefined),
+ ).rejects.toThrow('no longer matches the current MCP server URL');
+
+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('rejects an edited token endpoint for a stored public configured client', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://mcp.example.com/mcp',
+ clientInfo: { client_id: 'public-client-id' },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['none'],
+ storedServerUrl: 'https://mcp.example.com/mcp',
+ clientSource: 'configured' as const,
+ };
+
+ await expect(
+ MCPOAuthHandler.refreshOAuthTokens(
+ 'test-refresh-token',
+ metadata,
+ {},
+ {
+ client_id: 'public-client-id',
+ token_url: 'https://attacker.example.com/token',
+ },
+ ),
+ ).rejects.toThrow('no longer matches the current configured token endpoint');
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('keeps a configured public client pinned when discovery advertises confidential methods', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://mcp.example.com/mcp',
+ clientInfo: {
+ client_id: 'public-client-id',
+ token_endpoint_auth_method: 'none',
+ },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['client_secret_basic'],
+ storedServerUrl: 'https://mcp.example.com/mcp',
+ clientSource: 'configured' as const,
+ };
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ access_token: 'new-access-token', expires_in: 3600 }),
+ } as Response);
+
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'test-refresh-token',
+ metadata,
{},
+ {
+ client_id: 'public-client-id',
+ },
);
expect(mockFetch).toHaveBeenCalledWith(
'https://auth.example.com/token',
expect.objectContaining({ method: 'POST' }),
);
- expect(result.access_token).toBe('new-access-token');
+ const body = mockFetch.mock.calls[0][1]?.body as URLSearchParams;
+ expect(body.get('client_id')).toBe('public-client-id');
+ });
+
+ it('rejects stored configured credentials after the configured client is removed', async () => {
+ const metadata = {
+ serverName: 'test-server',
+ serverUrl: 'https://mcp.example.com/mcp',
+ clientInfo: {
+ client_id: 'configured-client-id',
+ client_secret: 'configured-client-secret',
+ },
+ storedTokenEndpoint: 'https://auth.example.com/token',
+ storedAuthMethods: ['client_secret_basic'],
+ storedServerUrl: 'https://mcp.example.com/mcp',
+ clientSource: 'configured' as const,
+ };
+
+ await expect(
+ MCPOAuthHandler.refreshOAuthTokens('test-refresh-token', metadata, {}, undefined),
+ ).rejects.toThrow('no longer matches the current configured client');
+
+ expect(mockFetch).not.toHaveBeenCalled();
});
it('uses stored token endpoint when discovery fails (auto-discovered)', async () => {
@@ -1217,22 +1410,30 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
expect(result.access_token).toBe('new-access-token');
});
- it('still throws when discovery fails and no stored endpoint (stored clientInfo)', async () => {
+ it('fails before discovery or fetch when confidential client binding is missing', async () => {
const metadata = {
serverName: 'test-server',
- serverUrl: 'https://mcp.example.com',
+ serverUrl: 'https://attacker.example.com/mcp',
clientInfo: {
client_id: 'test-client-id',
client_secret: 'test-client-secret',
},
};
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce(undefined);
-
await expect(
- MCPOAuthHandler.refreshOAuthTokens('test-refresh-token', metadata, {}, {}),
- ).rejects.toThrow('No OAuth metadata discovered for token refresh');
+ MCPOAuthHandler.refreshOAuthTokens(
+ 'test-refresh-token',
+ metadata,
+ {},
+ {
+ token_url: 'https://attacker.example.com/token',
+ client_id: 'replacement-client-id',
+ client_secret: 'replacement-client-secret',
+ },
+ ),
+ ).rejects.toThrow('Stored OAuth client_secret is missing its bound token endpoint');
+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();
expect(mockFetch).not.toHaveBeenCalled();
});
@@ -1538,12 +1739,63 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
return { access_token: 'test-token', token_type: 'Bearer', expires_in: 3600 };
});
- await MCPOAuthHandler.completeOAuthFlow('test-flow-id', 'test-auth-code', mockFlowManager, {
- foo: 'bar',
- });
+ const result = await MCPOAuthHandler.completeOAuthFlow(
+ 'test-flow-id',
+ 'test-auth-code',
+ mockFlowManager,
+ { foo: 'bar' },
+ );
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(
+ 'test-flow-id',
+ 'mcp_oauth',
+ expect.objectContaining({ credential_set_id: result.credential_set_id }),
+ );
+ });
+
+ it('persists exchanged tokens before completing and waking the OAuth flow', async () => {
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ metadata: {
+ serverName: 'test-server',
+ codeVerifier: 'test-verifier',
+ clientInfo: {},
+ metadata: {},
+ } as MCPOAuthFlowMetadata,
+ }),
+ completeFlow: jest.fn(),
+ } 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,
+ expires_at: 123456,
+ }));
+
+ const result = await MCPOAuthHandler.completeOAuthFlow(
+ 'test-flow-id',
+ 'test-auth-code',
+ mockFlowManager,
+ {},
+ persistBeforeComplete,
+ );
+
+ expect(result.expires_at).toBe(123456);
+ expect(persistBeforeComplete.mock.invocationCallOrder[0]).toBeLessThan(
+ (mockFlowManager.completeFlow as jest.Mock).mock.invocationCallOrder[0],
+ );
+ expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(
+ 'test-flow-id',
+ 'mcp_oauth',
+ result,
+ );
});
it('passes headers to token refresh', async () => {
@@ -1560,7 +1812,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
{
serverName: 'test-server',
serverUrl: 'http://example.com',
- clientInfo: { client_id: 'test-client', client_secret: 'test-secret' },
+ clientInfo: { client_id: 'test-client' },
},
{ foo: 'bar' },
{},
@@ -1773,27 +2025,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
});
it('should force client_secret_post even when server advertises client_secret_basic', async () => {
- const metadata = {
- serverName: 'test-server',
- serverUrl: 'https://auth.example.com',
- clientInfo: {
- client_id: 'test-client-id',
- client_secret: 'test-client-secret',
- token_endpoint_auth_method: 'client_secret_basic',
- },
- };
-
- mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({
- issuer: 'https://auth.example.com',
- authorization_endpoint: 'https://auth.example.com/oauth/authorize',
- token_endpoint: 'https://auth.example.com/oauth/token',
- token_endpoint_auth_methods_supported: ['client_secret_basic'],
- response_types_supported: ['code'],
- jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- } as AuthorizationServerMetadata);
-
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -1803,12 +2034,21 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
}),
} as Response);
- await MCPOAuthHandler.refreshOAuthTokens('refresh-token', metadata, {}, {
- token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
- } as MCPOptions['oauth']);
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'refresh-token',
+ { serverName: 'test-server' },
+ {},
+ {
+ token_url: 'https://auth.example.com/oauth/token',
+ client_id: 'test-client-id',
+ client_secret: 'test-client-secret',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ token_endpoint_auth_methods_supported: ['client_secret_basic'],
+ },
+ );
expect(mockFetch).toHaveBeenCalledWith(
- 'https://auth.example.com/oauth/token',
+ new URL('https://auth.example.com/oauth/token'),
expect.objectContaining({
method: 'POST',
headers: expect.not.objectContaining({
@@ -1900,7 +2140,13 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
mockGetClientInfoAndMetadata.mockResolvedValueOnce({
clientInfo: existingClientInfo,
- clientMetadata: { issuer: 'https://example.com' },
+ clientMetadata: {
+ issuer: 'https://example.com',
+ token_endpoint: 'https://example.com/token',
+ server_url: 'https://example.com/mcp',
+ client_source: 'dynamic',
+ credential_set_id: 'stored-generation',
+ },
});
// Mock resource metadata discovery to fail
@@ -1948,6 +2194,7 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
expect(result.authorizationUrl).toBeDefined();
expect(result.flowId).toBeDefined();
+ expect(result.flowMetadata.reusedClientCredentialSetId).toBe('stored-generation');
});
it('should register a new client when findToken is provided but no existing registration found', async () => {
@@ -2282,13 +2529,12 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
);
});
- it('should throw when metadata discovery fails during refresh (stored clientInfo)', async () => {
+ it('should throw when metadata discovery fails during refresh (public stored clientInfo)', async () => {
const metadata = {
serverName: 'test-server',
serverUrl: 'https://mcp.example.com',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
},
};
@@ -2307,7 +2553,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://mcp.example.com',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
},
};
@@ -2365,7 +2610,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://mcp.sentry.dev/mcp',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
grant_types: ['authorization_code', 'refresh_token'],
},
};
@@ -2498,7 +2742,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://mcp.sentry.dev/mcp',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
grant_types: ['authorization_code', 'refresh_token'],
},
};
@@ -2521,7 +2764,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://auth.example.com/',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
},
};
@@ -2541,7 +2783,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://mcp.sentry.dev/mcp',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
grant_types: ['authorization_code', 'refresh_token'],
},
};
@@ -2587,7 +2828,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://auth.example.com/',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
},
};
@@ -2608,7 +2848,6 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
serverUrl: 'https://mcp.sentry.dev/mcp',
clientInfo: {
client_id: 'test-client-id',
- client_secret: 'test-client-secret',
},
};
diff --git a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
index 453c3600dd..2b01c95716 100644
--- a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
+++ b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
@@ -536,6 +536,12 @@ export interface InMemoryToken {
export class InMemoryTokenStore {
private tokens: Map<string, InMemoryToken> = new Map();
+ private getCredentialSetId(token: InMemoryToken): unknown {
+ return token.metadata instanceof Map
+ ? token.metadata.get('credential_set_id')
+ : token.metadata?.credential_set_id;
+ }
+
private key(filter: { userId?: string; type?: string; identifier?: string }): string {
return `${filter.userId}:${filter.type}:${filter.identifier}`;
}
@@ -544,12 +550,20 @@ export class InMemoryTokenStore {
userId?: string;
type?: string;
identifier?: string;
+ token?: string;
+ metadataCredentialSetId?: string | null;
}): Promise<InMemoryToken | null> => {
for (const token of this.tokens.values()) {
const matchUserId = !filter.userId || token.userId === filter.userId;
const matchType = !filter.type || token.type === filter.type;
const matchIdentifier = !filter.identifier || token.identifier === filter.identifier;
- if (matchUserId && matchType && matchIdentifier) {
+ const matchToken = !filter.token || token.token === filter.token;
+ const matchCredentialSet =
+ filter.metadataCredentialSetId === undefined ||
+ (filter.metadataCredentialSetId === null
+ ? this.getCredentialSetId(token) == null
+ : this.getCredentialSetId(token) === filter.metadataCredentialSetId);
+ if (matchUserId && matchType && matchIdentifier && matchToken && matchCredentialSet) {
return token;
}
}
@@ -579,19 +593,26 @@ export class InMemoryTokenStore {
}) as unknown as TokenMethods['createToken'];
updateToken = (async (
- filter: { userId?: string; type?: string; identifier?: string },
+ filter: {
+ userId?: string;
+ type?: string;
+ identifier?: string;
+ token?: string;
+ metadataCredentialSetId?: string | null;
+ },
data: {
userId?: string;
type?: string;
identifier?: string;
token?: string;
+ expiresAt?: Date;
expiresIn?: number;
metadata?: Record<string, unknown>;
},
- ): Promise<InMemoryToken> => {
+ ): Promise<InMemoryToken | null> => {
const existing = (await this.findToken(filter)) as InMemoryToken | null;
if (!existing) {
- throw new Error(`Token not found for filter: ${JSON.stringify(filter)}`);
+ return null;
}
const existingKey = this.key(existing);
const expiresIn =
@@ -599,7 +620,9 @@ export class InMemoryTokenStore {
const updated: InMemoryToken = {
...existing,
token: data.token ?? existing.token,
- expiresAt: data.expiresIn ? new Date(Date.now() + expiresIn * 1000) : existing.expiresAt,
+ expiresAt:
+ data.expiresAt ??
+ (data.expiresIn ? new Date(Date.now() + expiresIn * 1000) : existing.expiresAt),
metadata: data.metadata ?? existing.metadata,
};
this.tokens.set(existingKey, updated);
@@ -618,13 +641,20 @@ export class InMemoryTokenStore {
userId?: string;
type?: string;
identifier?: string;
+ token?: string;
+ metadataCredentialSetId?: string | null;
}): Promise<{ acknowledged: boolean; deletedCount: number }> => {
let deletedCount = 0;
for (const [key, token] of this.tokens.entries()) {
const match =
(!query.userId || token.userId === query.userId) &&
(!query.type || token.type === query.type) &&
- (!query.identifier || token.identifier === query.identifier);
+ (!query.identifier || token.identifier === query.identifier) &&
+ (!query.token || token.token === query.token) &&
+ (query.metadataCredentialSetId === undefined ||
+ (query.metadataCredentialSetId === null
+ ? this.getCredentialSetId(token) == null
+ : this.getCredentialSetId(token) === query.metadataCredentialSetId));
if (match) {
this.tokens.delete(key);
deletedCount++;
diff --git a/packages/api/src/mcp/errors.ts b/packages/api/src/mcp/errors.ts
index 9ac7568313..6e3eaa919d 100644
--- a/packages/api/src/mcp/errors.ts
+++ b/packages/api/src/mcp/errors.ts
@@ -5,6 +5,7 @@
export const MCPErrorCodes = {
DOMAIN_NOT_ALLOWED: 'MCP_DOMAIN_NOT_ALLOWED',
INSPECTION_FAILED: 'MCP_INSPECTION_FAILED',
+ OAUTH_SECRET_REENTRY_REQUIRED: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
} as const;
export type MCPErrorCode = (typeof MCPErrorCodes)[keyof typeof MCPErrorCodes];
@@ -46,6 +47,24 @@ export class MCPInspectionFailedError extends Error {
}
}
+/** Raised when an update would move a retained OAuth client secret across trust boundaries. */
+export class MCPOAuthSecretReentryRequiredError extends Error {
+ public readonly code: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED' =
+ MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED;
+
+ public readonly statusCode = 400;
+ public readonly changedFields: readonly string[];
+
+ constructor(changedFields: readonly string[]) {
+ super(
+ `Re-enter oauth.client_secret when changing OAuth credential binding fields: ${changedFields.join(', ')}`,
+ );
+ this.name = 'MCPOAuthSecretReentryRequiredError';
+ this.changedFields = changedFields;
+ Object.setPrototypeOf(this, MCPOAuthSecretReentryRequiredError.prototype);
+ }
+}
+
/**
* Type guard to check if an error is an MCPDomainNotAllowedError
*/
@@ -59,3 +78,10 @@ export function isMCPDomainNotAllowedError(error: unknown): error is MCPDomainNo
export function isMCPInspectionFailedError(error: unknown): error is MCPInspectionFailedError {
return error instanceof MCPInspectionFailedError;
}
+
+/** Type guard for OAuth client-secret binding violations. */
+export function isMCPOAuthSecretReentryRequiredError(
+ error: unknown,
+): error is MCPOAuthSecretReentryRequiredError {
+ return error instanceof MCPOAuthSecretReentryRequiredError;
+}
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index 3cb7fdd861..fa62c6024c 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -19,6 +19,7 @@ import type {
OAuthClientInformation,
OAuthProtectedResourceMetadata,
OAuthStoredClientMetadata,
+ OAuthClientSource,
MCPOAuthFlowMetadata,
MCPOAuthTokens,
OAuthMetadata,
@@ -470,20 +471,122 @@ export class MCPOAuthHandler {
);
}
+ private static oauthUrlsMatch(left: string, right: string): boolean {
+ try {
+ return new URL(left).href === new URL(right).href;
+ } catch {
+ return false;
+ }
+ }
+
public static buildStoredClientMetadata(
metadata?: OAuthMetadata,
resourceMetadata?: OAuthProtectedResourceMetadata,
+ serverUrl?: string,
+ clientSource?: OAuthClientSource,
): OAuthStoredClientMetadata | undefined {
- if (!metadata) {
+ if (!metadata || !serverUrl || !clientSource) {
return undefined;
}
- const storedMetadata: OAuthStoredClientMetadata = { ...metadata };
+ const storedMetadata: OAuthStoredClientMetadata = {
+ ...metadata,
+ server_url: new URL(serverUrl).href,
+ client_source: clientSource,
+ };
if (resourceMetadata?.resource) {
storedMetadata.resource = new URL(resourceMetadata.resource).href;
}
return storedMetadata;
}
+ /**
+ * Ensures stored tokens and client credentials are only reused with the MCP resource and
+ * configured-client provenance captured by the authorization flow that created them.
+ */
+ public static assertStoredClientBinding(
+ serverName: string,
+ serverUrl: string | undefined,
+ clientInfo: OAuthClientInformation | undefined,
+ storedMetadata: Partial<OAuthStoredClientMetadata> | undefined,
+ config?: MCPOptions['oauth'],
+ ): void {
+ const reauthenticate = (reason: string): never => {
+ throw new Error(
+ `[MCPOAuth] Stored OAuth binding for ${serverName} ${reason}; re-authentication is required.`,
+ );
+ };
+
+ if (!serverUrl || !clientInfo?.client_id || !storedMetadata) {
+ reauthenticate('is incomplete');
+ }
+ const currentServerUrl = serverUrl!;
+ const stored = storedMetadata!;
+ const client = clientInfo!;
+ if (
+ !stored.server_url ||
+ !stored.token_endpoint ||
+ (stored.client_source !== 'configured' && stored.client_source !== 'dynamic')
+ ) {
+ reauthenticate('is missing its server URL, token endpoint, or client provenance');
+ }
+ if (!this.oauthUrlsMatch(stored.server_url!, currentServerUrl)) {
+ reauthenticate('no longer matches the current MCP server URL');
+ }
+
+ if (stored.resource) {
+ this.assertResourceBoundToServer(stored.server_url!, {
+ resource: stored.resource,
+ });
+ }
+
+ if (stored.client_source === 'dynamic') {
+ if (config?.client_id) {
+ reauthenticate('was dynamically registered but the server now uses a configured client');
+ }
+ return;
+ }
+
+ if (
+ !config?.client_id ||
+ config.client_id !== client.client_id ||
+ config.client_secret !== client.client_secret
+ ) {
+ reauthenticate('no longer matches the current configured client');
+ }
+ const configured = config!;
+ if (
+ configured.token_url &&
+ !this.oauthUrlsMatch(stored.token_endpoint!, configured.token_url)
+ ) {
+ reauthenticate('no longer matches the current configured token endpoint');
+ }
+
+ const storedAuthMethod = client.client_secret
+ ? (resolveTokenEndpointAuthMethod({
+ tokenAuthMethods: stored.token_endpoint_auth_methods_supported ?? ['client_secret_basic'],
+ preferredMethod: client.token_endpoint_auth_method,
+ }) ?? 'client_secret_basic')
+ : 'none';
+ const hasConfiguredAuthPolicy =
+ configured.token_exchange_method !== undefined ||
+ configured.token_endpoint_auth_methods_supported !== undefined;
+ let configuredAuthMethod: ReturnType<typeof inferClientAuthMethod> = client.client_secret
+ ? storedAuthMethod
+ : 'none';
+ if (client.client_secret && hasConfiguredAuthPolicy) {
+ configuredAuthMethod =
+ resolveTokenEndpointAuthMethod({
+ tokenExchangeMethod: configured.token_exchange_method,
+ tokenAuthMethods: configured.token_endpoint_auth_methods_supported ?? [
+ 'client_secret_basic',
+ ],
+ }) ?? 'client_secret_basic';
+ }
+ if (storedAuthMethod !== configuredAuthMethod) {
+ reauthenticate('no longer matches the current configured token authentication method');
+ }
+ }
+
private static appendResourceParameter(body: URLSearchParams, resource?: string): void {
if (!resource) {
return;
@@ -750,6 +853,11 @@ export class MCPOAuthHandler {
response_types_supported: config?.response_types_supported ??
discoveredMetadata?.response_types_supported ?? ['code'],
code_challenge_methods_supported: codeChallengeMethodsSupported,
+ revocation_endpoint:
+ config.revocation_endpoint ?? discoveredMetadata?.revocation_endpoint,
+ revocation_endpoint_auth_methods_supported:
+ config.revocation_endpoint_auth_methods_supported ??
+ discoveredMetadata?.revocation_endpoint_auth_methods_supported,
};
logger.debug(`[MCPOAuth] metadata for "${serverName}": ${JSON.stringify(metadata)}`);
const redirectUri = this.getDefaultRedirectUri(serverName);
@@ -798,6 +906,7 @@ export class MCPOAuthHandler {
state,
codeVerifier,
clientInfo,
+ clientSource: 'configured',
metadata,
resourceMetadata,
...(allowedDomains !== undefined && { allowedDomains }),
@@ -835,6 +944,8 @@ export class MCPOAuthHandler {
let clientInfo: OAuthClientInformation | undefined;
let reusedStoredClient = false;
+ let reusedClientCredentialSetId: string | undefined;
+ let clientSource: OAuthClientSource = config?.client_id ? 'configured' : 'dynamic';
if (config?.client_id) {
logger.debug(`[MCPOAuth] Using predefined public client_id for ${serverName}`);
@@ -860,6 +971,13 @@ export class MCPOAuthHandler {
? existing.clientMetadata.issuer.replace(/\/+$/, '')
: null;
const currentIssuer = (metadata.issuer ?? authServerUrl.toString()).replace(/\/+$/, '');
+ const storedServerUrl = existing.clientMetadata?.server_url;
+ const storedTokenEndpoint = existing.clientMetadata?.token_endpoint;
+ const storedResource = existing.clientMetadata?.resource;
+ const storedCredentialSetId = existing.clientMetadata?.credential_set_id;
+ const currentResource = resourceMetadata?.resource
+ ? new URL(resourceMetadata.resource).href
+ : undefined;
if (!storedRedirectUri || storedRedirectUri !== redirectUri) {
logger.debug(
@@ -869,12 +987,27 @@ export class MCPOAuthHandler {
logger.debug(
`[MCPOAuth] Issuer mismatch (stored: ${storedIssuer ?? 'none'}, current: ${currentIssuer}), will re-register`,
);
+ } else if (
+ existing.clientMetadata?.client_source !== 'dynamic' ||
+ typeof storedCredentialSetId !== 'string' ||
+ storedCredentialSetId.length === 0 ||
+ typeof storedServerUrl !== 'string' ||
+ !this.oauthUrlsMatch(storedServerUrl, serverUrl) ||
+ typeof storedTokenEndpoint !== 'string' ||
+ !this.oauthUrlsMatch(storedTokenEndpoint, metadata.token_endpoint) ||
+ storedResource !== currentResource
+ ) {
+ logger.debug(
+ `[MCPOAuth] Stored client registration binding does not match the current MCP resource, will re-register`,
+ );
} else {
logger.debug(
`[MCPOAuth] Reusing existing client registration: ${existing.clientInfo.client_id}`,
);
clientInfo = existing.clientInfo;
reusedStoredClient = true;
+ reusedClientCredentialSetId = storedCredentialSetId;
+ clientSource = 'dynamic';
}
}
} catch (error) {
@@ -979,12 +1112,14 @@ export class MCPOAuthHandler {
state,
codeVerifier,
clientInfo,
+ clientSource,
metadata,
resourceMetadata,
...(allowedDomains !== undefined && { allowedDomains }),
...(allowedAddresses !== undefined && { allowedAddresses }),
...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),
...(reusedStoredClient && { reusedStoredClient }),
+ ...(reusedClientCredentialSetId && { reusedClientCredentialSetId }),
...(tenantId && { tenantId }),
};
@@ -1021,6 +1156,7 @@ export class MCPOAuthHandler {
authorizationCode: string,
flowManager: FlowStateManager<MCPOAuthTokens>,
oauthHeaders: Record<string, string>,
+ persistBeforeComplete?: (tokens: MCPOAuthTokens) => Promise<MCPOAuthTokens>,
): Promise<MCPOAuthTokens> {
try {
/** Flow state which contains our metadata */
@@ -1079,13 +1215,22 @@ export class MCPOAuthHandler {
scope: tokens.scope,
});
- const mcpTokens: MCPOAuthTokens = {
+ let mcpTokens: MCPOAuthTokens = {
...tokens,
+ credential_set_id: randomBytes(16).toString('hex'),
obtained_at: Date.now(),
expires_at: tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined,
};
- /** Now complete the flow with the tokens */
+ /**
+ * Persist before completing the flow so waiting connection factories cannot race the
+ * callback route to write the same credential generation.
+ */
+ if (persistBeforeComplete) {
+ mcpTokens = await persistBeforeComplete(mcpTokens);
+ }
+
+ /** Now wake flow waiters with the persisted token snapshot. */
await flowManager.completeFlow(flowId, this.FLOW_TYPE, mcpTokens);
return mcpTokens;
@@ -1453,6 +1598,8 @@ export class MCPOAuthHandler {
clientInfo?: OAuthClientInformation;
storedTokenEndpoint?: string;
storedAuthMethods?: string[];
+ storedServerUrl?: string;
+ clientSource?: OAuthClientSource;
resource?: string;
},
oauthHeaders: Record<string, string>,
@@ -1484,7 +1631,61 @@ export class MCPOAuthHandler {
let tokenUrl: string;
let authMethods: string[] | undefined;
- if (config?.token_url) {
+ const hasStoredClientSecret = !!metadata.clientInfo.client_secret;
+ const hasStoredBinding =
+ metadata.storedServerUrl !== undefined || metadata.clientSource !== undefined;
+ if (hasStoredBinding) {
+ this.assertStoredClientBinding(
+ metadata.serverName,
+ metadata.serverUrl,
+ metadata.clientInfo,
+ {
+ token_endpoint: metadata.storedTokenEndpoint ?? '',
+ token_endpoint_auth_methods_supported: metadata.storedAuthMethods,
+ server_url: metadata.storedServerUrl ?? '',
+ client_source: metadata.clientSource,
+ resource: metadata.resource,
+ },
+ config,
+ );
+ await this.validateOAuthUrl(
+ metadata.storedTokenEndpoint!,
+ 'token_url',
+ allowedDomains,
+ allowedAddresses,
+ );
+ tokenUrl = metadata.storedTokenEndpoint!;
+ authMethods = metadata.storedAuthMethods;
+ } else if (metadata.storedTokenEndpoint) {
+ /**
+ * Keep direct, non-storage callers compatible while still pinning every supplied
+ * token endpoint. MCPTokenStorage requires the full binding before invoking this path.
+ */
+ if (
+ hasStoredClientSecret &&
+ config?.client_id &&
+ (metadata.clientInfo.client_id !== config.client_id ||
+ metadata.clientInfo.client_secret !== config.client_secret ||
+ (config.token_url &&
+ !this.oauthUrlsMatch(metadata.storedTokenEndpoint, config.token_url)))
+ ) {
+ throw new Error(
+ '[MCPOAuth] Stored OAuth client binding no longer matches current OAuth client configuration; re-authentication is required.',
+ );
+ }
+ await this.validateOAuthUrl(
+ metadata.storedTokenEndpoint,
+ 'token_url',
+ allowedDomains,
+ allowedAddresses,
+ );
+ tokenUrl = metadata.storedTokenEndpoint;
+ authMethods = metadata.storedAuthMethods;
+ } else if (hasStoredClientSecret) {
+ throw new Error(
+ '[MCPOAuth] Stored OAuth client_secret is missing its bound token endpoint; re-authentication is required.',
+ );
+ } else if (config?.token_url) {
await this.validateOAuthUrl(
config.token_url,
'token_url',
@@ -1580,7 +1781,7 @@ export class MCPOAuthHandler {
/** Default to client_secret_basic if no methods specified (per RFC 8414) */
const tokenAuthMethods = authMethods ?? ['client_secret_basic'];
const authMethod = resolveTokenEndpointAuthMethod({
- tokenExchangeMethod: config?.token_exchange_method,
+ tokenExchangeMethod: hasStoredClientSecret ? undefined : config?.token_exchange_method,
tokenAuthMethods,
preferredMethod: metadata.clientInfo.token_endpoint_auth_method,
});
diff --git a/packages/api/src/mcp/oauth/tokens.ts b/packages/api/src/mcp/oauth/tokens.ts
index b242072bc2..b4dd633cc4 100644
--- a/packages/api/src/mcp/oauth/tokens.ts
+++ b/packages/api/src/mcp/oauth/tokens.ts
@@ -1,17 +1,27 @@
import jwt from 'jsonwebtoken';
+import { randomUUID } from 'crypto';
import { logger, encryptV2, decryptV2, getTenantId } from '@librechat/data-schemas';
+import type {
+ TokenMethods,
+ IToken,
+ TokenCreateData,
+ TokenUpdateData,
+} from '@librechat/data-schemas';
import type { OAuthTokens, OAuthClientInformation } from '@modelcontextprotocol/sdk/shared/auth.js';
-import type { TokenMethods, IToken } from '@librechat/data-schemas';
import type { MCPOAuthTokens, ExtendedOAuthTokens, OAuthStoredClientMetadata } from './types';
import { isInvalidClientMessage } from '~/mcp/utils';
import { isSystemUserId } from '~/mcp/enum';
export class ReauthenticationRequiredError extends Error {
- constructor(serverName: string, reason: 'expired' | 'missing' | 'invalid_client') {
- const detail =
- reason === 'invalid_client'
- ? 'stored client registration is no longer valid'
- : `access token ${reason} and no refresh token available`;
+ constructor(serverName: string, reason: 'expired' | 'missing' | 'invalid_client' | 'binding') {
+ let detail: string;
+ if (reason === 'invalid_client') {
+ detail = 'stored client registration is no longer valid';
+ } else if (reason === 'binding') {
+ detail = 'stored OAuth binding metadata is missing or no longer valid';
+ } else {
+ detail = `access token ${reason} and no refresh token available`;
+ }
super(`Re-authentication required for "${serverName}": ${detail}`);
this.name = 'ReauthenticationRequiredError';
}
@@ -23,9 +33,12 @@ interface StoreTokensParams {
tokens: OAuthTokens | ExtendedOAuthTokens | MCPOAuthTokens;
createToken: TokenMethods['createToken'];
updateToken?: TokenMethods['updateToken'];
+ deleteTokens?: TokenMethods['deleteTokens'];
findToken?: TokenMethods['findToken'];
clientInfo?: OAuthClientInformation;
metadata?: Partial<OAuthStoredClientMetadata>;
+ /** Existing generation that must still own every stored record before a refresh is persisted. */
+ expectedCredentialSetId?: string;
/** Optional: Pass existing token state to avoid duplicate DB calls */
existingTokens?: {
accessToken?: IToken | null;
@@ -47,6 +60,8 @@ interface GetTokensParams {
clientInfo?: OAuthClientInformation;
storedTokenEndpoint?: string;
storedAuthMethods?: string[];
+ storedServerUrl?: string;
+ clientSource?: OAuthStoredClientMetadata['client_source'];
resource?: string;
},
signal?: AbortSignal,
@@ -63,6 +78,8 @@ interface GetTokensParams {
* cache invalidation tied to the fresh tokens cannot be skipped by a timeout.
*/
onRefreshSuccess?: (tokens: MCPOAuthTokens) => Promise<void>;
+ /** Separates in-flight redemptions for the same named server under different OAuth bindings. */
+ singleFlightScope?: string;
}
/**
@@ -92,10 +109,35 @@ function getJwtAccessTokenExpiry(accessToken?: string): number | null {
return null;
}
+function getTokenMetadata(tokenData: IToken | null | undefined): Record<string, unknown> {
+ if (tokenData?.metadata == null) {
+ return {};
+ }
+ if (tokenData.metadata instanceof Map) {
+ return Object.fromEntries(tokenData.metadata);
+ }
+ return { ...(tokenData.metadata as unknown as Record<string, unknown>) };
+}
+
+function getCredentialSetId(tokenData: IToken | null | undefined): string | undefined {
+ const value = getTokenMetadata(tokenData).credential_set_id;
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+function cloneTokenMetadata(tokenData: IToken): Record<string, unknown> | Map<string, unknown> {
+ if (tokenData.metadata instanceof Map) {
+ return new Map(tokenData.metadata);
+ }
+ if (tokenData.metadata) {
+ return { ...(tokenData.metadata as unknown as Record<string, unknown>) };
+ }
+ return {};
+}
+
export class MCPTokenStorage {
/**
* Process-local in-flight refresh-token redemptions, keyed by
- * `tenantId:userId:serverName`. Every code path that redeems a refresh token
+ * `tenantId:userId:serverName:bindingScope`. Every code path that redeems a refresh token
* (expired-token refresh via `getTokens`, silent refresh on 401, reconnect
* retries) converges on `forceRefreshTokens`, so coalescing here guarantees
* at most one wire call to the token endpoint per user/server at a time.
@@ -122,6 +164,62 @@ export class MCPTokenStorage {
: `[MCP][User: ${userId}][${serverName}]`;
}
+ /**
+ * Confirms a flow-cached access token is still the token in persistent storage. This prevents
+ * an old `mcp_get_tokens` result from being paired with newer client-binding metadata.
+ */
+ static async isCurrentAccessToken({
+ userId,
+ serverName,
+ accessToken,
+ credentialSetId,
+ findToken,
+ }: {
+ userId: string;
+ serverName: string;
+ accessToken: string;
+ credentialSetId: string | undefined;
+ findToken: TokenMethods['findToken'];
+ }): Promise<boolean> {
+ try {
+ const tokenData = await findToken({
+ userId,
+ type: 'mcp_oauth',
+ identifier: `mcp:${serverName}`,
+ });
+ if (!tokenData || (tokenData.expiresAt && new Date() >= tokenData.expiresAt)) {
+ return false;
+ }
+ return (
+ credentialSetId != null &&
+ getCredentialSetId(tokenData) === credentialSetId &&
+ (await decryptV2(tokenData.token)) === accessToken
+ );
+ } catch (error) {
+ logger.warn(`${this.getLogPrefix(userId, serverName)} Failed to verify cached access token`, {
+ error,
+ });
+ return false;
+ }
+ }
+
+ /** Fails closed when separately stored OAuth records are not from the same authorization. */
+ static assertCredentialSetBinding(
+ serverName: string,
+ tokenCredentialSetId: string | undefined,
+ clientMetadata: Partial<OAuthStoredClientMetadata> | Record<string, unknown> | undefined,
+ ): void {
+ const clientCredentialSetId = clientMetadata?.credential_set_id;
+ if (
+ !tokenCredentialSetId ||
+ typeof clientCredentialSetId !== 'string' ||
+ clientCredentialSetId.length === 0 ||
+ tokenCredentialSetId !== clientCredentialSetId
+ ) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ }
+
/**
* Stores OAuth tokens for an MCP server
*
@@ -134,15 +232,191 @@ export class MCPTokenStorage {
tokens,
createToken,
updateToken,
+ deleteTokens,
findToken,
clientInfo,
existingTokens,
metadata,
- }: StoreTokensParams): Promise<void> {
+ expectedCredentialSetId,
+ }: StoreTokensParams): Promise<MCPOAuthTokens> {
const logPrefix = this.getLogPrefix(userId, serverName);
+ const rollbackWrites: Array<() => Promise<void>> = [];
try {
const identifier = `mcp:${serverName}`;
+ const tokenCredentialSetId = (tokens as Partial<MCPOAuthTokens>).credential_set_id;
+ const metadataCredentialSetId = metadata?.credential_set_id;
+ const validTokenCredentialSetId =
+ typeof tokenCredentialSetId === 'string' && tokenCredentialSetId.length > 0
+ ? tokenCredentialSetId
+ : undefined;
+ const validMetadataCredentialSetId =
+ typeof metadataCredentialSetId === 'string' && metadataCredentialSetId.length > 0
+ ? metadataCredentialSetId
+ : undefined;
+ let credentialSetId: string;
+ if (expectedCredentialSetId) {
+ if (
+ (validTokenCredentialSetId && validTokenCredentialSetId !== expectedCredentialSetId) ||
+ (validMetadataCredentialSetId && validMetadataCredentialSetId !== expectedCredentialSetId)
+ ) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ /** Every successful refresh becomes a distinct credential generation. */
+ credentialSetId = randomUUID();
+ } else {
+ /**
+ * Only the token exchange result carries an internally generated flow ID. OAuth
+ * metadata is provider-controlled (and the schema permits extensions), so it must
+ * never select the credential generation for an interactive/non-refresh write.
+ */
+ credentialSetId = validTokenCredentialSetId ?? randomUUID();
+ }
+ const tokenMetadata = { credential_set_id: credentialSetId };
+
+ /**
+ * Snapshot every record before the first write. Conditional updates below use these
+ * encrypted values and generation IDs as an optimistic lock, so a refresh response from
+ * generation A cannot overwrite a newer interactive authorization B.
+ */
+ let existingAccessToken: IToken | null | undefined;
+ let existingRefreshToken: IToken | null | undefined;
+ let existingClientInfo: IToken | null | undefined;
+ if (findToken && updateToken) {
+ const accessLookup =
+ existingTokens?.accessToken !== undefined
+ ? Promise.resolve(existingTokens.accessToken)
+ : findToken({ userId, type: 'mcp_oauth', identifier });
+ const refreshLookup =
+ existingTokens?.refreshToken !== undefined
+ ? Promise.resolve(existingTokens.refreshToken)
+ : findToken({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ });
+ const clientLookup =
+ existingTokens?.clientInfoToken !== undefined
+ ? Promise.resolve(existingTokens.clientInfoToken)
+ : findToken({
+ userId,
+ type: 'mcp_oauth_client',
+ identifier: `${identifier}:client`,
+ });
+
+ [existingAccessToken, existingRefreshToken, existingClientInfo] = await Promise.all([
+ accessLookup,
+ refreshLookup,
+ clientLookup,
+ ]);
+ }
+
+ if (expectedCredentialSetId) {
+ if (!existingRefreshToken || !existingClientInfo) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ for (const currentRecord of [
+ existingAccessToken,
+ existingRefreshToken,
+ existingClientInfo,
+ ]) {
+ if (currentRecord && getCredentialSetId(currentRecord) !== expectedCredentialSetId) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ }
+ } else if (
+ existingAccessToken &&
+ existingClientInfo &&
+ getCredentialSetId(existingAccessToken) !== getCredentialSetId(existingClientInfo)
+ ) {
+ /**
+ * A fresh authorization may replace a coherent generation, but it must not build on a
+ * crash-left mixed anchor. Allowing that would let three concurrent writers chain their
+ * access-token CAS operations and make a later rollback resurrect a failed generation.
+ */
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+
+ const updateIfCurrent = async (
+ existingToken: IToken,
+ type: string,
+ recordIdentifier: string,
+ tokenData: TokenUpdateData,
+ ): Promise<void> => {
+ const existingCredentialSetId = getCredentialSetId(existingToken);
+ const updated = await updateToken!(
+ {
+ userId,
+ type,
+ identifier: recordIdentifier,
+ token: existingToken.token,
+ metadataCredentialSetId: existingCredentialSetId ?? null,
+ },
+ tokenData,
+ );
+ if (!updated) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ const postWriteToken = tokenData.token ?? existingToken.token;
+ const previousMetadata = cloneTokenMetadata(existingToken);
+ rollbackWrites.push(async () => {
+ const restored = await updateToken!(
+ {
+ userId,
+ type,
+ identifier: recordIdentifier,
+ token: postWriteToken,
+ metadataCredentialSetId: credentialSetId,
+ },
+ {
+ token: existingToken.token,
+ expiresAt: existingToken.expiresAt,
+ metadata: previousMetadata,
+ },
+ );
+ if (!restored) {
+ logger.warn(
+ `${logPrefix} Skipped OAuth rollback for ${type}; the record was superseded`,
+ );
+ }
+ });
+ };
+
+ const createWithRollback = async (
+ type: string,
+ recordIdentifier: string,
+ tokenData: TokenCreateData,
+ ): Promise<void> => {
+ await createToken(tokenData);
+ if (!deleteTokens) {
+ return;
+ }
+ rollbackWrites.push(async () => {
+ const result = await deleteTokens({
+ userId,
+ type,
+ identifier: recordIdentifier,
+ token: tokenData.token,
+ metadataCredentialSetId: credentialSetId,
+ });
+ if (result.deletedCount === 0) {
+ logger.warn(
+ `${logPrefix} Skipped OAuth create rollback for ${type}; the record was superseded`,
+ );
+ }
+ });
+ };
+
+ interface PlannedTokenWrite {
+ type: string;
+ identifier: string;
+ existingToken?: IToken | null;
+ createData?: TokenCreateData;
+ updateData: TokenUpdateData;
+ description: string;
+ }
+
+ const plannedWrites: PlannedTokenWrite[] = [];
// Encrypt and store access token
const encryptedAccessToken = await encryptV2(tokens.access_token);
@@ -199,28 +473,17 @@ export class MCPTokenStorage {
identifier,
token: encryptedAccessToken,
expiresIn: expiresInSeconds > 0 ? expiresInSeconds : defaultTTL,
+ metadata: tokenMetadata,
};
- // Check if token already exists and update if it does
- if (findToken && updateToken) {
- // Use provided existing token state if available, otherwise look it up
- const existingToken =
- existingTokens?.accessToken !== undefined
- ? existingTokens.accessToken
- : await findToken({ userId, identifier });
-
- if (existingToken) {
- await updateToken({ userId, identifier }, accessTokenData);
- logger.debug(`${logPrefix} Updated existing access token`);
- } else {
- await createToken(accessTokenData);
- logger.debug(`${logPrefix} Created new access token`);
- }
- } else {
- // Create new token if it's initial store or update methods not provided
- await createToken(accessTokenData);
- logger.debug(`${logPrefix} Created access token (no update methods available)`);
- }
+ plannedWrites.push({
+ type: 'mcp_oauth',
+ identifier,
+ existingToken: existingAccessToken,
+ createData: accessTokenData,
+ updateData: accessTokenData,
+ description: 'access token',
+ });
// Store refresh token if available
if (tokens.refresh_token) {
@@ -242,34 +505,30 @@ export class MCPTokenStorage {
identifier: `${identifier}:refresh`,
token: encryptedRefreshToken,
expiresIn: refreshExpiresIn > 0 ? refreshExpiresIn : 365 * 24 * 60 * 60,
+ metadata: tokenMetadata,
};
- // Check if refresh token already exists and update if it does
- if (findToken && updateToken) {
- // Use provided existing token state if available, otherwise look it up
- const existingRefreshToken =
- existingTokens?.refreshToken !== undefined
- ? existingTokens.refreshToken
- : await findToken({
- userId,
- identifier: `${identifier}:refresh`,
- });
-
- if (existingRefreshToken) {
- await updateToken({ userId, identifier: `${identifier}:refresh` }, refreshTokenData);
- logger.debug(`${logPrefix} Updated existing refresh token`);
- } else {
- await createToken(refreshTokenData);
- logger.debug(`${logPrefix} Created new refresh token`);
- }
- } else {
- await createToken(refreshTokenData);
- logger.debug(`${logPrefix} Created refresh token (no update methods available)`);
- }
+ plannedWrites.push({
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ existingToken: existingRefreshToken,
+ createData: refreshTokenData,
+ updateData: refreshTokenData,
+ description: 'refresh token',
+ });
} else {
logger.debug(
`${logPrefix} No refresh token in response - OAuth server did not rotate refresh token (this is normal for some providers)`,
);
+ if (expectedCredentialSetId && existingRefreshToken && updateToken) {
+ plannedWrites.push({
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ existingToken: existingRefreshToken,
+ updateData: { metadata: tokenMetadata },
+ description: 'refresh token binding',
+ });
+ }
}
/** Store client information if provided */
@@ -286,30 +545,81 @@ export class MCPTokenStorage {
identifier: `${identifier}:client`,
token: encryptedClientInfo,
expiresIn: 365 * 24 * 60 * 60,
- metadata: metadata ? { ...metadata } : undefined,
+ metadata: { ...metadata, credential_set_id: credentialSetId },
};
- // Check if client info already exists and update if it does
- if (findToken && updateToken) {
- // Use provided existing token state if available, otherwise look it up
- const existingClientInfo =
- existingTokens?.clientInfoToken !== undefined
- ? existingTokens.clientInfoToken
- : await findToken({
- userId,
- identifier: `${identifier}:client`,
- });
-
- if (existingClientInfo) {
- await updateToken({ userId, identifier: `${identifier}:client` }, clientInfoData);
- logger.debug(`${logPrefix} Updated existing client info`);
- } else {
- await createToken(clientInfoData);
- logger.debug(`${logPrefix} Created new client info`);
- }
+ plannedWrites.push({
+ type: 'mcp_oauth_client',
+ identifier: `${identifier}:client`,
+ existingToken: existingClientInfo,
+ createData: clientInfoData,
+ updateData: clientInfoData,
+ description: 'client info',
+ });
+ }
+
+ /**
+ * Claim an existing access record first (then refresh/client as fallbacks). Once the
+ * anchor moves to the target generation, a competing writer can only continue from the
+ * exact record versions it observed. Remaining writes are journaled so a later failure
+ * restores the exact snapshot without clobbering a still-newer writer. The preflight gate
+ * above rejects mixed access/client snapshots before they can extend this CAS chain.
+ */
+ const anchorIndex = plannedWrites.findIndex((write) => write.existingToken != null);
+ const orderedWrites =
+ anchorIndex > 0
+ ? [
+ plannedWrites[anchorIndex],
+ ...plannedWrites.slice(0, anchorIndex),
+ ...plannedWrites.slice(anchorIndex + 1),
+ ]
+ : plannedWrites;
+
+ for (const write of orderedWrites) {
+ if (findToken && updateToken && write.existingToken) {
+ await updateIfCurrent(
+ write.existingToken,
+ write.type,
+ write.identifier,
+ write.updateData,
+ );
+ logger.debug(`${logPrefix} Updated existing ${write.description}`);
+ } else if (write.createData) {
+ await createWithRollback(write.type, write.identifier, write.createData);
+ logger.debug(`${logPrefix} Created ${write.description}`);
} else {
- await createToken(clientInfoData);
- logger.debug(`${logPrefix} Created client info (no update methods available)`);
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ }
+
+ /**
+ * An interactive response without a refresh token must never bind an older refresh
+ * secret to the new client. Remove that stale record after the committed writes. This
+ * cleanup is best-effort and fully scoped; reads already omit it if a crash or transient
+ * database error leaves it behind.
+ */
+ if (
+ !expectedCredentialSetId &&
+ !tokens.refresh_token &&
+ existingRefreshToken &&
+ getCredentialSetId(existingRefreshToken) !== credentialSetId &&
+ deleteTokens
+ ) {
+ try {
+ const result = await deleteTokens({
+ userId,
+ type: 'mcp_oauth_refresh',
+ identifier: `${identifier}:refresh`,
+ token: existingRefreshToken.token,
+ metadataCredentialSetId: getCredentialSetId(existingRefreshToken) ?? null,
+ });
+ if (result.deletedCount === 0) {
+ logger.debug(`${logPrefix} Stale refresh token was already superseded`);
+ }
+ } catch (cleanupError) {
+ logger.warn(`${logPrefix} Failed to remove stale refresh token after OAuth callback`, {
+ error: cleanupError,
+ });
}
}
@@ -318,8 +628,25 @@ export class MCPTokenStorage {
has_refresh_token: !!tokens.refresh_token,
expires_at: 'expires_at' in tokens ? tokens.expires_at : 'N/A',
});
+ return {
+ ...tokens,
+ credential_set_id: credentialSetId,
+ obtained_at:
+ 'obtained_at' in tokens && typeof tokens.obtained_at === 'number'
+ ? tokens.obtained_at
+ : Date.now(),
+ expires_at: accessTokenExpiry.getTime(),
+ };
} catch (error) {
- const logPrefix = this.getLogPrefix(userId, serverName);
+ for (const rollback of rollbackWrites.reverse()) {
+ try {
+ await rollback();
+ } catch (rollbackError) {
+ logger.warn(`${logPrefix} Failed to roll back a partial OAuth credential write`, {
+ error: rollbackError,
+ });
+ }
+ }
logger.error(`${logPrefix} Failed to store tokens`, error);
throw error;
}
@@ -331,7 +658,7 @@ export class MCPTokenStorage {
* server has signaled token invalidity (e.g. a 401 mid-session) — the 401 is
* the authoritative signal, not the local `expires_at`.
*
- * Single-flighted per `(tenantId, userId, serverName)`: concurrent callers
+ * Single-flighted per `(tenantId, userId, serverName, bindingScope)`: concurrent callers
* (tool-call 401s, pings, reconnect retries, expired-token reads) share one
* redemption and receive the same rotated result instead of each replaying
* the refresh token at the token endpoint.
@@ -345,10 +672,10 @@ export class MCPTokenStorage {
existingAccessToken?: IToken | null;
},
): Promise<MCPOAuthTokens | null> {
- const { userId, serverName, refreshTokens, createToken, signal } = params;
+ const { userId, serverName, refreshTokens, createToken, signal, singleFlightScope } = params;
const logPrefix = this.getLogPrefix(userId, serverName);
- const refreshKey = `${getTenantId() ?? ''}:${userId}:${serverName}`;
+ const refreshKey = `${getTenantId() ?? ''}:${userId}:${serverName}:${singleFlightScope ?? ''}`;
const inflight = this.inflightRefreshes.get(refreshKey);
if (inflight) {
logger.debug(`${logPrefix} Joining in-flight token refresh`);
@@ -487,15 +814,17 @@ export class MCPTokenStorage {
return null;
}
+ const refreshCredentialSetId = getCredentialSetId(refreshTokenData);
try {
logger.info(`${logPrefix} Attempting to refresh token`);
- const decryptedRefreshToken = await decryptV2(refreshTokenData.token);
let clientInfo;
let clientInfoData;
let storedClientMetadata: Partial<OAuthStoredClientMetadata> | undefined;
let storedTokenEndpoint: string | undefined;
let storedAuthMethods: string[] | undefined;
+ let storedServerUrl: string | undefined;
+ let clientSource: OAuthStoredClientMetadata['client_source'] | undefined;
let resource: string | undefined;
try {
clientInfoData = await findToken({
@@ -512,10 +841,7 @@ export class MCPTokenStorage {
});
if (clientInfoData.metadata) {
- const raw =
- clientInfoData.metadata instanceof Map
- ? Object.fromEntries(clientInfoData.metadata)
- : (clientInfoData.metadata as Record<string, unknown>);
+ const raw = getTokenMetadata(clientInfoData);
storedClientMetadata = raw as Partial<OAuthStoredClientMetadata>;
if (typeof raw.token_endpoint === 'string') {
storedTokenEndpoint = raw.token_endpoint;
@@ -523,6 +849,12 @@ export class MCPTokenStorage {
if (Array.isArray(raw.token_endpoint_auth_methods_supported)) {
storedAuthMethods = raw.token_endpoint_auth_methods_supported as string[];
}
+ if (typeof raw.server_url === 'string') {
+ storedServerUrl = raw.server_url;
+ }
+ if (raw.client_source === 'configured' || raw.client_source === 'dynamic') {
+ clientSource = raw.client_source;
+ }
if (typeof raw.resource === 'string') {
resource = raw.resource;
}
@@ -532,6 +864,18 @@ export class MCPTokenStorage {
logger.debug(`${logPrefix} No client info found`);
}
+ if (
+ !clientInfo?.client_id ||
+ !storedTokenEndpoint ||
+ !storedServerUrl ||
+ !clientSource ||
+ !refreshCredentialSetId
+ ) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+ this.assertCredentialSetBinding(serverName, refreshCredentialSetId, storedClientMetadata);
+ const decryptedRefreshToken = await decryptV2(refreshTokenData.token);
+
const metadata = {
userId,
serverName,
@@ -539,6 +883,8 @@ export class MCPTokenStorage {
clientInfo,
storedTokenEndpoint,
storedAuthMethods,
+ storedServerUrl,
+ clientSource,
resource,
};
@@ -562,34 +908,39 @@ export class MCPTokenStorage {
// Store the refreshed tokens (handles both create and update)
// Pass existing token state to avoid duplicate DB calls
- await this.storeTokens({
+ const storedTokens = await this.storeTokens({
userId,
serverName,
tokens: newTokens,
createToken,
updateToken,
+ deleteTokens,
findToken,
clientInfo,
existingTokens: {
- accessToken: existingAccessToken,
+ accessToken: existingAccessToken ?? undefined,
refreshToken: refreshTokenData,
clientInfoToken: clientInfoData,
},
metadata: storedClientMetadata,
+ expectedCredentialSetId: refreshCredentialSetId,
});
if (onRefreshSuccess) {
try {
- await onRefreshSuccess(newTokens);
+ await onRefreshSuccess(storedTokens);
} catch (hookError) {
logger.warn(`${logPrefix} onRefreshSuccess callback failed`, hookError);
}
}
logger.info(`${logPrefix} Successfully refreshed and stored OAuth tokens`);
- return newTokens;
+ return storedTokens;
} catch (refreshError) {
logger.error(`${logPrefix} Failed to refresh tokens`, refreshError);
+ if (refreshError instanceof ReauthenticationRequiredError) {
+ throw refreshError;
+ }
// Check if it's an unauthorized_client error (refresh not supported)
const errorMessage =
refreshError instanceof Error ? refreshError.message : String(refreshError);
@@ -603,11 +954,19 @@ export class MCPTokenStorage {
`${logPrefix} Client registration rejected during token refresh, attempting to clear stale registration and refresh token`,
);
const results = await Promise.allSettled([
- MCPTokenStorage.deleteClientRegistration({ userId, serverName, deleteTokens }),
+ MCPTokenStorage.deleteClientRegistration({
+ userId,
+ serverName,
+ deleteTokens,
+ credentialSetId: refreshCredentialSetId,
+ }),
deleteTokens({
userId,
type: 'mcp_oauth_refresh',
identifier: `${identifier}:refresh`,
+ ...(refreshCredentialSetId && {
+ metadataCredentialSetId: refreshCredentialSetId,
+ }),
}),
]);
for (const r of results) {
@@ -636,6 +995,7 @@ export class MCPTokenStorage {
updateToken,
deleteTokens,
refreshTokens,
+ singleFlightScope,
}: GetTokensParams): Promise<MCPOAuthTokens | null> {
const logPrefix = this.getLogPrefix(userId, serverName);
@@ -683,6 +1043,7 @@ export class MCPTokenStorage {
updateToken,
deleteTokens,
refreshTokens,
+ singleFlightScope,
existingAccessToken: accessTokenData,
});
}
@@ -692,6 +1053,11 @@ export class MCPTokenStorage {
return null;
}
+ const credentialSetId = getCredentialSetId(accessTokenData);
+ if (!credentialSetId) {
+ throw new ReauthenticationRequiredError(serverName, 'binding');
+ }
+
const decryptedAccessToken = await decryptV2(accessTokenData.token);
/** Get refresh token if available */
@@ -701,15 +1067,29 @@ export class MCPTokenStorage {
identifier: `${identifier}:refresh`,
});
+ const clientInfoData = await findToken({
+ userId,
+ type: 'mcp_oauth_client',
+ identifier: `${identifier}:client`,
+ });
+ this.assertCredentialSetBinding(
+ serverName,
+ credentialSetId,
+ getTokenMetadata(clientInfoData),
+ );
+
const tokens: MCPOAuthTokens = {
access_token: decryptedAccessToken,
token_type: 'Bearer',
+ credential_set_id: credentialSetId,
obtained_at: accessTokenData.createdAt.getTime(),
expires_at: accessTokenData.expiresAt?.getTime(),
};
- if (refreshTokenData) {
+ if (refreshTokenData && getCredentialSetId(refreshTokenData) === credentialSetId) {
tokens.refresh_token = await decryptV2(refreshTokenData.token);
+ } else if (refreshTokenData) {
+ logger.warn(`${logPrefix} Ignoring refresh token from a different OAuth credential set`);
}
logger.debug(`${logPrefix} Loaded existing OAuth tokens from storage`);
@@ -749,19 +1129,7 @@ export class MCPTokenStorage {
const tokenData = await decryptV2(clientInfoData.token);
const clientInfo = JSON.parse(tokenData);
- // get metadata from the token as a plain object. While it's defined as a Map in the database type, it's a plain object at runtime.
- function getMetadata(
- metadata: Map<string, unknown> | Record<string, unknown> | null,
- ): Record<string, unknown> {
- if (metadata == null) {
- return {};
- }
- if (metadata instanceof Map) {
- return Object.fromEntries(metadata);
- }
- return { ...(metadata as Record<string, unknown>) };
- }
- const clientMetadata = getMetadata(clientInfoData.metadata ?? null);
+ const clientMetadata = getTokenMetadata(clientInfoData);
return {
clientInfo,
@@ -774,16 +1142,19 @@ export class MCPTokenStorage {
userId,
serverName,
deleteTokens,
+ credentialSetId,
}: {
userId: string;
serverName: string;
deleteTokens: TokenMethods['deleteTokens'];
+ credentialSetId?: string;
}): Promise<void> {
const identifier = `mcp:${serverName}`;
await deleteTokens({
userId,
type: 'mcp_oauth_client',
identifier: `${identifier}:client`,
+ ...(credentialSetId && { metadataCredentialSetId: credentialSetId }),
});
const logPrefix = this.getLogPrefix(userId, serverName);
logger.debug(`${logPrefix} Cleared stored client registration`);
diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.ts
index fea8b6a1c5..e79660a98e 100644
--- a/packages/api/src/mcp/oauth/types.ts
+++ b/packages/api/src/mcp/oauth/types.ts
@@ -26,7 +26,16 @@ export interface OAuthMetadata {
revocation_endpoint_auth_methods_supported?: string[];
}
+/** How the OAuth client credentials associated with stored tokens were obtained. */
+export type OAuthClientSource = 'configured' | 'dynamic';
+
export interface OAuthStoredClientMetadata extends OAuthMetadata {
+ /** Random identifier shared by the access, refresh, and client records from one authorization. */
+ credential_set_id?: string;
+ /** Canonical MCP server URL the tokens and client registration are bound to. */
+ server_url: string;
+ /** Whether the client came from server configuration or dynamic client registration. */
+ client_source: OAuthClientSource;
/** Canonical OAuth resource indicator used when the authorization code was exchanged. */
resource?: string;
}
@@ -91,6 +100,8 @@ export interface MCPOAuthFlowMetadata extends FlowMetadata {
state: string;
codeVerifier?: string;
clientInfo?: OAuthClientInformation;
+ /** Whether this flow uses a configured client or a dynamically registered client. */
+ clientSource?: OAuthClientSource;
metadata?: OAuthMetadata;
resourceMetadata?: OAuthProtectedResourceMetadata;
authorizationUrl?: string;
@@ -102,11 +113,15 @@ export interface MCPOAuthFlowMetadata extends FlowMetadata {
allowedAddresses?: string[] | null;
/** True when the flow reused a stored client registration from a prior successful OAuth flow */
reusedStoredClient?: boolean;
+ /** Credential generation of the reused client, used to scope stale-registration cleanup. */
+ reusedClientCredentialSetId?: string;
/** Tenant context captured at flow initiation for callback replay (SameSite cookies unavailable on cross-origin redirects) */
tenantId?: string;
}
export interface MCPOAuthTokens extends OAuthTokens {
+ /** Internal identifier for the persisted credential set; never sent to the OAuth provider. */
+ credential_set_id?: string;
/** When the tokens were obtained */
obtained_at: number;
/** Calculated expiry time */
diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
index af0141ee8e..7ae0862632 100644
--- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
@@ -6,10 +6,12 @@ import {
PrincipalType,
PermissionBits,
PrincipalModel,
+ TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import type { ParsedServerConfig } from '~/mcp/types';
type ServerConfigsDBType = import('../db/ServerConfigsDB').ServerConfigsDB;
+type MCPOAuthHandlerType = typeof import('~/mcp/oauth').MCPOAuthHandler;
type CreateMethodsType = typeof import('@librechat/data-schemas').createMethods;
type CreateModelsType = typeof import('@librechat/data-schemas').createModels;
type RoleBitsType = typeof import('@librechat/data-schemas').RoleBits;
@@ -17,6 +19,7 @@ type RoleBitsType = typeof import('@librechat/data-schemas').RoleBits;
let mongoServer: MongoMemoryServer;
let serverConfigsDB: ServerConfigsDBType;
let ServerConfigsDB: new (mongoose: typeof import('mongoose')) => ServerConfigsDBType;
+let MCPOAuthHandler: MCPOAuthHandlerType;
let createModels: CreateModelsType;
let createMethods: CreateMethodsType;
let RoleBits: RoleBitsType;
@@ -58,6 +61,8 @@ beforeAll(async () => {
const serverConfigsModule = await import('../db/ServerConfigsDB');
ServerConfigsDB = serverConfigsModule.ServerConfigsDB;
+ const oauthModule = await import('~/mcp/oauth');
+ MCPOAuthHandler = oauthModule.MCPOAuthHandler;
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
@@ -178,10 +183,22 @@ describe('ServerConfigsDB', () => {
});
it('should preserve oauth.client_secret when not provided in update', async () => {
- const config = createSSEConfig('OAuth Server', 'Test', {
- client_id: 'my-client-id',
- client_secret: 'super-secret-key',
- });
+ const config: ParsedServerConfig = {
+ type: 'sse',
+ url: 'https://mcp.example.com/sse',
+ title: 'OAuth Server',
+ description: 'Test',
+ oauth: {
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
+ client_id: 'my-client-id',
+ client_secret: 'super-secret-key',
+ token_exchange_method: TokenExchangeMethodEnum.BasicAuthHeader,
+ token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
+ revocation_endpoint: 'https://auth.example.com/revoke',
+ revocation_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
+ },
+ };
const created = await serverConfigsDB.add('temp-name', config, userId);
// Verify the secret is encrypted in DB after add (not plaintext)
@@ -190,10 +207,14 @@ describe('ServerConfigsDB', () => {
expect(server?.config?.oauth?.client_secret).not.toBe('super-secret-key');
// Update without client_secret
- const updatedConfig = createSSEConfig('OAuth Server', 'Updated description', {
- client_id: 'my-client-id',
- // client_secret not provided
- });
+ const updatedConfig: ParsedServerConfig = {
+ ...config,
+ description: 'Updated description',
+ oauth: {
+ ...config.oauth,
+ client_secret: undefined,
+ },
+ };
await serverConfigsDB.update(created.serverName, updatedConfig, userId);
// Verify the secret is still encrypted in DB (preserved, not plaintext)
@@ -203,20 +224,274 @@ describe('ServerConfigsDB', () => {
// Verify the secret is decrypted when accessed via get()
const retrieved = await serverConfigsDB.get(created.serverName, userId);
expect(retrieved?.oauth?.client_secret).toBe('super-secret-key');
+ expect(retrieved?.description).toBe('Updated description');
});
- it('should allow updating oauth.client_secret when explicitly provided', async () => {
- const config = createSSEConfig('OAuth Server 2', 'Test', {
+ const baseBoundOAuthConfig: ParsedServerConfig = {
+ type: 'sse',
+ url: 'https://mcp.example.com/sse',
+ title: 'Bound OAuth Server',
+ oauth: {
+ authorization_url: 'https://auth.example.com/authorize',
+ token_url: 'https://auth.example.com/token',
client_id: 'my-client-id',
- client_secret: 'old-secret',
+ client_secret: 'super-secret-key',
+ token_exchange_method: TokenExchangeMethodEnum.BasicAuthHeader,
+ token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
+ revocation_endpoint: 'https://auth.example.com/revoke',
+ revocation_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
+ },
+ };
+
+ const updateOAuth = (
+ config: ParsedServerConfig,
+ oauth: Partial<NonNullable<ParsedServerConfig['oauth']>>,
+ ): ParsedServerConfig => ({
+ ...config,
+ oauth: {
+ ...config.oauth,
+ ...oauth,
+ client_secret: undefined,
+ },
+ });
+
+ const bindingChanges: Array<[string, (config: ParsedServerConfig) => ParsedServerConfig]> = [
+ [
+ 'url',
+ (config) => ({ ...updateOAuth(config, {}), url: 'https://attacker.example.com/sse' }),
+ ],
+ [
+ 'oauth.authorization_url',
+ (config) =>
+ updateOAuth(config, { authorization_url: 'https://attacker.example.com/authorize' }),
+ ],
+ [
+ 'oauth.token_url',
+ (config) => updateOAuth(config, { token_url: 'https://attacker.example.com/token' }),
+ ],
+ ['oauth.client_id', (config) => updateOAuth(config, { client_id: 'attacker-client-id' })],
+ [
+ 'oauth.token_exchange_method',
+ (config) =>
+ updateOAuth(config, { token_exchange_method: TokenExchangeMethodEnum.DefaultPost }),
+ ],
+ [
+ 'oauth.token_endpoint_auth_methods_supported',
+ (config) =>
+ updateOAuth(config, { token_endpoint_auth_methods_supported: ['client_secret_post'] }),
+ ],
+ [
+ 'oauth.revocation_endpoint',
+ (config) =>
+ updateOAuth(config, { revocation_endpoint: 'https://attacker.example.com/revoke' }),
+ ],
+ [
+ 'oauth.revocation_endpoint_auth_methods_supported',
+ (config) =>
+ updateOAuth(config, {
+ revocation_endpoint_auth_methods_supported: ['client_secret_post'],
+ }),
+ ],
+ ];
+
+ it.each(bindingChanges)(
+ 'should require the OAuth client secret when changing %s',
+ async (field, createUpdate) => {
+ const created = await serverConfigsDB.add('temp-name', baseBoundOAuthConfig, userId);
+
+ await expect(
+ serverConfigsDB.update(created.serverName, createUpdate(baseBoundOAuthConfig), userId),
+ ).rejects.toThrow(
+ `Re-enter oauth.client_secret when changing OAuth credential binding fields: ${field}`,
+ );
+ },
+ );
+
+ it('should treat OAuth auth-method arrays as unordered sets when preserving a secret', async () => {
+ const created = await serverConfigsDB.add('temp-name', baseBoundOAuthConfig, userId);
+ const updatedConfig = updateOAuth(baseBoundOAuthConfig, {
+ token_endpoint_auth_methods_supported: [
+ 'client_secret_post',
+ 'client_secret_basic',
+ 'client_secret_basic',
+ ],
+ revocation_endpoint_auth_methods_supported: [
+ 'client_secret_post',
+ 'client_secret_basic',
+ 'client_secret_post',
+ ],
});
+
+ await serverConfigsDB.update(created.serverName, updatedConfig, userId);
+
+ const retrieved = await serverConfigsDB.get(created.serverName, userId);
+ expect(retrieved?.oauth?.client_secret).toBe('super-secret-key');
+ });
+
+ it('should treat empty and omitted OAuth auth-method arrays as equivalent', async () => {
+ const config: ParsedServerConfig = {
+ ...baseBoundOAuthConfig,
+ oauth: {
+ ...baseBoundOAuthConfig.oauth,
+ token_endpoint_auth_methods_supported: undefined,
+ revocation_endpoint_auth_methods_supported: undefined,
+ },
+ };
const created = await serverConfigsDB.add('temp-name', config, userId);
+ const updatedConfig = updateOAuth(config, {
+ token_endpoint_auth_methods_supported: [],
+ revocation_endpoint_auth_methods_supported: [],
+ });
- // Update with new client_secret
- const updatedConfig = createSSEConfig('OAuth Server 2', 'Updated', {
- client_id: 'my-client-id',
- client_secret: 'new-secret',
+ await serverConfigsDB.update(created.serverName, updatedConfig, userId);
+
+ const retrieved = await serverConfigsDB.get(created.serverName, userId);
+ expect(retrieved?.oauth?.client_secret).toBe('super-secret-key');
+ });
+
+ it('should preserve OAuth binding fields omitted by the editor', async () => {
+ const created = await serverConfigsDB.add('temp-name', baseBoundOAuthConfig, userId);
+ const updatedConfig: ParsedServerConfig = {
+ ...baseBoundOAuthConfig,
+ description: 'Updated description',
+ oauth: {
+ authorization_url: baseBoundOAuthConfig.oauth?.authorization_url,
+ token_url: baseBoundOAuthConfig.oauth?.token_url,
+ client_id: baseBoundOAuthConfig.oauth?.client_id,
+ token_exchange_method: baseBoundOAuthConfig.oauth?.token_exchange_method,
+ },
+ };
+
+ await serverConfigsDB.update(created.serverName, updatedConfig, userId);
+
+ const retrieved = await serverConfigsDB.get(created.serverName, userId);
+ expect(retrieved?.description).toBe('Updated description');
+ expect(retrieved?.oauth?.client_secret).toBe('super-secret-key');
+ expect(retrieved?.oauth?.token_endpoint_auth_methods_supported).toEqual([
+ 'client_secret_basic',
+ 'client_secret_post',
+ ]);
+ expect(retrieved?.oauth?.revocation_endpoint).toBe('https://auth.example.com/revoke');
+ expect(retrieved?.oauth?.revocation_endpoint_auth_methods_supported).toEqual([
+ 'client_secret_basic',
+ 'client_secret_post',
+ ]);
+ });
+
+ it('should preserve a secret across equivalent WHATWG URL serialization', async () => {
+ const created = await serverConfigsDB.add('temp-name', baseBoundOAuthConfig, userId);
+ const updatedConfig: ParsedServerConfig = {
+ ...updateOAuth(baseBoundOAuthConfig, {
+ authorization_url: 'https://AUTH.EXAMPLE.COM:443/authorize',
+ token_url: 'https://AUTH.EXAMPLE.COM:443/token',
+ revocation_endpoint: 'https://AUTH.EXAMPLE.COM:443/revoke',
+ }),
+ url: 'https://MCP.EXAMPLE.COM:443/sse',
+ };
+
+ await serverConfigsDB.update(created.serverName, updatedConfig, userId);
+
+ const retrieved = await serverConfigsDB.get(created.serverName, userId);
+ expect(retrieved?.oauth?.client_secret).toBe('super-secret-key');
+ });
+
+ it('should treat reordered endpoint query parameters as a binding change', async () => {
+ const configWithoutSecret = updateOAuth(baseBoundOAuthConfig, {
+ token_url: 'https://auth.example.com/token?first=one&second=two',
+ });
+ const config: ParsedServerConfig = {
+ ...configWithoutSecret,
+ oauth: {
+ ...configWithoutSecret.oauth,
+ client_secret: 'super-secret-key',
+ },
+ };
+ const created = await serverConfigsDB.add('temp-name', config, userId);
+ const updatedConfig = updateOAuth(config, {
+ token_url: 'https://auth.example.com/token?second=two&first=one',
+ });
+
+ await expect(
+ serverConfigsDB.update(created.serverName, updatedConfig, userId),
+ ).rejects.toThrow('oauth.token_url');
+ });
+
+ it('should keep a retained secret away from an editor-controlled token endpoint at runtime', async () => {
+ const created = await serverConfigsDB.add('temp-name', baseBoundOAuthConfig, userId);
+ const maliciousUpdate = updateOAuth(baseBoundOAuthConfig, {
+ token_url: 'https://attacker.example.com/token',
});
+ let updateBlocked = false;
+
+ try {
+ await serverConfigsDB.update(created.serverName, maliciousUpdate, userId2);
+ } catch (error) {
+ updateBlocked = true;
+ expect(error).toMatchObject({ code: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED' });
+ }
+
+ const storedConfig = await serverConfigsDB.get(created.serverName, userId);
+ if (!storedConfig?.oauth) {
+ throw new Error('Expected the stored OAuth configuration');
+ }
+
+ const originalFetch = global.fetch;
+ const mockFetch = Object.assign(
+ jest.fn().mockResolvedValue(
+ new Response(JSON.stringify({ access_token: 'new-access-token', token_type: 'Bearer' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ ),
+ { preconnect: jest.fn() },
+ );
+ global.fetch = mockFetch;
+
+ try {
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'refresh-token',
+ { serverName: created.serverName },
+ {},
+ storedConfig.oauth,
+ ['auth.example.com', 'attacker.example.com'],
+ );
+
+ expect(updateBlocked).toBe(true);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(String(mockFetch.mock.calls[0][0])).toBe('https://auth.example.com/token');
+ expect(String(mockFetch.mock.calls[0][0])).not.toContain('attacker.example.com');
+ const request = mockFetch.mock.calls[0][1] as RequestInit;
+ const expectedCredentials = Buffer.from('my-client-id:super-secret-key').toString('base64');
+ expect(new Headers(request.headers).get('Authorization')).toBe(
+ `Basic ${expectedCredentials}`,
+ );
+ } finally {
+ global.fetch = originalFetch;
+ }
+ });
+
+ it('should allow updating oauth.client_secret when explicitly provided', async () => {
+ const config: ParsedServerConfig = {
+ ...baseBoundOAuthConfig,
+ title: 'OAuth Server 2',
+ oauth: {
+ ...baseBoundOAuthConfig.oauth,
+ client_secret: 'old-secret',
+ },
+ };
+ const created = await serverConfigsDB.add('temp-name', config, userId);
+
+ const updatedConfig: ParsedServerConfig = {
+ ...config,
+ url: 'https://new-mcp.example.com/sse',
+ oauth: {
+ ...config.oauth,
+ authorization_url: 'https://new-auth.example.com/authorize',
+ token_url: 'https://new-auth.example.com/token',
+ client_id: 'new-client-id',
+ client_secret: 'new-secret',
+ },
+ };
await serverConfigsDB.update(created.serverName, updatedConfig, userId);
// Verify the secret is encrypted in DB (not plaintext)
@@ -227,6 +502,23 @@ describe('ServerConfigsDB', () => {
// Verify the secret is decrypted to the new value when accessed via get()
const retrieved = await serverConfigsDB.get(created.serverName, userId);
expect(retrieved?.oauth?.client_secret).toBe('new-secret');
+ expect(retrieved?.oauth?.token_url).toBe('https://new-auth.example.com/token');
+ expect(retrieved?.oauth?.client_id).toBe('new-client-id');
+ });
+
+ it('should clear the OAuth client secret when OAuth is removed', async () => {
+ const created = await serverConfigsDB.add('temp-name', baseBoundOAuthConfig, userId);
+ const updatedConfig: ParsedServerConfig = {
+ ...baseBoundOAuthConfig,
+ oauth: undefined,
+ };
+
+ await serverConfigsDB.update(created.serverName, updatedConfig, userId);
+
+ const retrieved = await serverConfigsDB.get(created.serverName, userId);
+ expect(retrieved?.oauth?.client_secret).toBeUndefined();
+ const server = await mongoose.models.MCPServer.findOne({ serverName: created.serverName });
+ expect(server?.config?.oauth?.client_secret).toBeUndefined();
});
it('should encrypt oauth.client_secret when saving to database', async () => {
diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
index 8994d6b529..d15d918075 100644
--- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
+++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
@@ -10,6 +10,7 @@ import type { AllMethods, MCPServerDocument } from '@librechat/data-schemas';
import type { IServerConfigsRepositoryInterface } from '~/mcp/registry/ServerConfigsRepositoryInterface';
import type { ParsedServerConfig, AddServerResult } from '~/mcp/types';
+import { MCPOAuthSecretReentryRequiredError } from '~/mcp/errors';
import { AccessControlService } from '~/acl/accessControlService';
/**
@@ -29,6 +30,8 @@ const DANGEROUS_CREDENTIAL_PATTERNS = [
const BLOCKED_USER_OAUTH_ENDPOINT_PARAMS = ['audience', 'resource'] as const;
+type OAuthConfig = NonNullable<ParsedServerConfig['oauth']>;
+
/**
* Sanitizes headers by removing dangerous credential placeholders.
* This prevents credential exfiltration when MCP servers are shared between users.
@@ -92,6 +95,99 @@ function sanitizeUserManagedOAuthConfig(config: ParsedServerConfig): ParsedServe
};
}
+function normalizeOAuthUrl(value?: string): string | undefined {
+ if (!value) {
+ return value;
+ }
+
+ try {
+ return new URL(value).href;
+ } catch {
+ return value;
+ }
+}
+
+function normalizeOAuthMethods(values?: readonly string[]): string | undefined {
+ if (!values?.length) {
+ return undefined;
+ }
+ return JSON.stringify([...new Set(values)].sort());
+}
+
+function preserveOmittedOAuthBindingFields(
+ existingOAuth: OAuthConfig,
+ updatedOAuth: OAuthConfig,
+): OAuthConfig {
+ return {
+ ...updatedOAuth,
+ ...(updatedOAuth.token_endpoint_auth_methods_supported === undefined &&
+ existingOAuth.token_endpoint_auth_methods_supported !== undefined && {
+ token_endpoint_auth_methods_supported: existingOAuth.token_endpoint_auth_methods_supported,
+ }),
+ ...(updatedOAuth.revocation_endpoint === undefined &&
+ existingOAuth.revocation_endpoint !== undefined && {
+ revocation_endpoint: existingOAuth.revocation_endpoint,
+ }),
+ ...(updatedOAuth.revocation_endpoint_auth_methods_supported === undefined &&
+ existingOAuth.revocation_endpoint_auth_methods_supported !== undefined && {
+ revocation_endpoint_auth_methods_supported:
+ existingOAuth.revocation_endpoint_auth_methods_supported,
+ }),
+ };
+}
+
+function getChangedOAuthSecretBindingFields(
+ existingConfig: MCPServerDocument['config'],
+ updatedConfig: ParsedServerConfig,
+): string[] {
+ const existingOAuth = existingConfig.oauth;
+ const updatedOAuth = updatedConfig.oauth;
+ if (!existingOAuth || !updatedOAuth) {
+ return [];
+ }
+
+ const fields = [
+ [
+ 'url',
+ normalizeOAuthUrl('url' in existingConfig ? existingConfig.url : undefined),
+ normalizeOAuthUrl(updatedConfig.url),
+ ],
+ [
+ 'oauth.authorization_url',
+ normalizeOAuthUrl(existingOAuth.authorization_url),
+ normalizeOAuthUrl(updatedOAuth.authorization_url),
+ ],
+ [
+ 'oauth.token_url',
+ normalizeOAuthUrl(existingOAuth.token_url),
+ normalizeOAuthUrl(updatedOAuth.token_url),
+ ],
+ ['oauth.client_id', existingOAuth.client_id, updatedOAuth.client_id],
+ [
+ 'oauth.token_exchange_method',
+ existingOAuth.token_exchange_method,
+ updatedOAuth.token_exchange_method,
+ ],
+ [
+ 'oauth.token_endpoint_auth_methods_supported',
+ normalizeOAuthMethods(existingOAuth.token_endpoint_auth_methods_supported),
+ normalizeOAuthMethods(updatedOAuth.token_endpoint_auth_methods_supported),
+ ],
+ [
+ 'oauth.revocation_endpoint',
+ normalizeOAuthUrl(existingOAuth.revocation_endpoint),
+ normalizeOAuthUrl(updatedOAuth.revocation_endpoint),
+ ],
+ [
+ 'oauth.revocation_endpoint_auth_methods_supported',
+ normalizeOAuthMethods(existingOAuth.revocation_endpoint_auth_methods_supported),
+ normalizeOAuthMethods(updatedOAuth.revocation_endpoint_auth_methods_supported),
+ ],
+ ] as const;
+
+ return fields.filter(([, existing, updated]) => existing !== updated).map(([field]) => field);
+}
+
/**
* DB backed config storage
* Handles CRUD Methods of dynamic mcp servers
@@ -225,15 +321,30 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {
/** Transformed user-provided API key config (adds customUserVars and headers) */
configToSave = this.transformUserApiKeyConfig(configToSave);
+ const existingOAuth = existingServer?.config?.oauth;
+ const existingOAuthSecret = existingOAuth?.client_secret;
+ const preservesOAuthSecret =
+ !config.oauth?.client_secret && !!existingOAuthSecret && !!configToSave.oauth;
+ if (preservesOAuthSecret && existingServer && existingOAuth && configToSave.oauth) {
+ configToSave = {
+ ...configToSave,
+ oauth: preserveOmittedOAuthBindingFields(existingOAuth, configToSave.oauth),
+ };
+ const changedFields = getChangedOAuthSecretBindingFields(existingServer.config, configToSave);
+ if (changedFields.length > 0) {
+ throw new MCPOAuthSecretReentryRequiredError(changedFields);
+ }
+ }
+
/** Encrypted config before storing in database */
configToSave = await this.encryptConfig(configToSave);
- if (!config.oauth?.client_secret && existingServer?.config?.oauth?.client_secret) {
+ if (preservesOAuthSecret && existingOAuthSecret && configToSave.oauth) {
configToSave = {
...configToSave,
oauth: {
...configToSave.oauth,
- client_secret: existingServer.config.oauth.client_secret,
+ client_secret: existingOAuthSecret,
},
};
}
diff --git a/packages/data-schemas/src/methods/token.spec.ts b/packages/data-schemas/src/methods/token.spec.ts
index 7e7c44c185..bc4335bd84 100644
--- a/packages/data-schemas/src/methods/token.spec.ts
+++ b/packages/data-schemas/src/methods/token.spec.ts
@@ -448,6 +448,55 @@ describe('Token Methods - Detailed Tests', () => {
expect(updated).toBeNull();
});
+ test('should condition updates on the OAuth credential-set metadata selector', async () => {
+ await Token.updateOne(
+ { token: 'update-token' },
+ { $set: { metadata: { credential_set_id: 'generation-a' } } },
+ );
+
+ const staleUpdate = await methods.updateToken(
+ {
+ token: 'update-token',
+ metadataCredentialSetId: 'generation-b',
+ },
+ { email: '[email protected]' },
+ );
+ expect(staleUpdate).toBeNull();
+
+ const currentUpdate = await methods.updateToken(
+ {
+ token: 'update-token',
+ metadataCredentialSetId: 'generation-a',
+ },
+ { email: '[email protected]' },
+ );
+ expect(currentUpdate?.email).toBe('[email protected]');
+ });
+
+ test('should condition legacy OAuth updates on a missing credential-set selector', async () => {
+ const legacyUpdate = await methods.updateToken(
+ {
+ token: 'update-token',
+ metadataCredentialSetId: null,
+ },
+ { email: '[email protected]' },
+ );
+ expect(legacyUpdate?.email).toBe('[email protected]');
+
+ await Token.updateOne(
+ { token: 'update-token' },
+ { $set: { metadata: { credential_set_id: 'generation-a' } } },
+ );
+ const staleLegacyUpdate = await methods.updateToken(
+ {
+ token: 'update-token',
+ metadataCredentialSetId: null,
+ },
+ { email: '[email protected]' },
+ );
+ expect(staleLegacyUpdate).toBeNull();
+ });
+
test('should update expiresAt when expiresIn is provided', async () => {
const beforeUpdate = Date.now();
const newExpiresIn = 7200;
@@ -580,6 +629,72 @@ describe('Token Methods - Detailed Tests', () => {
expect(remainingTokens.find((t) => t.identifier === 'oauth-identifier-456')).toBeUndefined();
});
+ test('should condition OAuth client deletion on the credential-set metadata selector', async () => {
+ const identifier = 'mcp:test-server:client';
+ await Token.create({
+ token: 'encrypted-client-registration',
+ userId: oauthUserId,
+ type: 'mcp_oauth_client',
+ identifier,
+ metadata: { credential_set_id: 'generation-b' },
+ createdAt: new Date(),
+ expiresAt: new Date(Date.now() + 3600000),
+ });
+
+ const staleDelete = await methods.deleteTokens({
+ userId: oauthUserId.toString(),
+ type: 'mcp_oauth_client',
+ identifier,
+ metadataCredentialSetId: 'generation-a',
+ });
+ expect(staleDelete.deletedCount).toBe(0);
+ expect(await Token.exists({ token: 'encrypted-client-registration' })).not.toBeNull();
+
+ const currentDelete = await methods.deleteTokens({
+ userId: oauthUserId.toString(),
+ type: 'mcp_oauth_client',
+ identifier,
+ metadataCredentialSetId: 'generation-b',
+ });
+ expect(currentDelete.deletedCount).toBe(1);
+ expect(await Token.exists({ token: 'encrypted-client-registration' })).toBeNull();
+ });
+
+ test('should delete only a legacy OAuth token with a missing credential-set selector', async () => {
+ const identifier = 'mcp:test-server:refresh';
+ await Token.create([
+ {
+ token: 'legacy-refresh-token',
+ userId: oauthUserId,
+ type: 'mcp_oauth_refresh',
+ identifier,
+ createdAt: new Date(),
+ expiresAt: new Date(Date.now() + 3600000),
+ },
+ {
+ token: 'tagged-refresh-token',
+ userId: oauthUserId,
+ type: 'mcp_oauth_refresh',
+ identifier,
+ metadata: { credential_set_id: 'generation-b' },
+ createdAt: new Date(),
+ expiresAt: new Date(Date.now() + 3600000),
+ },
+ ]);
+
+ const result = await methods.deleteTokens({
+ userId: oauthUserId.toString(),
+ type: 'mcp_oauth_refresh',
+ identifier,
+ token: 'legacy-refresh-token',
+ metadataCredentialSetId: null,
+ });
+
+ expect(result.deletedCount).toBe(1);
+ expect(await Token.exists({ token: 'legacy-refresh-token' })).toBeNull();
+ expect(await Token.exists({ token: 'tagged-refresh-token' })).not.toBeNull();
+ });
+
test('should delete tokens matching an identifier pattern', async () => {
await Token.create([
{
diff --git a/packages/data-schemas/src/methods/token.ts b/packages/data-schemas/src/methods/token.ts
index 412001cfa3..cbf640fcf8 100644
--- a/packages/data-schemas/src/methods/token.ts
+++ b/packages/data-schemas/src/methods/token.ts
@@ -40,13 +40,18 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
): Promise<IToken | null> {
try {
const Token = mongoose.models.Token;
+ const { metadataCredentialSetId, ...tokenQuery } = query;
+ const dbQuery: Record<string, unknown> = { ...tokenQuery };
+ if (metadataCredentialSetId !== undefined) {
+ dbQuery['metadata.credential_set_id'] = metadataCredentialSetId;
+ }
const dataToUpdate = { ...updateData };
if (updateData?.expiresIn !== undefined) {
dataToUpdate.expiresAt = new Date(Date.now() + updateData.expiresIn * 1000);
}
- return await Token.findOneAndUpdate(query, dataToUpdate, { new: true });
+ return await Token.findOneAndUpdate(dbQuery, dataToUpdate, { new: true });
} catch (error) {
logger.debug('An error occurred while updating token:', error);
throw error;
@@ -75,6 +80,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
if (query.identifier !== undefined) {
conditions.push({ identifier: query.identifier });
}
+ if (query.metadataCredentialSetId !== undefined) {
+ conditions.push({ 'metadata.credential_set_id': query.metadataCredentialSetId });
+ }
if (conditions.length === 0) {
throw new Error('At least one query parameter must be provided');
@@ -114,6 +122,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
if (query.identifier !== undefined) {
conditions.push({ identifier: query.identifier });
}
+ if (query.metadataCredentialSetId !== undefined) {
+ conditions.push({ 'metadata.credential_set_id': query.metadataCredentialSetId });
+ }
const token = await Token.findOne({ $and: conditions }, null, options).lean();
diff --git a/packages/data-schemas/src/types/token.ts b/packages/data-schemas/src/types/token.ts
index 560900c409..7385da6a32 100644
--- a/packages/data-schemas/src/types/token.ts
+++ b/packages/data-schemas/src/types/token.ts
@@ -28,6 +28,8 @@ export interface TokenQuery {
email?: string | null;
type?: string | null;
identifier?: string | RegExp | null;
+ /** Internal optimistic-concurrency selector for OAuth token record generations. */
+ metadataCredentialSetId?: string | null;
}
export interface TokenUpdateData {