Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🤫 refactor: Silent MCP OAuth Refresh on Mid-Session 401 (#13369)
Danny Avilac27d6b85a4f2
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.jsindex 7104910b39..9766760b8a 100644--- a/api/server/controllers/UserController.js+++ b/api/server/controllers/UserController.js@@ -1,5 +1,5 @@const mongoose = require('mongoose');-const { logger, webSearchKeys } = require('@librechat/data-schemas');+const { logger, getTenantId, webSearchKeys } = require('@librechat/data-schemas');const {getNewS3URL,needsRefresh,@@ -432,11 +432,24 @@ const clearStoredMCPOAuthState = async (userId, serverName) => {try {const flowsCache = getLogStores(CacheKeys.FLOWS);const flowManager = getFlowStateManager(flowsCache);- const flowId = MCPOAuthHandler.generateFlowId(userId, serverName);- const results = await Promise.allSettled([- flowManager.deleteFlow(flowId, 'mcp_get_tokens'),- flowManager.deleteFlow(flowId, 'mcp_oauth'),- ]);+ const baseFlowId = MCPOAuthHandler.generateFlowId(userId, serverName);+ const tenantId = getTenantId();+ const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(userId, serverName, tenantId);+ const oauthFlowId = MCPOAuthHandler.generateFlowId(userId, serverName, tenantId);+ const flowDeletes = [+ [tokenFlowId, 'mcp_get_tokens'],+ [oauthFlowId, 'mcp_oauth'],+ [baseFlowId, 'mcp_get_tokens'],+ [baseFlowId, 'mcp_oauth'],+ ].filter(+ ([flowId, type], index, deletes) =>+ deletes.findIndex(([candidateId, candidateType]) => {+ return candidateId === flowId && candidateType === type;+ }) === index,+ );+ const results = await Promise.allSettled(+ flowDeletes.map(([flowId, type]) => flowManager.deleteFlow(flowId, type)),+ );for (const result of results) {if (result.status === 'rejected') {logger.warn(diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.jsindex ef605beaab..a831184333 100644--- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js+++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js@@ -10,6 +10,7 @@ const mockGetMCPServersRegistry = jest.fn();jest.mock('@librechat/data-schemas', () => ({logger: { error: jest.fn(), info: jest.fn(), warn: jest.fn() },+ getTenantId: jest.fn(),webSearchKeys: [],}));@@ -22,7 +23,14 @@ jest.mock('librechat-data-provider', () => ({jest.mock('@librechat/api', () => ({MCPOAuthHandler: {- generateFlowId: jest.fn(() => 'user-1:test-server'),+ generateFlowId: jest.fn((userId, serverName, tenantId) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ }),+ generateTokenFlowId: jest.fn((userId, serverName, tenantId) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ }),revokeOAuthToken: jest.fn(),},MCPTokenStorage: {@@ -78,7 +86,7 @@ jest.mock('~/cache', () => ({getLogStores: (...args) => mockGetLogStores(...args),}));-const { logger } = require('@librechat/data-schemas');+const { logger, getTenantId } = require('@librechat/data-schemas');const { MCPTokenStorage, MCPOAuthHandler } = require('@librechat/api');const { updateUserPluginsController } = require('~/server/controllers/UserController');@@ -138,6 +146,7 @@ function setupMCPMocks() {beforeEach(() => {jest.clearAllMocks();+ getTenantId.mockReturnValue(undefined);});describe('updateUserPluginsController MCP OAuth cleanup', () => {@@ -231,6 +240,27 @@ describe('updateUserPluginsController MCP OAuth cleanup', () => {expect(MCPOAuthHandler.revokeOAuthToken).not.toHaveBeenCalled();});+ it('clears tenant-scoped and legacy OAuth flow state when tenant context exists', async () => {+ const { flowManager } = setupMCPMocks();+ getTenantId.mockReturnValue('tenant-a');+ MCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue(null);++ const res = createResponse();+ await updateUserPluginsController(createRequest(), res);++ expect(res.status).toHaveBeenCalledWith(200);+ expect(flowManager.deleteFlow).toHaveBeenCalledWith(+ 'tenant:tenant-a:user-1:test-server',+ 'mcp_get_tokens',+ );+ expect(flowManager.deleteFlow).toHaveBeenCalledWith(+ 'tenant:tenant-a:user-1:test-server',+ 'mcp_oauth',+ );+ expect(flowManager.deleteFlow).toHaveBeenCalledWith('user-1:test-server', 'mcp_get_tokens');+ expect(flowManager.deleteFlow).toHaveBeenCalledWith('user-1:test-server', 'mcp_oauth');+ });+it('clears stored OAuth token state when server config is missing', async () => {const { flowManager, registry } = setupMCPMocks();registry.getServerConfig.mockResolvedValue(undefined);diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.jsindex fd591aa440..1b8436233a 100644--- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js+++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js@@ -13,9 +13,11 @@ const mockDeleteTokens = jest.fn();const mockLoggerInfo = jest.fn();const mockLoggerWarn = jest.fn();const mockLoggerError = jest.fn();+const mockGetTenantId = jest.fn();jest.mock('@librechat/data-schemas', () => ({logger: { info: mockLoggerInfo, warn: mockLoggerWarn, error: mockLoggerError },+ getTenantId: (...args) => mockGetTenantId(...args),webSearchKeys: [],}));@@ -23,7 +25,14 @@ jest.mock('@librechat/api', () => {return {MCPOAuthHandler: {revokeOAuthToken: (...args) => mockRevokeOAuthToken(...args),- generateFlowId: (userId, serverName) => `${userId}:${serverName}`,+ generateFlowId: (userId, serverName, tenantId) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ },+ generateTokenFlowId: (userId, serverName, tenantId) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ },},MCPTokenStorage: {getTokens: (...args) => mockGetTokens(...args),@@ -151,6 +160,7 @@ function setupOAuthServerFound() {describe('maybeUninstallOAuthMCP', () => {beforeEach(() => {jest.clearAllMocks();+ mockGetTenantId.mockReturnValue(undefined);});test('is a no-op when pluginKey is not an MCP key', async () => {@@ -205,6 +215,20 @@ describe('maybeUninstallOAuthMCP', () => {);});+ test('clears tenant-scoped and legacy flow state when tenant context exists', async () => {+ setupOAuthServerFound();+ mockGetTenantId.mockReturnValue('tenant-a');+ mockGetClientInfoAndMetadata.mockResolvedValue(null);++ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);++ expect(mockDeleteFlow).toHaveBeenCalledTimes(4);+ expect(mockDeleteFlow).toHaveBeenCalledWith('tenant:tenant-a:user-123:acme', 'mcp_get_tokens');+ expect(mockDeleteFlow).toHaveBeenCalledWith('tenant:tenant-a:user-123:acme', 'mcp_oauth');+ expect(mockDeleteFlow).toHaveBeenCalledWith('user-123:acme', 'mcp_get_tokens');+ expect(mockDeleteFlow).toHaveBeenCalledWith('user-123:acme', 'mcp_oauth');+ });+test('revokes both tokens and runs cleanup on happy path', async () => {setupOAuthServerFound();mockGetTokens.mockResolvedValue({diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.jsindex 9d953e93f8..a55d6ef81d 100644--- a/api/server/routes/__tests__/mcp.spec.js+++ b/api/server/routes/__tests__/mcp.spec.js@@ -36,6 +36,16 @@ jest.mock('@librechat/api', () => {getFlowState: jest.fn(),completeOAuthFlow: jest.fn(),generateFlowId: jest.fn(),+ generateTokenFlowId: jest.fn(),+ parseFlowId: jest.fn(),+ buildStoredClientMetadata: jest.fn((metadata, resourceMetadata) =>+ metadata+ ? {+ ...metadata,+ ...(resourceMetadata?.resource && { resource: resourceMetadata.resource }),+ }+ : undefined,+ ),resolveStateToFlowId: jest.fn(async (state) => state),storeStateMapping: jest.fn(),deleteStateMapping: jest.fn(),@@ -184,11 +194,53 @@ describe('MCP Routes', () => {beforeEach(() => {jest.clearAllMocks();currentUser = undefined;- require('@librechat/api').MCPOAuthHandler.generateFlowId.mockImplementation(- (userId, serverName) => `${userId}:${serverName}`,- );mockResolveAllMcpConfigs.mockResolvedValue({});mockResolveMcpConfigNames.mockResolvedValue([]);+ const { MCPOAuthHandler } = require('@librechat/api');+ const { getTenantId } = require('@librechat/data-schemas');+ getTenantId.mockReturnValue(undefined);+ MCPOAuthHandler.generateFlowId.mockImplementation((userId, serverName, tenantId) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ });+ MCPOAuthHandler.generateTokenFlowId.mockImplementation((userId, serverName, tenantId) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ });+ MCPOAuthHandler.parseFlowId.mockImplementation((flowId) => {+ const parts = flowId.split(':');+ if (parts[0] === 'tenant') {+ if (parts.length < 4 || !parts[1] || !parts[2]) {+ return null;+ }+ let tenantId;+ try {+ tenantId = decodeURIComponent(parts[1]);+ } catch {+ return null;+ }+ return {+ tenantId,+ userId: parts[2],+ serverName: parts.slice(3).join(':'),+ };+ }+ if (parts.length < 2 || !parts[0]) {+ return null;+ }+ return {+ userId: parts[0],+ serverName: parts.slice(1).join(':'),+ };+ });+ MCPOAuthHandler.buildStoredClientMetadata.mockImplementation((metadata, resourceMetadata) =>+ metadata+ ? {+ ...metadata,+ ...(resourceMetadata?.resource && { resource: resourceMetadata.resource }),+ }+ : undefined,+ );mockMCPUseAllowed = true;/*** Reset registry method implementations every test. `clearAllMocks` resets@@ -235,6 +287,53 @@ describe('MCP Routes', () => {expect(mockRegistryInstance.getServerConfig).not.toHaveBeenCalled();});+ it('should accept tenant-scoped flow IDs when a tenant is active', async () => {+ const { getTenantId } = require('@librechat/data-schemas');+ getTenantId.mockReturnValue('tenant-a');+ const tenantFlowId = 'tenant:tenant-a:test-user-id:test-server';+ const mockFlowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ status: 'PENDING',+ createdAt: Date.now(),+ metadata: {+ serverName: 'test-server',+ userId: 'test-user-id',+ authorizationUrl: 'https://oauth.example.com/auth?state=stored-state',+ },+ }),+ };++ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);++ const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({+ userId: 'test-user-id',+ flowId: tenantFlowId,+ });++ expect(response.status).toBe(302);+ expect(response.headers.location).toBe('https://oauth.example.com/auth?state=stored-state');+ expect(mockFlowManager.getFlowState).toHaveBeenCalledWith(tenantFlowId, 'mcp_oauth');+ });++ it('should reject non-tenant flow IDs when a tenant is active', async () => {+ const { getTenantId } = require('@librechat/data-schemas');+ getTenantId.mockReturnValue('tenant-a');+ const mockFlowManager = { getFlowState: jest.fn() };++ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);++ const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({+ userId: 'test-user-id',+ flowId: 'test-user-id:test-server',+ });++ expect(response.status).toBe(403);+ expect(response.body).toEqual({ error: 'Flow mismatch' });+ expect(mockFlowManager.getFlowState).not.toHaveBeenCalled();+ });+it('should reject stored authorization URL when flow is no longer pending', async () => {const mockFlowManager = {getFlowState: jest.fn().mockResolvedValue({@@ -303,6 +402,7 @@ describe('MCP Routes', () => {null,undefined,null,+ undefined,);expect(MCPOAuthHandler.deleteStateMapping).toHaveBeenCalledWith('old-state-value',@@ -524,6 +624,26 @@ describe('MCP Routes', () => {expect(response.headers.location).toBe(`${basePath}/oauth/error?error=invalid_client`);expect(mockFlowManager.failFlow).not.toHaveBeenCalled();});++ it('should redirect instead of hanging when OAuth error flow ID is malformed', async () => {+ const mockFlowManager = {+ failFlow: jest.fn(),+ };++ getLogStores.mockReturnValueOnce({});+ require('~/config').getFlowStateManager.mockReturnValueOnce(mockFlowManager);+ MCPOAuthHandler.resolveStateToFlowId.mockResolvedValueOnce('malformed-flow-id');++ const response = await request(app).get('/api/mcp/test-server/oauth/callback').query({+ error: 'invalid_client',+ state: 'opaque-state',+ });+ const basePath = getBasePath();++ expect(response.status).toBe(302);+ expect(response.headers.location).toBe(`${basePath}/oauth/error?error=invalid_client`);+ expect(mockFlowManager.failFlow).not.toHaveBeenCalled();+ });});it('should redirect to error page when code is missing', async () => {@@ -800,6 +920,140 @@ describe('MCP Routes', () => {);});+ it('should clear tenant-scoped token flow state after storing callback tokens', async () => {+ const mockFlowManager = {+ getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING' }),+ completeFlow: jest.fn().mockResolvedValue(),+ deleteFlow: jest.fn().mockResolvedValue(true),+ };+ const mockFlowState = {+ serverName: 'test-server',+ userId: 'test-user-id',+ metadata: {+ toolFlowId: 'tool-flow-123',+ token_endpoint: 'https://auth.example.com/token',+ },+ resourceMetadata: { resource: 'https://api.example.com/' },+ clientInfo: {},+ codeVerifier: 'test-verifier',+ tenantId: 'tenant-a',+ };+ const mockTokens = {+ access_token: 'test-access-token',+ refresh_token: 'test-refresh-token',+ };++ MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);+ MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);+ MCPTokenStorage.storeTokens.mockResolvedValue();+ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);+ require('~/config').getOAuthReconnectionManager.mockReturnValue({+ clearReconnection: jest.fn(),+ });+ require('~/config').getMCPManager.mockReturnValue({+ getUserConnection: jest.fn().mockResolvedValue({+ fetchTools: jest.fn().mockResolvedValue([]),+ }),+ });+ const { getCachedTools, setCachedTools } = require('~/server/services/Config');+ getCachedTools.mockResolvedValue({});+ setCachedTools.mockResolvedValue();++ const flowId = 'test-user-id:test-server';+ const csrfToken = generateTestCsrfToken(flowId);++ const response = await request(app)+ .get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', [`oauth_csrf=${csrfToken}`])+ .query({+ code: 'test-auth-code',+ state: flowId,+ });++ expect(response.status).toBe(302);+ expect(MCPTokenStorage.storeTokens).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: expect.objectContaining({+ resource: 'https://api.example.com/',+ }),+ }),+ );+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith(+ 'tenant:tenant-a:test-user-id:test-server',+ 'mcp_get_tokens',+ );+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith(flowId, 'mcp_get_tokens');+ });++ it('should complete pending token flow waiters after storing callback tokens', async () => {+ const mockFlowManager = {+ getFlowState: jest.fn().mockImplementation((id, type) => {+ if (type === 'mcp_get_tokens' && id === 'tenant:tenant-a:test-user-id:test-server') {+ return Promise.resolve({+ type: 'mcp_get_tokens',+ status: 'PENDING',+ });+ }+ return Promise.resolve({ status: 'PENDING' });+ }),+ completeFlow: jest.fn().mockResolvedValue(true),+ deleteFlow: jest.fn().mockResolvedValue(true),+ };+ const mockFlowState = {+ serverName: 'test-server',+ userId: 'test-user-id',+ metadata: {},+ clientInfo: {},+ codeVerifier: 'test-verifier',+ tenantId: 'tenant-a',+ };+ const mockTokens = {+ access_token: 'fresh-access-token',+ refresh_token: 'fresh-refresh-token',+ };++ MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);+ MCPOAuthHandler.completeOAuthFlow.mockResolvedValue(mockTokens);+ MCPTokenStorage.storeTokens.mockResolvedValue();+ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);+ require('~/config').getOAuthReconnectionManager.mockReturnValue({+ clearReconnection: jest.fn(),+ });+ require('~/config').getMCPManager.mockReturnValue({+ getUserConnection: jest.fn().mockResolvedValue({+ fetchTools: jest.fn().mockResolvedValue([]),+ }),+ });+ const { getCachedTools, setCachedTools } = require('~/server/services/Config');+ getCachedTools.mockResolvedValue({});+ setCachedTools.mockResolvedValue();++ const flowId = 'test-user-id:test-server';+ const csrfToken = generateTestCsrfToken(flowId);++ const response = await request(app)+ .get('/api/mcp/test-server/oauth/callback')+ .set('Cookie', [`oauth_csrf=${csrfToken}`])+ .query({+ code: 'test-auth-code',+ state: flowId,+ });++ expect(response.status).toBe(302);+ expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(+ 'tenant:tenant-a:test-user-id:test-server',+ 'mcp_get_tokens',+ mockTokens,+ );+ expect(mockFlowManager.deleteFlow).not.toHaveBeenCalledWith(+ 'tenant:tenant-a:test-user-id:test-server',+ 'mcp_get_tokens',+ );+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith(flowId, 'mcp_get_tokens');+ });+it('should use oauthHeaders from flow state when present', async () => {const mockFlowManager = {getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING' }),@@ -1210,6 +1464,49 @@ describe('MCP Routes', () => {});});+ it('should return tokens for a tenant-prefixed flow owned by the user', async () => {+ const { getTenantId } = require('@librechat/data-schemas');+ const mockFlowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ status: 'COMPLETED',+ result: {+ access_token: 'tenant-access-token',+ },+ }),+ };++ getTenantId.mockReturnValue('tenant-a');+ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);++ const response = await request(app).get(+ '/api/mcp/oauth/tokens/tenant:tenant-a:test-user-id:test-server',+ );++ expect(response.status).toBe(200);+ expect(response.body).toEqual({+ tokens: {+ access_token: 'tenant-access-token',+ },+ });+ expect(mockFlowManager.getFlowState).toHaveBeenCalledWith(+ 'tenant:tenant-a:test-user-id:test-server',+ 'mcp_oauth',+ );+ });++ it('should reject tenant-prefixed token flow access from another tenant', async () => {+ const { getTenantId } = require('@librechat/data-schemas');+ getTenantId.mockReturnValue('tenant-b');++ const response = await request(app).get(+ '/api/mcp/oauth/tokens/tenant:tenant-a:test-user-id:test-server',+ );++ expect(response.status).toBe(403);+ expect(response.body).toEqual({ error: 'Access denied' });+ });+it('should return 401 when user is not authenticated', async () => {const unauthApp = express();unauthApp.use(express.json());@@ -1302,6 +1599,48 @@ describe('MCP Routes', () => {});});+ it('should return flow status for a tenant-prefixed flow owned by the user', async () => {+ const { getTenantId } = require('@librechat/data-schemas');+ const mockFlowManager = {+ getFlowState: jest.fn().mockResolvedValue({+ status: 'PENDING',+ error: null,+ }),+ };++ getTenantId.mockReturnValue('tenant-a');+ getLogStores.mockReturnValue({});+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);++ const response = await request(app).get(+ '/api/mcp/oauth/status/tenant:tenant-a:test-user-id:test-server',+ );++ expect(response.status).toBe(200);+ expect(response.body).toEqual({+ status: 'PENDING',+ completed: false,+ failed: false,+ error: null,+ });+ expect(mockFlowManager.getFlowState).toHaveBeenCalledWith(+ 'tenant:tenant-a:test-user-id:test-server',+ 'mcp_oauth',+ );+ });++ it('should reject tenant-prefixed status access from another tenant', async () => {+ const { getTenantId } = require('@librechat/data-schemas');+ getTenantId.mockReturnValue('tenant-b');++ const response = await request(app).get(+ '/api/mcp/oauth/status/tenant:tenant-a:test-user-id:test-server',+ );++ expect(response.status).toBe(403);+ expect(response.body).toEqual({ error: 'Access denied' });+ });+it('should return 403 when flowId does not match authenticated user', async () => {const response = await request(app).get('/api/mcp/oauth/status/other-user-id:test-server');diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.jsindex 41c1bcd7bd..a216a897b4 100644--- a/api/server/routes/mcp.js+++ b/api/server/routes/mcp.js@@ -53,6 +53,29 @@ const router = Router();const OAUTH_CSRF_COOKIE_PATH = '/api/mcp';+const getOAuthFlowId = (userId, serverName) =>+ MCPOAuthHandler.generateFlowId(userId, serverName, getTenantId());++const canAccessOAuthFlow = (flowId, userId) => {+ const parsed = MCPOAuthHandler.parseFlowId(flowId);+ if (!parsed) {+ return false;+ }+ if (parsed.tenantId && parsed.tenantId !== getTenantId()) {+ return false;+ }+ return parsed.userId === userId || parsed.userId === 'system';+};++const clearGetTokensFlow = async ({ flowManager, flowId, tokens }) => {+ const state = await flowManager.getFlowState(flowId, 'mcp_get_tokens');+ if (state?.type === 'mcp_get_tokens' && state.status === 'PENDING') {+ await flowManager.completeFlow(flowId, 'mcp_get_tokens', tokens);+ return;+ }+ await flowManager.deleteFlow(flowId, 'mcp_get_tokens');+};+const checkMCPUsePermissions = generateCheckAccess({permissionType: PermissionTypes.MCP_SERVERS,permissions: [Permissions.USE],@@ -88,7 +111,7 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, asyncreturn res.status(403).json({ error: 'User mismatch' });}- const expectedFlowId = MCPOAuthHandler.generateFlowId(user.id, serverName);+ const expectedFlowId = getOAuthFlowId(user.id, serverName);if (typeof flowId !== 'string' || flowId !== expectedFlowId) {logger.error('[MCP OAuth] Invalid flow ID for initiate request', {serverName,@@ -173,6 +196,7 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, asyncallowedDomains,undefined,allowedAddresses,+ getTenantId(),);logger.debug('[MCP OAuth] OAuth flow initiated', { oauthFlowId, authorizationUrl });@@ -218,16 +242,21 @@ router.get('/:serverName/oauth/callback', async (req, res) => {const flowManager = getFlowStateManager(flowsCache);const flowId = await MCPOAuthHandler.resolveStateToFlowId(state, flowManager);if (flowId) {- const flowParts = flowId.split(':');- const [flowUserId] = flowParts;- const hasCsrf = validateOAuthCsrf(req, res, flowId, OAUTH_CSRF_COOKIE_PATH);- const hasSession = !hasCsrf && validateOAuthSession(req, flowUserId);- if (hasCsrf || hasSession) {- await flowManager.failFlow(flowId, 'mcp_oauth', String(oauthError));- logger.debug('[MCP OAuth] Marked flow as FAILED with OAuth error', {+ const parsed = MCPOAuthHandler.parseFlowId(flowId);+ if (!parsed) {+ logger.warn('[MCP OAuth] Invalid flow ID format for OAuth error callback', {flowId,- error: oauthError,});+ } else {+ const hasCsrf = validateOAuthCsrf(req, res, flowId, OAUTH_CSRF_COOKIE_PATH);+ const hasSession = !hasCsrf && validateOAuthSession(req, parsed.userId);+ if (hasCsrf || hasSession) {+ await flowManager.failFlow(flowId, 'mcp_oauth', String(oauthError));+ logger.debug('[MCP OAuth] Marked flow as FAILED with OAuth error', {+ flowId,+ error: oauthError,+ });+ }}}} catch (err) {@@ -259,16 +288,14 @@ router.get('/:serverName/oauth/callback', async (req, res) => {}logger.debug('[MCP OAuth] Resolved flow ID from state', { flowId });- const flowParts = flowId.split(':');- if (flowParts.length < 2 || !flowParts[0] || !flowParts[1]) {+ const parsedFlowId = MCPOAuthHandler.parseFlowId(flowId);+ if (!parsedFlowId) {logger.error('[MCP OAuth] Invalid flow ID format', { flowId });return res.redirect(`${basePath}/oauth/error?error=invalid_state`);}- const [flowUserId] = flowParts;-const hasCsrf = validateOAuthCsrf(req, res, flowId, OAUTH_CSRF_COOKIE_PATH);- const hasSession = !hasCsrf && validateOAuthSession(req, flowUserId);+ const hasSession = !hasCsrf && validateOAuthSession(req, parsedFlowId.userId);let hasActiveFlow = false;if (!hasCsrf && !hasSession) {const pendingFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');@@ -365,7 +392,10 @@ router.get('/:serverName/oauth/callback', async (req, res) => {updateToken: db.updateToken,findToken: db.findToken,clientInfo: flowState.clientInfo,- metadata: flowState.metadata,+ metadata: MCPOAuthHandler.buildStoredClientMetadata(+ flowState.metadata,+ flowState.resourceMetadata,+ ),});logger.debug('[MCP OAuth] Stored OAuth tokens prior to reconnection', {serverName,@@ -382,7 +412,23 @@ router.get('/:serverName/oauth/callback', async (req, res) => {*/if (typeof flowManager?.deleteFlow === 'function') {try {- await flowManager.deleteFlow(flowId, 'mcp_get_tokens');+ const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(+ flowState.userId,+ serverName,+ flowState.tenantId,+ );+ await clearGetTokensFlow({+ flowManager,+ flowId: tokenFlowId,+ tokens,+ });+ if (tokenFlowId !== flowId) {+ await clearGetTokensFlow({+ flowManager,+ flowId,+ tokens,+ });+ }} catch (error) {logger.warn('[MCP OAuth] Failed to clear cached token flow state', error);}@@ -467,7 +513,7 @@ router.get('/oauth/tokens/:flowId', requireJwtAuth, async (req, res) => {return res.status(401).json({ error: 'User not authenticated' });}- if (!flowId.startsWith(`${user.id}:`) && !flowId.startsWith('system:')) {+ if (!canAccessOAuthFlow(flowId, user.id)) {return res.status(403).json({ error: 'Access denied' });}@@ -504,7 +550,7 @@ router.post('/:serverName/oauth/bind', requireJwtAuth, setOAuthSession, async (rreturn res.status(401).json({ error: 'User not authenticated' });}- const flowId = MCPOAuthHandler.generateFlowId(user.id, serverName);+ const flowId = getOAuthFlowId(user.id, serverName);setOAuthCsrfCookie(res, flowId, OAUTH_CSRF_COOKIE_PATH);res.json({ success: true });@@ -527,7 +573,7 @@ router.get('/oauth/status/:flowId', requireJwtAuth, async (req, res) => {return res.status(401).json({ error: 'User not authenticated' });}- if (!flowId.startsWith(`${user.id}:`) && !flowId.startsWith('system:')) {+ if (!canAccessOAuthFlow(flowId, user.id)) {return res.status(403).json({ error: 'Access denied' });}@@ -568,7 +614,7 @@ router.post('/oauth/cancel/:serverName', requireJwtAuth, async (req, res) => {const flowsCache = getLogStores(CacheKeys.FLOWS);const flowManager = getFlowStateManager(flowsCache);- const flowId = MCPOAuthHandler.generateFlowId(user.id, serverName);+ const flowId = getOAuthFlowId(user.id, serverName);const flowState = await flowManager.getFlowState(flowId, 'mcp_oauth');if (!flowState) {@@ -656,7 +702,7 @@ router.post(const { success, message, oauthRequired, oauthUrl } = result;if (oauthRequired) {- const flowId = MCPOAuthHandler.generateFlowId(user.id, serverName);+ const flowId = getOAuthFlowId(user.id, serverName);setOAuthCsrfCookie(res, flowId, OAUTH_CSRF_COOKIE_PATH);}diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 2da3744f44..4c6daa3682 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -95,6 +95,13 @@ function evictStale(map, ttl) {const unavailableMsg ="This tool's MCP server is temporarily unavailable. Please try again shortly.";+function getOAuthFlowId(userId, serverName, tenantId = getTenantId()) {+ if (!tenantId) {+ return MCPOAuthHandler.generateFlowId(userId, serverName);+ }+ return MCPOAuthHandler.generateFlowId(userId, serverName, tenantId);+}+async function getAppConfigForRequest(req) {const user = req?.user;return await getAppConfigForUser(user?.id, user);@@ -344,12 +351,13 @@ function createOAuthEnd({ res, stepId, toolCall, streamId = null }) {* @param {string} params.userId - The ID of the user.* @param {string} params.serverName - The name of the server.* @param {string} params.toolName - The name of the tool.+ * @param {string} [params.tenantId] - The tenant ID for the current request.* @param {FlowStateManager<any>} params.flowManager - The flow manager instance.*/-function createAbortHandler({ userId, serverName, toolName, flowManager }) {+function createAbortHandler({ userId, serverName, toolName, tenantId, flowManager }) {return function () {logger.info(`[MCP][User: ${userId}][${serverName}][${toolName}] Tool call aborted`);- const flowId = MCPOAuthHandler.generateFlowId(userId, serverName);+ const flowId = getOAuthFlowId(userId, serverName, tenantId);// Clean up both mcp_oauth and mcp_get_tokens flowsflowManager.failFlow(flowId, 'mcp_oauth', new Error('Tool call aborted'));flowManager.failFlow(flowId, 'mcp_get_tokens', new Error('Tool call aborted'));@@ -423,7 +431,8 @@ async function reconnectServer({});// Set up abort handler to clean up OAuth flows if request is aborted- const oauthFlowId = MCPOAuthHandler.generateFlowId(user.id, serverName);+ const tenantId = user?.tenantId ?? getTenantId();+ const oauthFlowId = getOAuthFlowId(user.id, serverName, tenantId);const abortHandler = () => {logger.info(`[MCP][User: ${user.id}][${serverName}] Tool loading aborted, cleaning up OAuth flows`,@@ -788,7 +797,8 @@ function createToolInstance({});if (derivedSignal) {- abortHandler = createAbortHandler({ userId, serverName, toolName, flowManager });+ const tenantId = config?.configurable?.user?.tenantId ?? getTenantId();+ abortHandler = createAbortHandler({ userId, serverName, toolName, tenantId, flowManager });derivedSignal.addEventListener('abort', abortHandler, { once: true });}@@ -915,12 +925,13 @@ async function getMCPSetupData(userId, options = {}) {* Check OAuth flow status for a user and server* @param {string} userId - The user ID* @param {string} serverName - The server name+ * @param {string} [tenantId] - The tenant ID for the current request.* @returns {Object} Object containing hasActiveFlow and hasFailedFlow flags*/-async function checkOAuthFlowStatus(userId, serverName) {+async function checkOAuthFlowStatus(userId, serverName, tenantId = getTenantId()) {const flowsCache = getLogStores(CacheKeys.FLOWS);const flowManager = getFlowStateManager(flowsCache);- const flowId = MCPOAuthHandler.generateFlowId(userId, serverName);+ const flowId = getOAuthFlowId(userId, serverName, tenantId);try {const flowState = await flowManager.getFlowState(flowId, 'mcp_oauth');diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex 564aca74b5..30fbc6442b 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -1,5 +1,6 @@// Mock all dependencies - define mocks before imports-// Mock all dependencies+const mockGetTenantId = jest.fn();+jest.mock('@librechat/data-schemas', () => ({logger: {debug: jest.fn(),@@ -7,6 +8,7 @@ jest.mock('@librechat/data-schemas', () => ({info: jest.fn(),warn: jest.fn(),},+ getTenantId: mockGetTenantId,}));// Create mock registry instance@@ -94,6 +96,7 @@ describe('tests for the new helper functions used by the MCP connection status ebeforeEach(() => {jest.clearAllMocks();jest.spyOn(MCPOAuthHandler, 'generateFlowId');+ mockGetTenantId.mockReturnValue(undefined);mockGetMCPManager = require('~/config').getMCPManager;mockGetFlowStateManager = require('~/config').getFlowStateManager;@@ -360,6 +363,28 @@ describe('tests for the new helper functions used by the MCP connection status e);});+ it('should check the tenant-scoped OAuth flow when tenant context exists', async () => {+ mockGetTenantId.mockReturnValue('tenant/a');+ MCPOAuthHandler.generateFlowId.mockReturnValue('tenant-flow-id');+ const mockFlowState = {+ status: 'PENDING',+ createdAt: Date.now() - 60000,+ ttl: 180000,+ };+ const mockFlowManager = { getFlowState: jest.fn(() => mockFlowState) };+ mockGetFlowStateManager.mockReturnValue(mockFlowManager);++ const result = await checkOAuthFlowStatus(mockUserId, mockServerName);++ expect(MCPOAuthHandler.generateFlowId).toHaveBeenCalledWith(+ mockUserId,+ mockServerName,+ 'tenant/a',+ );+ expect(mockFlowManager.getFlowState).toHaveBeenCalledWith('tenant-flow-id', 'mcp_oauth');+ expect(result).toEqual({ hasActiveFlow: true, hasFailedFlow: false });+ });+it('should return false flags for other statuses', async () => {const mockFlowState = {status: 'COMPLETED',@@ -749,6 +774,7 @@ describe('User parameter passing tests', () => {beforeEach(() => {jest.clearAllMocks();+ mockGetTenantId.mockReturnValue(undefined);mockReinitMCPServer = require('./Tools/mcp').reinitMCPServer;mockGetMCPManager = require('~/config').getMCPManager;mockGetFlowStateManager = require('~/config').getFlowStateManager;@@ -811,6 +837,57 @@ describe('User parameter passing tests', () => {expect(mockReinitMCPServer.mock.calls[0][0].user).toBe(mockUser);});+ it('should fail tenant-scoped OAuth flows when tool loading is aborted', async () => {+ const mockUser = { id: 'tenant-user', name: 'Tenant User' };+ const mockRes = { write: jest.fn(), flush: jest.fn() };+ const abortController = new AbortController();+ const mockFlowManager = {+ createFlowWithHandler: jest.fn(),+ failFlow: jest.fn(),+ };+ mockGetTenantId.mockReturnValue('tenant/a');+ mockGetFlowStateManager.mockReturnValue(mockFlowManager);+ MCPOAuthHandler.generateFlowId.mockReturnValue('tenant-flow-id');++ let resolveReinit;+ mockReinitMCPServer.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveReinit = resolve;+ }),+ );++ const createToolsPromise = createMCPTools({+ res: mockRes,+ user: mockUser,+ serverName: 'tenant-abort-server',+ provider: 'openai',+ signal: abortController.signal,+ userMCPAuthMap: {},+ config: { type: 'stdio' },+ });++ abortController.abort();+ resolveReinit({ tools: [], availableTools: {} });+ await createToolsPromise;++ expect(MCPOAuthHandler.generateFlowId).toHaveBeenCalledWith(+ mockUser.id,+ 'tenant-abort-server',+ 'tenant/a',+ );+ expect(mockFlowManager.failFlow).toHaveBeenCalledWith(+ 'tenant-flow-id',+ 'mcp_oauth',+ expect.any(Error),+ );+ expect(mockFlowManager.failFlow).toHaveBeenCalledWith(+ 'tenant-flow-id',+ 'mcp_get_tokens',+ expect.any(Error),+ );+ });+it('should throw error if user is not provided', async () => {const mockRes = { write: jest.fn(), flush: jest.fn() };diff --git a/packages/api/src/flow/manager.test.ts b/packages/api/src/flow/manager.test.tsindex 7112a822d4..d955f98f4e 100644--- a/packages/api/src/flow/manager.test.ts+++ b/packages/api/src/flow/manager.test.ts@@ -71,6 +71,24 @@ describe('FlowStateManager', () => {expect(result2).toBe('result');});+ it('should return the externally completed result when handler loses completion race', async () => {+ const flowId = 'race-flow';+ const type = 'test-type';++ const result = await flowManager.createFlowWithHandler(flowId, type, async () => {+ await flowManager.completeFlow(flowId, type, 'fresh-result');+ return 'stale-result';+ });++ expect(result).toBe('fresh-result');+ await expect(flowManager.getFlowState(flowId, type)).resolves.toEqual(+ expect.objectContaining({+ status: 'COMPLETED',+ result: 'fresh-result',+ }),+ );+ });+it('should handle flow timeout correctly', async () => {const flowId = 'timeout-flow';const type = 'test-type';@@ -157,6 +175,25 @@ describe('FlowStateManager', () => {await expect(flowPromise).rejects.toThrow('failure');}, 15000);++ it('should not overwrite a completed flow with a late failure', async () => {+ const flowId = 'completed-race-flow';+ const type = 'test-type';+ const flowKey = `${type}:${flowId}`;++ await flowManager.initFlow(flowId, type);+ await flowManager.completeFlow(flowId, type, 'success');++ const result = await flowManager.failFlow(flowId, type, new Error('late failure'));+ const state = await store.get(flowKey);++ expect(result).toBe(true);+ expect(state).toMatchObject({+ status: 'COMPLETED',+ result: 'success',+ });+ expect(state?.error).toBeUndefined();+ });});describe('initFlow', () => {diff --git a/packages/api/src/flow/manager.ts b/packages/api/src/flow/manager.tsindex 27de97bbe6..bbf335fd97 100644--- a/packages/api/src/flow/manager.ts+++ b/packages/api/src/flow/manager.ts@@ -354,6 +354,17 @@ export class FlowStateManager<T = unknown> {return false;}+ if (flowState.status === 'COMPLETED') {+ logger.debug(+ '[FlowStateManager] Flow already completed, skipping failure to prevent overwrite',+ {+ flowId,+ type,+ },+ );+ return true;+ }+const updatedState: FlowState = {...flowState,status: 'FAILED',@@ -413,6 +424,10 @@ export class FlowStateManager<T = unknown> {try {const result = await handler();await this.completeFlow(flowId, type, result);+ const completedState = (await this.keyv.get(flowKey)) as FlowState<T> | undefined;+ if (completedState?.status === 'COMPLETED' && completedState.result !== undefined) {+ return completedState.result;+ }return result;} catch (error) {await this.failFlow(flowId, type, error instanceof Error ? error : new Error(String(error)));diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 7669c451ba..be1639048e 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -1,8 +1,13 @@-import { logger, getTenantId } from '@librechat/data-schemas';+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';import type { Tool } from '@modelcontextprotocol/sdk/types.js';-import type { TokenMethods } from '@librechat/data-schemas';-import type { MCPOAuthTokens, OAuthMetadata, MCPOAuthFlowMetadata } from '~/mcp/oauth';+import type {+ MCPOAuthTokens,+ OAuthMetadata,+ MCPOAuthFlowMetadata,+ OAuthProtectedResourceMetadata,+} from '~/mcp/oauth';import type { OboTokenResolver, OboTrustChecker } from '~/mcp/oauth/obo';import type { FlowStateManager } from '~/flow/manager';import type * as t from './types';@@ -28,6 +33,14 @@ export interface ToolDiscoveryResult {oauthUrl: string | null;}+type OAuthRequiredEvent = {+ serverUrl?: string;+ error?: unknown;+ status?: number;+ statusCode?: number;+ skipSilentRefresh?: boolean;+};+/*** Factory for creating MCP connections with optional OAuth authentication.* Handles OAuth flows, token management, and connection retry logic.@@ -47,13 +60,45 @@ export class MCPConnectionFactory {protected readonly user?: t.OAuthConnectionOptions['user'];protected readonly flowManager?: FlowStateManager<MCPOAuthTokens | null>;protected readonly tokenMethods?: TokenMethods;- protected readonly signal?: AbortSignal;- protected readonly oauthStart?: t.OAuthStartHandler;- protected readonly oauthEnd?: () => Promise<void>;- protected readonly returnOnOAuth?: boolean;+ protected signal?: AbortSignal;+ protected oauthStart?: t.OAuthStartHandler;+ protected oauthEnd?: () => Promise<void>;+ protected returnOnOAuth?: boolean;protected readonly connectionTimeout?: number;protected readonly oboTokenResolver?: OboTokenResolver;protected readonly oboTrustChecker?: OboTrustChecker;+ private connectionReady = false;+ /**+ * Snapshot of the tenant context at factory construction time. Captured eagerly+ * because the OAuth handler runs later inside an EventEmitter callback,+ * outside the original request's async context - `getTenantId()` called+ * from the listener would return the wrong tenant (or none at all).+ */+ protected readonly tenantId?: string;+ protected readonly tenantContext?: TenantContext;++ /**+ * Process-local in-flight silent refresh promises, keyed by+ * `tenantId:userId:serverName`. 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.+ * The map only holds in-flight promises (no result caching), so each new 401+ * after the previous attempt resolves triggers a fresh redemption.+ *+ * NOTE: this is a single-process lock. Across multiple worker processes the+ * race with `getOAuthTokens()`'s `mcp_get_tokens` flow remains; that's an+ * inherent limitation of process-local coalescing and tracked separately.+ */+ private static inflightSilentRefreshes = new Map<string, Promise<MCPOAuthTokens | null>>();++ /**+ * Silent refresh is a best-effort optimization before interactive OAuth.+ * Keep the cap short so a stalled refresh still leaves most of the factory+ * connect budget for OAuth discovery, registration, and `oauthStart`.+ */+ private static readonly SILENT_REFRESH_TIMEOUT_MS = 5_000;+ private static readonly SILENT_REFRESH_ABORT_GRACE_MS = 1_000;/** Creates a new MCP connection with optional OAuth support */static async create(@@ -64,6 +109,15 @@ export class MCPConnectionFactory {return factory.createConnection();}+ static attachRequestOAuthHandler(+ basic: t.BasicConnectionOptions,+ oauth: t.OAuthConnectionOptions,+ connection: MCPConnection,+ ): () => void {+ const factory = new this(basic, oauth);+ return factory.handleOAuthEvents(connection, 'oauthReauthenticationRequired');+ }+/*** Discovers tools from an MCP server, even when OAuth is required.* Per MCP spec, tool listing should be possible without authentication.@@ -232,18 +286,22 @@ export class MCPConnectionFactory {basic: t.BasicConnectionOptions,options?: t.OAuthConnectionOptions | t.UserConnectionContext,) {- this.serverConfig = processMCPEnv({- user: options?.user,- body: options?.requestBody,- dbSourced: basic.dbSourced,- options: basic.serverConfig,- customUserVars: options?.customUserVars,- });+ this.serverConfig = basic.skipEnvProcessing+ ? basic.serverConfig+ : processMCPEnv({+ user: options?.user,+ body: options?.requestBody,+ dbSourced: basic.dbSourced,+ options: basic.serverConfig,+ customUserVars: options?.customUserVars,+ });this.serverName = basic.serverName;this.useSSRFProtection = basic.useSSRFProtection === true;this.allowedDomains = basic.allowedDomains;this.allowedAddresses = basic.allowedAddresses;this.connectionTimeout = options?.connectionTimeout;+ this.tenantContext = tenantStorage?.getStore?.();+ this.tenantId = this.tenantContext?.tenantId ?? getTenantId();this.logPrefix = options?.user? `[MCP][${basic.serverName}][${options.user.id}]`: `[MCP][${basic.serverName}]`;@@ -361,9 +419,10 @@ export class MCPConnectionFactory {await this.initiateOAuthBeforeConnect(connection);}await this.attemptToConnect(connection);- if (cleanupOAuthHandlers) {- cleanupOAuthHandlers();- }+ this.connectionReady = true;+ // Keep the `oauthRequired` listener for cached-connection 401 recovery,+ // but drop response/tool-call callbacks from the completed request.+ this.releaseRequestScopedOAuthState();return connection;} catch (error) {if (cleanupOAuthHandlers) {@@ -380,6 +439,13 @@ export class MCPConnectionFactory {return isOAuthServer(this.serverConfig);}+ protected releaseRequestScopedOAuthState(): void {+ this.signal = undefined;+ this.oauthStart = undefined;+ this.oauthEnd = undefined;+ this.returnOnOAuth = false;+ }+private getServerUrl(): string | undefined {return 'url' in this.serverConfig ? this.serverConfig.url : undefined;}@@ -435,6 +501,8 @@ export class MCPConnectionFactory {error: new Error('OAuth tokens missing before connection'),serverUrl,userId: this.userId,+ /** `getOAuthTokens` just exhausted the stored-token/refresh path; go straight to interactive OAuth */+ skipSilentRefresh: true,});if (!emitted) {@@ -444,25 +512,58 @@ export class MCPConnectionFactory {});}+ private async runWithCapturedTenant<T>(fn: () => Promise<T>): Promise<T> {+ const context = this.tenantContext ?? (this.tenantId ? { tenantId: this.tenantId } : undefined);+ if (!context || !tenantStorage?.run) {+ return fn();+ }+ return tenantStorage.run(context, fn);+ }++ private getConnectionOAuthTimeoutMs(): number {+ const factoryConnectTimeout = this.connectionTimeout ?? this.serverConfig.initTimeout ?? 30000;+ const connectionOAuthTimeout = this.serverConfig.initTimeout ?? 60000 * 2;+ return Math.min(factoryConnectTimeout, connectionOAuthTimeout);+ }++ private getSilentRefreshTimeoutMs(): number {+ const oauthTimeout = this.getConnectionOAuthTimeoutMs();+ const silentRefreshBudgetMs = Math.floor(oauthTimeout * 0.4);+ return Math.max(+ 1,+ Math.min(MCPConnectionFactory.SILENT_REFRESH_TIMEOUT_MS, silentRefreshBudgetMs),+ );+ }++ private getBaseFlowId(): string {+ return MCPOAuthHandler.generateFlowId(this.userId!, this.serverName, this.tenantId);+ }++ private getTokenFlowId(): string {+ return MCPOAuthHandler.generateTokenFlowId(this.userId!, this.serverName, this.tenantId);+ }+/** Retrieves existing OAuth tokens from storage or returns null */protected async getOAuthTokens(): Promise<MCPOAuthTokens | null> {if (!this.tokenMethods?.findToken) return null;try {- const flowId = MCPOAuthHandler.generateFlowId(this.userId!, this.serverName);+ const flowId = this.getTokenFlowId();const tokens = await this.flowManager!.createFlowWithHandler(flowId,'mcp_get_tokens',async () => {- return await MCPTokenStorage.getTokens({- userId: this.userId!,- serverName: this.serverName,- findToken: this.tokenMethods!.findToken!,- createToken: this.tokenMethods!.createToken,- updateToken: this.tokenMethods!.updateToken,- deleteTokens: this.tokenMethods!.deleteTokens,- refreshTokens: this.createRefreshTokensFunction(),- });+ return await this.runWithCapturedTenant(async () =>+ MCPTokenStorage.getTokens({+ userId: this.userId!,+ serverName: this.serverName,+ findToken: this.tokenMethods!.findToken!,+ createToken: this.tokenMethods!.createToken,+ updateToken: this.tokenMethods!.updateToken,+ deleteTokens: this.tokenMethods!.deleteTokens,+ refreshTokens: this.createRefreshTokensFunction(),+ }),+ );},this.signal,);@@ -489,9 +590,11 @@ export class MCPConnectionFactory {clientInfo?: OAuthClientInformation;storedTokenEndpoint?: string;storedAuthMethods?: string[];+ resource?: string;},+ signal?: AbortSignal,) => Promise<MCPOAuthTokens> {- return async (refreshToken, metadata) => {+ return async (refreshToken, metadata, signal) => {return await MCPOAuthHandler.refreshOAuthTokens(refreshToken,{@@ -500,15 +603,269 @@ export class MCPConnectionFactory {clientInfo: metadata.clientInfo,storedTokenEndpoint: metadata.storedTokenEndpoint,storedAuthMethods: metadata.storedAuthMethods,+ resource: metadata.resource,},this.serverConfig.oauth_headers ?? {},this.serverConfig.oauth,this.allowedDomains,this.allowedAddresses,+ signal,);};}+ /**+ * Attempts to silently refresh OAuth tokens using the stored refresh token,+ * bypassing the local `expires_at` check. Use this when the server has+ * signaled token invalidity (a 401 emitted as `oauthRequired`) to avoid+ * forcing the user through an interactive OAuth flow when the refresh token+ * is still valid.+ *+ * Coalesces via `inflightSilentRefreshes` rather than `FlowStateManager` —+ * the latter caches the completed result for the new token's TTL, which+ * would hand back stale tokens on a subsequent 401 (e.g. when the freshly+ * minted token is revoked before its local expiry). Caching only the+ * in-flight promise means every fresh 401 after settlement triggers a+ * fresh redemption.+ */+ protected async attemptSilentTokenRefresh(): Promise<MCPOAuthTokens | null> {+ if (!this.tokenMethods?.findToken || !this.tokenMethods?.createToken) {+ 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}`;+ const inflight = MCPConnectionFactory.inflightSilentRefreshes.get(lockKey);+ if (inflight) {+ logger.debug(`${this.logPrefix} Joining in-flight silent refresh attempt`);+ return inflight;+ }++ const timeoutMs = this.getSilentRefreshTimeoutMs();+ 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 promise = new Promise<MCPOAuthTokens | null>((resolve) => {+ timeoutId = setTimeout(() => {+ abortController.abort();+ abortGraceTimeoutId = setTimeout(+ releaseLock,+ MCPConnectionFactory.SILENT_REFRESH_ABORT_GRACE_MS,+ );+ logger.info(+ `${this.logPrefix} Silent token refresh timed out after ${timeoutMs}ms, falling back to interactive OAuth`,+ );+ resolve(null);+ }, timeoutMs);++ refreshPromise.then(resolve, (error: unknown) => {+ logger.info(+ `${this.logPrefix} Silent token refresh failed, falling back to interactive OAuth`,+ error,+ );+ resolve(null);+ });+ }).finally(() => {+ if (timeoutId) {+ clearTimeout(timeoutId);+ }+ });+ function releaseLock() {+ if (abortGraceTimeoutId) {+ clearTimeout(abortGraceTimeoutId);+ abortGraceTimeoutId = null;+ }+ if (MCPConnectionFactory.inflightSilentRefreshes.get(lockKey) === promise) {+ MCPConnectionFactory.inflightSilentRefreshes.delete(lockKey);+ }+ }+ MCPConnectionFactory.inflightSilentRefreshes.set(lockKey, promise);+ void refreshPromise.then(releaseLock, releaseLock);+ return await promise;+ }++ /**+ * Executes a single force-refresh attempt against the OAuth provider and+ * persists the new tokens. Called by `attemptSilentTokenRefresh` under the+ * `inflightSilentRefreshes` coalescing lock.+ */+ private async runSilentRefresh(signal: AbortSignal): Promise<MCPOAuthTokens | null> {+ try {+ const tokens = await this.runWithCapturedTenant(async () =>+ MCPTokenStorage.forceRefreshTokens({+ userId: this.userId!,+ serverName: this.serverName,+ findToken: this.tokenMethods!.findToken!,+ createToken: this.tokenMethods!.createToken,+ updateToken: this.tokenMethods!.updateToken,+ deleteTokens: this.tokenMethods!.deleteTokens,+ refreshTokens: this.createRefreshTokensFunction(),+ signal,+ }),+ );++ if (tokens) {+ // Drop any previously cached `mcp_get_tokens` result so the next call+ // to `getOAuthTokens` reads the freshly persisted tokens from the+ // token store rather than the now-stale flow-cached value.+ await this.invalidateGetTokensFlow(tokens);+ }++ if (tokens) {+ logger.info(`${this.logPrefix} Silent token refresh succeeded`);+ } else {+ logger.info(`${this.logPrefix} Silent token refresh returned no tokens`);+ }+ return tokens;+ } catch (error) {+ if (error instanceof ReauthenticationRequiredError) {+ logger.info(`${this.logPrefix} ${error.message}, falling back to interactive OAuth`);+ } else {+ logger.info(+ `${this.logPrefix} Silent token refresh failed, falling back to interactive OAuth`,+ error,+ );+ }+ return null;+ }+ }++ /**+ * Clears stale token-fetch cache after fresh credentials are known. COMPLETED+ * entries are deleted; PENDING entries are completed with fresh tokens so+ * concurrent waiters do not fail or later publish server-rejected tokens.+ */+ protected async invalidateGetTokensFlow(freshTokens?: MCPOAuthTokens): Promise<void> {+ if (!this.flowManager || !this.userId) {+ return;+ }+ const flowId = this.getTokenFlowId();+ try {+ const state = await this.flowManager.getFlowState(flowId, 'mcp_get_tokens');+ if (!state) {+ return;+ }+ if (state.status === 'PENDING' && freshTokens) {+ await this.flowManager.completeFlow(flowId, 'mcp_get_tokens', freshTokens);+ return;+ }+ if (state.status !== 'COMPLETED') {+ return;+ }+ await this.flowManager.deleteFlow(flowId, 'mcp_get_tokens');+ } catch (err) {+ logger.debug(`${this.logPrefix} Failed to invalidate mcp_get_tokens cache`, err);+ }+ }++ /**+ * Drops any cached COMPLETED `mcp_oauth` flow state so that+ * `handleOAuthRequired`'s recent-completion fast path can't re-serve the+ * tokens that the resource server just rejected.+ */+ protected async invalidateCompletedOAuthFlow(): Promise<void> {+ if (!this.flowManager || !this.userId) {+ return;+ }+ const flowId = this.getBaseFlowId();+ try {+ const existing = await this.flowManager.getFlowState(flowId, 'mcp_oauth');+ if (!existing || existing.status !== 'COMPLETED') {+ return;+ }+ const meta = existing.metadata as MCPOAuthFlowMetadata | undefined;+ if (!this.isCurrentTenantOAuthFlow(meta)) {+ logger.debug(+ `${this.logPrefix} Skipping completed mcp_oauth invalidation for a different tenant`,+ );+ return;+ }+ const oldState = meta?.state;+ await this.flowManager.deleteFlow(flowId, 'mcp_oauth');+ if (oldState) {+ await MCPOAuthHandler.deleteStateMapping(oldState, this.flowManager);+ }+ } catch (err) {+ logger.debug(`${this.logPrefix} Failed to invalidate completed mcp_oauth cache`, err);+ }+ }++ private isCurrentTenantOAuthFlow(meta: MCPOAuthFlowMetadata | undefined): boolean {+ const flowTenantId = meta?.tenantId;+ if (!this.tenantId) {+ return !flowTenantId;+ }+ return flowTenantId === this.tenantId;+ }++ private getOAuthRequiredStatusCode(data: OAuthRequiredEvent): number | undefined {+ if (typeof data.status === 'number') {+ return data.status;+ }+ if (typeof data.statusCode === 'number') {+ return data.statusCode;+ }++ const error = data.error;+ if (!error || typeof error !== 'object') {+ return undefined;+ }++ const errorLike = error as {+ code?: unknown;+ status?: unknown;+ statusCode?: unknown;+ message?: unknown;+ };+ for (const value of [errorLike.code, errorLike.status, errorLike.statusCode]) {+ if (typeof value === 'number' && Number.isInteger(value)) {+ return value;+ }+ }++ if (typeof errorLike.message === 'string') {+ const statusMatch = errorLike.message.match(/\b(4\d{2}|5\d{2})\b/);+ if (statusMatch) {+ return Number.parseInt(statusMatch[1], 10);+ }+ }++ return undefined;+ }++ private shouldAttemptSilentTokenRefresh(data: OAuthRequiredEvent): boolean {+ const statusCode = this.getOAuthRequiredStatusCode(data);+ if (statusCode === 403) {+ logger.info(+ `${this.logPrefix} OAuth server returned 403; skipping silent refresh and starting interactive OAuth`,+ );+ return false;+ }++ const error = data.error;+ if (error && typeof error === 'object' && 'message' in error) {+ const message = (error as { message?: unknown }).message;+ if (typeof message === 'string') {+ const normalized = message.toLowerCase();+ if (+ normalized.includes('insufficient_scope') ||+ normalized.includes('insufficient scope')+ ) {+ logger.info(+ `${this.logPrefix} OAuth server reported insufficient scope; skipping silent refresh`,+ );+ return false;+ }+ }+ }++ return true;+ }+private getOAuthReplayExpiresAt(createdAt?: number): number | undefined {if (!createdAt) {return undefined;@@ -519,14 +876,48 @@ export class MCPConnectionFactory {}/** Sets up OAuth event handlers for the connection */- protected handleOAuthEvents(connection: MCPConnection): () => void {- const oauthHandler = async (data: { serverUrl?: string }) => {+ protected handleOAuthEvents(+ connection: MCPConnection,+ eventName: 'oauthRequired' | 'oauthReauthenticationRequired' = 'oauthRequired',+ ): () => void {+ const oauthHandler = async (data: OAuthRequiredEvent) => {logger.info(`${this.logPrefix} oauthRequired event received`);+ if (!data.skipSilentRefresh && this.shouldAttemptSilentTokenRefresh(data)) {+ const refreshedTokens = await this.attemptSilentTokenRefresh();+ if (refreshedTokens) {+ connection.setOAuthTokens(refreshedTokens);+ connection.emit('oauthHandled');+ return;+ }+ }++ // Silent refresh failed and we're about to fall through to interactive+ // OAuth. Invalidate any COMPLETED `mcp_oauth` flow first so+ // `handleOAuthRequired`'s recent-completion fast path can't re-serve the+ // tokens the resource server just rejected (see the `PENDING_STALE_MS`+ // window in `handleOAuthRequired`).+ await this.invalidateCompletedOAuthFlow();++ if (this.connectionReady) {+ const emitted = connection.emit('oauthReauthenticationRequired', {+ ...data,+ skipSilentRefresh: true,+ });+ if (emitted) {+ return;+ }+ logger.info(+ `${this.logPrefix} Silent refresh did not recover cached connection; requiring fresh OAuth prompt`,+ );+ connection.emit('oauthFailed', new Error('OAuth reauthentication required'));+ return;+ }+if (this.returnOnOAuth) {try {const config = this.serverConfig;- const flowId = MCPOAuthHandler.generateFlowId(this.userId!, this.serverName);+ const flowId = this.getBaseFlowId();const existingFlow = await this.flowManager!.getFlowState(flowId, 'mcp_oauth');if (existingFlow?.status === 'PENDING') {@@ -568,29 +959,32 @@ export class MCPConnectionFactory {authorizationUrl,flowId: newFlowId,flowMetadata,- } = await MCPOAuthHandler.initiateOAuthFlow(- this.serverName,- data.serverUrl || '',- this.userId!,- config?.oauth_headers ?? {},- config?.oauth,- this.allowedDomains,- // Only reuse stored client when deleteTokens is available for stale-client cleanup- this.tokenMethods?.deleteTokens ? this.tokenMethods.findToken : undefined,- this.allowedAddresses,+ } = await this.runWithCapturedTenant(() =>+ MCPOAuthHandler.initiateOAuthFlow(+ this.serverName,+ data.serverUrl || '',+ this.userId!,+ config?.oauth_headers ?? {},+ config?.oauth,+ this.allowedDomains,+ // Only reuse stored client when deleteTokens is available for stale-client cleanup+ this.tokenMethods?.deleteTokens ? this.tokenMethods.findToken : undefined,+ this.allowedAddresses,+ this.tenantId,+ ),);if (existingFlow) {const oldMeta = existingFlow.metadata as MCPOAuthFlowMetadata | undefined;const oldState = oldMeta?.state;- await this.flowManager!.deleteFlow(newFlowId, 'mcp_oauth');+ await this.flowManager!.deleteFlow(flowId, 'mcp_oauth');if (oldState) {await MCPOAuthHandler.deleteStateMapping(oldState, this.flowManager!);}}// Store flow state BEFORE redirecting so the callback can find it- const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: getTenantId() };+ const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: this.tenantId };await this.flowManager!.initFlow(newFlowId, 'mcp_oauth', metadataWithUrl);await MCPOAuthHandler.storeStateMapping(flowMetadata.state, newFlowId, this.flowManager!);@@ -621,18 +1015,29 @@ export class MCPConnectionFactory {const result = await this.handleOAuthRequired();if (result?.tokens && this.tokenMethods?.createToken) {+ const { tokens } = result;try {- connection.setOAuthTokens(result.tokens);- await MCPTokenStorage.storeTokens({- userId: this.userId!,- serverName: this.serverName,- tokens: result.tokens,- createToken: this.tokenMethods.createToken,- updateToken: this.tokenMethods.updateToken,- findToken: this.tokenMethods.findToken,- clientInfo: result.clientInfo,- metadata: result.metadata,- });+ 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,+ ),+ }),+ );+ // 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`);} catch (error) {logger.error(`${this.logPrefix} Failed to save OAuth tokens to storage`, error);@@ -649,10 +1054,10 @@ export class MCPConnectionFactory {}};- connection.on('oauthRequired', oauthHandler);+ connection.on(eventName, oauthHandler);return () => {- connection.removeListener('oauthRequired', oauthHandler);+ connection.removeListener(eventName, oauthHandler);};}@@ -717,11 +1122,13 @@ export class MCPConnectionFactory {if (!MCPConnectionFactory.isClientRejection(error)) {return;}- await MCPTokenStorage.deleteClientRegistration({- userId: this.userId!,- serverName: this.serverName,- deleteTokens: this.tokenMethods.deleteTokens,- }).catch((err) => {+ await this.runWithCapturedTenant(() =>+ MCPTokenStorage.deleteClientRegistration({+ userId: this.userId!,+ serverName: this.serverName,+ deleteTokens: this.tokenMethods!.deleteTokens,+ }),+ ).catch((err) => {logger.warn(`${this.logPrefix} Failed to clear stale client registration`, err);});}@@ -789,6 +1196,7 @@ export class MCPConnectionFactory {tokens: MCPOAuthTokens | null;clientInfo?: OAuthClientInformation;metadata?: OAuthMetadata;+ resourceMetadata?: OAuthProtectedResourceMetadata;reusedStoredClient?: boolean;error?: unknown;} | null> {@@ -811,7 +1219,7 @@ export class MCPConnectionFactory {logger.debug(`${this.logPrefix} Checking for existing OAuth flow for ${this.serverName}...`);/** Flow ID to check if a flow already exists */- const flowId = MCPOAuthHandler.generateFlowId(this.userId!, this.serverName);+ const flowId = this.getBaseFlowId();/** Check if there's already an ongoing OAuth flow for this flowId */const existingFlow = await this.flowManager.getFlowState(flowId, 'mcp_oauth');@@ -853,6 +1261,7 @@ export class MCPConnectionFactory {tokens,clientInfo: flowMeta?.clientInfo,metadata: flowMeta?.metadata,+ resourceMetadata: flowMeta?.resourceMetadata,reusedStoredClient,};}@@ -879,6 +1288,7 @@ export class MCPConnectionFactory {tokens: cachedTokens,clientInfo: flowMeta?.clientInfo,metadata: flowMeta?.metadata,+ resourceMetadata: flowMeta?.resourceMetadata,};}}@@ -902,21 +1312,24 @@ export class MCPConnectionFactory {authorizationUrl,flowId: newFlowId,flowMetadata,- } = await MCPOAuthHandler.initiateOAuthFlow(- this.serverName,- serverUrl,- this.userId!,- this.serverConfig.oauth_headers ?? {},- this.serverConfig.oauth,- this.allowedDomains,- this.tokenMethods?.deleteTokens ? this.tokenMethods.findToken : undefined,- this.allowedAddresses,+ } = await this.runWithCapturedTenant(() =>+ MCPOAuthHandler.initiateOAuthFlow(+ this.serverName,+ serverUrl,+ this.userId!,+ this.serverConfig.oauth_headers ?? {},+ this.serverConfig.oauth,+ this.allowedDomains,+ this.tokenMethods?.deleteTokens ? this.tokenMethods.findToken : undefined,+ this.allowedAddresses,+ this.tenantId,+ ),);reusedStoredClient = flowMetadata.reusedStoredClient === true;// Store flow state BEFORE redirecting so the callback can find it- const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: getTenantId() };+ const metadataWithUrl = { ...flowMetadata, authorizationUrl, tenantId: this.tenantId };await this.flowManager.initFlow(newFlowId, 'mcp_oauth', metadataWithUrl);await MCPOAuthHandler.storeStateMapping(flowMetadata.state, newFlowId, this.flowManager);@@ -941,6 +1354,7 @@ export class MCPConnectionFactory {tokens,clientInfo: flowMetadata.clientInfo,metadata: flowMetadata.metadata,+ resourceMetadata: flowMetadata.resourceMetadata,reusedStoredClient,};} catch (error) {diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex 417bfa00a6..e8663c598e 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -12,6 +12,7 @@ import type { RequestBody } from '~/types';import type * as t from './types';import {getMissingRuntimeBodyPlaceholderFields,+ isOAuthServer,isUserSourced,requiresEphemeralUserConnection,requiresOAuthMachinery,@@ -377,6 +378,7 @@ Please follow these instructions when using tools from the respective MCP server}): Promise<t.FormattedToolResponse> {/** User-specific connection */let connection: MCPConnection | undefined;+ let cleanupRequestOAuthHandler: (() => void) | undefined;let disconnectAfterCall = false;const userId = user?.id;const logPrefix = userId ? `[MCP][User: ${userId}][${serverName}]` : `[MCP][${serverName}]`;@@ -408,9 +410,8 @@ Please follow these instructions when using tools from the respective MCP server);}- const rawConfig =- providedConfig ??- (await MCPServersRegistry.getInstance().getServerConfig(serverName, userId));+ const registry = MCPServersRegistry.getInstance();+ const rawConfig = providedConfig ?? (await registry.getServerConfig(serverName, userId));if (!rawConfig) {throw new McpError(ErrorCode.InvalidRequest,@@ -479,6 +480,31 @@ Please follow these instructions when using tools from the respective MCP server}resolvedHeaders['Authorization'] = `Bearer ${oboTokens.access_token}`;}+ if (userId && user && oauthStart && flowManager && isOAuthServer(currentOptions)) {+ cleanupRequestOAuthHandler = MCPConnectionFactory.attachRequestOAuthHandler(+ {+ serverName,+ serverConfig: currentOptions,+ dbSourced: isDbSourced,+ skipEnvProcessing: true,+ useSSRFProtection: registry.shouldEnableSSRFProtection(),+ allowedDomains: registry.getAllowedDomains(),+ allowedAddresses: registry.getAllowedAddresses(),+ },+ {+ useOAuth: true,+ user,+ flowManager,+ tokenMethods,+ signal: options?.signal,+ oauthStart,+ oauthEnd,+ customUserVars,+ requestBody,+ },+ connection,+ );+ }connection.setRequestHeaders(resolvedHeaders);@@ -508,6 +534,7 @@ Please follow these instructions when using tools from the respective MCP server// Rethrowing allows the caller (createMCPTool) to handle the final user messagethrow error;} finally {+ cleanupRequestOAuthHandler?.();// Ephemeral connections are never stored in userConnections, so disconnecting// is the only cleanup needed; removing the map entry here could orphan a// still-connected cached connection from before a config change.diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.tsindex 2c801ef11b..6c02852586 100644--- a/packages/api/src/mcp/UserConnectionManager.ts+++ b/packages/api/src/mcp/UserConnectionManager.ts@@ -1,4 +1,4 @@-import { logger } from '@librechat/data-schemas';+import { logger, getTenantId } from '@librechat/data-schemas';import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';import type { MCPOAuthFlowMetadata } from '~/mcp/oauth';import type { FlowState } from '~/flow/types';@@ -247,7 +247,7 @@ export abstract class UserConnectionManager {return undefined;}- const flowId = MCPOAuthHandler.generateFlowId(userId, serverName);+ const flowId = MCPOAuthHandler.generateFlowId(userId, serverName, getTenantId());const existingFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');return this.getPendingOAuthStart(existingFlow);}diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.tsnew file mode 100644index 0000000000..618bcbf02e--- /dev/null+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts@@ -0,0 +1,270 @@+import { Keyv } from 'keyv';+import type { IUser } from '@librechat/data-schemas';+import type {+ OAuthClientInformation,+ OAuthStoredClientMetadata,+ MCPOAuthTokens,+} from '~/mcp/oauth';+import {+ MockKeyv,+ InMemoryTokenStore,+ createOAuthMCPServer,+ type OAuthTestServer,+} from './helpers/oauthTestServer';+import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';+import { FlowStateManager } from '~/flow/manager';+import { MCPConnection } from '~/mcp/connection';+import { MCPTokenStorage } from '~/mcp/oauth';++jest.mock('@librechat/data-schemas', () => ({+ logger: {+ info: jest.fn(),+ warn: jest.fn(),+ error: jest.fn(),+ debug: jest.fn(),+ },+ getTenantId: jest.fn(),+ tenantStorage: {+ getStore: jest.fn(),+ run: jest.fn((_context, fn: () => Promise<unknown>) => fn()),+ },+ encryptV2: jest.fn(async (val: string) => `enc:${val}`),+ decryptV2: jest.fn(async (val: string) => val.replace(/^enc:/, '')),+}));++jest.mock('~/auth', () => ({+ createSSRFSafeUndiciConnect: jest.fn(() => undefined),+ isOAuthUrlAllowed: jest.fn(() => false),+ isSSRFTarget: jest.fn(() => false),+ resolveHostnameSSRF: jest.fn(async () => false),+}));++jest.mock('~/mcp/mcpConfig', () => ({+ mcpConfig: { CONNECTION_CHECK_TTL: 0, USER_CONNECTION_IDLE_TIMEOUT: 30 * 60 * 1000 },+}));++const SERVER_NAME = 'sdk-oauth-server';+const USER_ID = 'sdk-user';+const CLIENT_ID = 'librechat-sdk-test-client';++async function safeDisconnect(conn: MCPConnection | null): Promise<void> {+ if (!conn) {+ return;+ }+ (conn as unknown as { shouldStopReconnecting: boolean }).shouldStopReconnecting = true;+ conn.removeAllListeners();+ await conn.disconnect().catch(() => undefined);+}++function createFlowManager(): FlowStateManager<MCPOAuthTokens | null> {+ return new FlowStateManager(new MockKeyv<MCPOAuthTokens | null>() as unknown as Keyv, {+ ttl: 30000,+ ci: true,+ });+}++async function issueTokens(server: OAuthTestServer, scope = 'read'): Promise<MCPOAuthTokens> {+ const authUrl = new URL('authorize', server.url);+ authUrl.searchParams.set('redirect_uri', 'http://localhost');+ authUrl.searchParams.set('state', 'sdk-test');+ authUrl.searchParams.set('client_id', CLIENT_ID);+ authUrl.searchParams.set('scope', scope);+ authUrl.searchParams.set('resource', server.resourceUrl);++ const authRes = await fetch(authUrl, { redirect: 'manual' });+ const location = authRes.headers.get('location');+ if (!location) {+ throw new Error(`Authorization failed with ${authRes.status}`);+ }+ const code = new URL(location).searchParams.get('code');+ if (!code) {+ throw new Error('Authorization response did not include a code');+ }++ const body = new URLSearchParams({+ grant_type: 'authorization_code',+ code,+ client_id: CLIENT_ID,+ resource: server.resourceUrl,+ });+ const tokenRes = await fetch(new URL('token', server.url), {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body,+ });+ if (!tokenRes.ok) {+ throw new Error(`Token exchange failed: ${tokenRes.status} ${await tokenRes.text()}`);+ }+ const tokens = (await tokenRes.json()) as {+ access_token: string;+ token_type: string;+ expires_in: number;+ refresh_token?: string;+ scope?: string;+ };+ return {+ ...tokens,+ obtained_at: Date.now(),+ expires_at: Date.now() + tokens.expires_in * 1000,+ };+}++async function storeTokens(+ tokenStore: InMemoryTokenStore,+ server: OAuthTestServer,+ tokens: MCPOAuthTokens,+ scope = 'read',+): Promise<void> {+ const clientInfo: OAuthClientInformation = {+ client_id: CLIENT_ID,+ redirect_uris: ['http://localhost'],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ token_endpoint_auth_method: 'none',+ scope,+ };+ const metadata: OAuthStoredClientMetadata = {+ issuer: server.url.replace(/\/$/, ''),+ authorization_endpoint: new URL('authorize', server.url).href,+ token_endpoint: new URL('token', server.url).href,+ response_types_supported: ['code'],+ grant_types_supported: ['authorization_code', 'refresh_token'],+ token_endpoint_auth_methods_supported: ['none'],+ scopes_supported: scope.split(/\s+/).filter(Boolean),+ resource: server.resourceUrl,+ };++ await MCPTokenStorage.storeTokens({+ userId: USER_ID,+ serverName: SERVER_NAME,+ tokens,+ createToken: tokenStore.createToken,+ updateToken: tokenStore.updateToken,+ findToken: tokenStore.findToken,+ clientInfo,+ metadata,+ });+}++describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', () => {+ let server: OAuthTestServer;+ let connection: MCPConnection | null;+ let tokenStore: InMemoryTokenStore;++ beforeEach(() => {+ MCPConnection.clearCooldown(SERVER_NAME);+ connection = null;+ tokenStore = new InMemoryTokenStore();+ });++ afterEach(async () => {+ await safeDisconnect(connection);+ if (server) {+ await server.close();+ }+ jest.clearAllMocks();+ });++ it('silently refreshes a server-rejected token and reconnects with the MCP resource parameter', async () => {+ server = await createOAuthMCPServer({+ issueRefreshTokens: true,+ requireResourceParameter: true,+ tokenScopes: ['read'],+ scopesSupported: ['read'],+ });+ const initialTokens = await issueTokens(server);+ await storeTokens(tokenStore, server, initialTokens);++ server.issuedTokens.delete(initialTokens.access_token);++ connection = await MCPConnectionFactory.create(+ {+ serverName: SERVER_NAME,+ serverConfig: {+ type: 'streamable-http',+ url: server.url,+ initTimeout: 15000,+ },+ },+ {+ useOAuth: true,+ user: { id: USER_ID } as IUser,+ flowManager: createFlowManager(),+ tokenMethods: {+ findToken: tokenStore.findToken,+ createToken: tokenStore.createToken,+ updateToken: tokenStore.updateToken,+ deleteTokens: tokenStore.deleteTokens,+ },+ },+ );++ expect(await connection.isConnected()).toBe(true);+ const tools = await connection.fetchTools();+ expect(tools.some((tool) => tool.name === 'echo')).toBe(true);++ const refreshRequest = server.tokenRequests.find(+ (request) => request.grantType === 'refresh_token',+ );+ expect(refreshRequest).toEqual(+ expect.objectContaining({+ resource: server.resourceUrl,+ clientId: CLIENT_ID,+ }),+ );++ const storedAccessToken = await tokenStore.findToken({+ userId: USER_ID,+ type: 'mcp_oauth',+ identifier: `mcp:${SERVER_NAME}`,+ });+ expect(storedAccessToken?.token).not.toBe(`enc:${initialTokens.access_token}`);+ });++ it('does not silently refresh an SDK insufficient_scope challenge before starting OAuth', async () => {+ server = await createOAuthMCPServer({+ issueRefreshTokens: true,+ requireResourceParameter: true,+ tokenScopes: ['read'],+ requiredScopes: ['write'],+ scopesSupported: ['write'],+ });+ const initialTokens = await issueTokens(server);+ await storeTokens(tokenStore, server, initialTokens);++ const oauthStart = jest.fn(async (_authorizationUrl: string): Promise<void> => undefined);+ await expect(+ MCPConnectionFactory.create(+ {+ serverName: SERVER_NAME,+ serverConfig: {+ type: 'streamable-http',+ url: server.url,+ initTimeout: 15000,+ },+ },+ {+ useOAuth: true,+ user: { id: USER_ID } as IUser,+ flowManager: createFlowManager(),+ tokenMethods: {+ findToken: tokenStore.findToken,+ createToken: tokenStore.createToken,+ updateToken: tokenStore.updateToken,+ deleteTokens: tokenStore.deleteTokens,+ },+ returnOnOAuth: true,+ oauthStart,+ },+ ),+ ).rejects.toThrow();++ expect(+ server.tokenRequests.filter((request) => request.grantType === 'refresh_token'),+ ).toHaveLength(0);+ expect(oauthStart).toHaveBeenCalledTimes(1);+ const authorizationUrl = new URL(oauthStart.mock.calls[0][0]);+ expect(authorizationUrl.searchParams.get('resource')).toBe(server.resourceUrl);+ expect(authorizationUrl.searchParams.get('scope')).toBe('write');+ });+});diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.tsindex f49bc9acda..fdf9c472ac 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts@@ -1,4 +1,4 @@-import { logger, getTenantId } from '@librechat/data-schemas';+import { logger, getTenantId, tenantStorage } from '@librechat/data-schemas';import type { TokenMethods, IUser } from '@librechat/data-schemas';import type { FlowStateManager } from '~/flow/manager';import type { MCPOAuthTokens } from '~/mcp/oauth';@@ -25,9 +25,17 @@ jest.mock('@librechat/data-schemas', () => ({debug: jest.fn(),},getTenantId: jest.fn(),+ tenantStorage: {+ getStore: jest.fn(),+ run: jest.fn((_context, fn: () => Promise<unknown>) => fn()),+ },}));const mockLogger = logger as jest.Mocked<typeof logger>;+const mockTenantStorage = tenantStorage as unknown as {+ getStore: jest.Mock;+ run: jest.Mock;+};const mockProcessMCPEnv = processMCPEnv as jest.MockedFunction<typeof processMCPEnv>;const mockPreProcessGraphTokens = preProcessGraphTokens as jest.MockedFunction<typeof preProcessGraphTokens@@ -36,6 +44,33 @@ const mockMCPConnection = MCPConnection as jest.MockedClass<typeof MCPConnectionconst mockMCPOAuthHandler = MCPOAuthHandler as jest.Mocked<typeof MCPOAuthHandler>;const mockMCPTokenStorage = MCPTokenStorage as jest.Mocked<typeof MCPTokenStorage>;+class InspectableMCPConnectionFactory extends MCPConnectionFactory {+ public constructor(+ basic: t.BasicConnectionOptions,+ options?: t.OAuthConnectionOptions | t.UserConnectionContext,+ ) {+ super(basic, options);+ }++ public async createConnectionForTest(): Promise<MCPConnection> {+ return await this.createConnection();+ }++ public getRequestScopedOAuthState(): {+ signal?: AbortSignal;+ oauthStart?: (authURL: string) => Promise<void>;+ oauthEnd?: () => Promise<void>;+ returnOnOAuth?: boolean;+ } {+ return {+ signal: this.signal,+ oauthStart: this.oauthStart,+ oauthEnd: this.oauthEnd,+ returnOnOAuth: this.returnOnOAuth,+ };+ }+}+describe('MCPConnectionFactory', () => {let mockUser: IUser | undefined;let mockServerConfig: t.MCPOptions;@@ -44,6 +79,12 @@ describe('MCPConnectionFactory', () => {beforeEach(() => {jest.clearAllMocks();+ // Clear process-local silent-refresh in-flight map so a leftover entry+ // from a prior test (e.g. one that errored before its `finally` ran)+ // cannot cause a later test to join a stale promise.+ (+ MCPConnectionFactory as unknown as { inflightSilentRefreshes: Map<string, unknown> }+ ).inflightSilentRefreshes.clear();mockUser = {id: 'user123',email: '[email protected]',@@ -60,6 +101,7 @@ describe('MCPConnectionFactory', () => {createFlow: jest.fn(),createFlowWithHandler: jest.fn(),getFlowState: jest.fn(),+ completeFlow: jest.fn().mockResolvedValue(true),deleteFlow: jest.fn().mockResolvedValue(true),} as unknown as jest.Mocked<FlowStateManager<MCPOAuthTokens | null>>;@@ -77,6 +119,30 @@ describe('MCPConnectionFactory', () => {mockMCPConnection.mockImplementation(() => mockConnectionInstance);mockPreProcessGraphTokens.mockImplementation(async (options) => options);mockProcessMCPEnv.mockReturnValue(mockServerConfig);+ mockMCPOAuthHandler.generateFlowId.mockImplementation(+ (userId: string, serverName: string, tenantId?: string) => {+ const flowId = `${userId}:${serverName}`;+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ },+ );+ mockMCPOAuthHandler.generateTokenFlowId.mockImplementation(+ (userId: string, serverName: string, tenantId?: string) => {+ const flowId = mockMCPOAuthHandler.generateFlowId(userId, serverName);+ return tenantId ? `tenant:${encodeURIComponent(tenantId)}:${flowId}` : flowId;+ },+ );+ mockMCPOAuthHandler.buildStoredClientMetadata.mockImplementation(+ (metadata, resourceMetadata) =>+ metadata+ ? {+ ...metadata,+ ...(resourceMetadata?.resource && { resource: resourceMetadata.resource }),+ }+ : undefined,+ );+ mockTenantStorage.getStore.mockReturnValue(undefined);+ mockTenantStorage.run.mockImplementation((_context, fn: () => Promise<unknown>) => fn());+ (getTenantId as jest.Mock).mockReturnValue(undefined);});describe('static create method', () => {@@ -170,7 +236,9 @@ describe('MCPConnectionFactory', () => {'oauthFailed',expect.objectContaining({ message: 'Server does not use OAuth' }),);- expect(mockConnectionInstance.removeListener).toHaveBeenCalledWith(+ // The fallback `oauthRequired` listener is intentionally kept attached+ // for the connection's lifetime so mid-session 401s are still handled.+ expect(mockConnectionInstance.removeListener).not.toHaveBeenCalledWith('oauthRequired',expect.any(Function),);@@ -220,6 +288,40 @@ describe('MCPConnectionFactory', () => {useSSRFProtection: false,});});++ it('should tenant-scope mcp_get_tokens flow locks', async () => {+ mockTenantStorage.getStore.mockReturnValueOnce({ tenantId: 'tenant-a' });+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');++ const basicOptions = {+ serverName: 'test-server',+ serverConfig: mockServerConfig,+ };++ const oauthOptions = {+ useOAuth: true as const,+ user: mockUser,+ flowManager: mockFlowManager,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ mockFlowManager.createFlowWithHandler.mockResolvedValue(null);+ mockConnectionInstance.isConnected.mockResolvedValue(true);++ await MCPConnectionFactory.create(basicOptions, oauthOptions);++ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledWith(+ 'tenant:tenant-a:flow123',+ 'mcp_get_tokens',+ expect.any(Function),+ undefined,+ );+ });});describe('OAuth token handling', () => {@@ -346,6 +448,7 @@ describe('MCPConnectionFactory', () => {expect(oauthRequiredHandler!).toBeDefined();+ (getTenantId as jest.Mock).mockReturnValue(undefined);await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalledWith(@@ -357,6 +460,7 @@ describe('MCPConnectionFactory', () => {undefined,oauthOptions.tokenMethods.findToken,undefined,+ 'test-tenant',);// initFlow must be awaited BEFORE the redirect to guarantee state is stored@@ -750,6 +854,7 @@ describe('MCPConnectionFactory', () => {// processMCPEnv must return config with url so handleOAuthRequired proceedsmockProcessMCPEnv.mockReturnValue(sseConfig);+ (getTenantId as jest.Mock).mockReturnValue('test-tenant');mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue(mockFlowData);mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');mockFlowManager.getFlowState.mockResolvedValue(null);@@ -770,13 +875,14 @@ describe('MCPConnectionFactory', () => {// Expected to fail}+ (getTenantId as jest.Mock).mockReturnValue(undefined);await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });// initFlow must be called BEFORE oauthStart and createFlowexpect(mockFlowManager.initFlow).toHaveBeenCalledWith('flow123','mcp_oauth',- expect.objectContaining(mockFlowData.flowMetadata),+ expect.objectContaining({ ...mockFlowData.flowMetadata, tenantId: 'test-tenant' }),);const initCallOrder = mockFlowManager.initFlow.mock.invocationCallOrder[0];const oauthStartCallOrder = (oauthOptions.oauthStart as jest.Mock).mock@@ -881,6 +987,1784 @@ describe('MCPConnectionFactory', () => {undefined,);});++ it('should silently refresh tokens on oauthRequired without invoking interactive flow', 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(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const refreshedTokens: MCPOAuthTokens = {+ access_token: 'refreshed-access',+ refresh_token: 'refresh123',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ // The silent refresh path: createFlowWithHandler executes the handler+ // (which calls forceRefreshTokens) and returns the refreshed tokens.+ mockFlowManager.createFlowWithHandler.mockImplementation(async (_flowId, type, handler) => {+ if (type === 'mcp_get_tokens') {+ return handler();+ }+ return null;+ });+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(refreshedTokens);+ 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 to fail because connection itself is mocked as not connected+ }++ await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });++ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledWith(+ expect.objectContaining({+ userId: 'user123',+ serverName: 'test-server',+ findToken: oauthOptions.tokenMethods.findToken,+ createToken: oauthOptions.tokenMethods.createToken,+ }),+ );+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(refreshedTokens);+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled');+ // Silent refresh succeeded — interactive flow must NOT be initiated.+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();+ });++ it('should fall back to interactive OAuth when silent refresh returns null', 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 mockFlowData = {+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'random-state',+ },+ };++ const interactiveTokens: MCPOAuthTokens = {+ access_token: 'interactive-access',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ // Silent refresh attempt returns null (no refresh token / refresh failed).+ mockFlowManager.createFlowWithHandler.mockImplementation(async (_flowId, type, handler) => {+ if (type === 'mcp_get_tokens') {+ return handler();+ }+ return null;+ });+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue(mockFlowData);+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(interactiveTokens);+ 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 to fail+ }++ await oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });++ // Silent refresh was attempted, but yielded no tokens.+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalled();+ // Fall-through behavior: interactive flow runs.+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(interactiveTokens);+ });++ it('should silently refresh tokens for returnOnOAuth path without redirecting', async () => {+ const basicOptions = {+ serverName: 'test-server',+ serverConfig: {+ ...mockServerConfig,+ url: 'https://api.example.com',+ type: 'sse' as const,+ } as t.SSEOptions,+ };++ const oauthOptions = {+ useOAuth: true as const,+ user: mockUser,+ flowManager: mockFlowManager,+ returnOnOAuth: true,+ oauthStart: jest.fn(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const refreshedTokens: MCPOAuthTokens = {+ access_token: 'refreshed-access',+ refresh_token: 'refresh123',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockFlowManager.createFlowWithHandler.mockImplementation(async (_flowId, type, handler) => {+ if (type === 'mcp_get_tokens') {+ return handler();+ }+ return null;+ });+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(refreshedTokens);+ 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(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(refreshedTokens);+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled');+ // returnOnOAuth interactive path must NOT trigger when silent refresh succeeds.+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();+ expect(oauthOptions.oauthStart).not.toHaveBeenCalled();+ });++ it('should fall back to interactive OAuth when silent refresh throws unexpectedly', 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 mockFlowData = {+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'random-state',+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ // Silent refresh path throws — must be swallowed and interactive runs.+ mockMCPTokenStorage.forceRefreshTokens.mockRejectedValueOnce(new Error('refresh boom'));+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue(mockFlowData);+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue({+ access_token: 'fallback-access',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ } as MCPOAuthTokens);+ 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' });++ // The thrown silent refresh error must be swallowed and the interactive+ // flow used as a fallback so the user is never stuck.+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();+ });++ it('should bypass any flow cache on silent refresh and invalidate mcp_get_tokens cache (regression for stale cached token reuse)', async () => {+ // Reproduces the cache-collision flagged by Codex on PR #13369: when an+ // earlier `getOAuthTokens` call cached its (now server-rejected) tokens+ // under the `mcp_get_tokens` flow, the silent refresh must NOT share or+ // reuse that cache. The fix bypasses `FlowStateManager` entirely for the+ // force-refresh, calls `MCPTokenStorage.forceRefreshTokens` directly,+ // and invalidates the `mcp_get_tokens` cache afterwards so the next+ // `getOAuthTokens` reads the freshly persisted tokens.+ 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(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const staleCachedTokens: MCPOAuthTokens = {+ access_token: 'stale-cached-access',+ refresh_token: 'refresh123',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ const freshlyRefreshedTokens: MCPOAuthTokens = {+ access_token: 'freshly-refreshed-access',+ refresh_token: 'refresh456',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ // Simulate the real FlowStateManager cache behavior for `mcp_get_tokens`:+ // a prior call cached `staleCachedTokens` and the cache is still+ // non-expired, so `getOAuthTokens` returns it without re-running the+ // handler. Silent refresh must NOT route through this cached flow.+ mockFlowManager.createFlowWithHandler.mockImplementation(async (_flowId, type, _handler) => {+ if (type === 'mcp_get_tokens') {+ return staleCachedTokens;+ }+ return null;+ });+ // `invalidateGetTokensFlow` only deletes COMPLETED states (to avoid+ // breaking concurrent PENDING joiners), so reflect that here.+ mockFlowManager.getFlowState.mockResolvedValue({+ status: 'COMPLETED' as const,+ type: 'mcp_get_tokens',+ metadata: {},+ createdAt: Date.now(),+ completedAt: Date.now(),+ result: staleCachedTokens,+ });+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(freshlyRefreshedTokens);+ 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' });++ // The refresh runs against the token storage directly — not through any+ // `createFlowWithHandler` flow that could return a stale cached value.+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalled();+ expect(mockFlowManager.createFlowWithHandler).not.toHaveBeenCalledWith(+ expect.anything(),+ 'mcp_force_refresh_tokens',+ expect.anything(),+ expect.anything(),+ );+ // The connection receives the FRESHLY refreshed tokens, NOT the stale+ // cached ones — that's the whole point of the fix.+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(freshlyRefreshedTokens);+ expect(mockConnectionInstance.setOAuthTokens).not.toHaveBeenCalledWith(staleCachedTokens);+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled');+ // The cached `mcp_get_tokens` flow state is dropped so the next+ // `getOAuthTokens` call reads the freshly persisted tokens from storage.+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('flow123', 'mcp_get_tokens');+ });++ it('should coalesce concurrent silent refresh attempts into a single redemption', async () => {+ // Reproduces the concurrent-redemption race flagged by Codex on PR #13369:+ // if two 401s for the same user/server race the silent refresh, they+ // must share one in-flight refresh-token redemption — providers that+ // rotate refresh tokens reject the second redemption, otherwise causing+ // an unnecessary interactive OAuth fallback.+ 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(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const refreshedTokens: MCPOAuthTokens = {+ access_token: 'refreshed-access',+ refresh_token: 'refresh456',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ // Hold a single in-flight refresh open until both concurrent callers+ // have joined the lock. `mockImplementationOnce` (rather than the+ // persistent `mockImplementation`) ensures this never-resolving promise+ // does not leak into later tests' default mock behavior.+ let resolveRefresh: ((tokens: MCPOAuthTokens) => void) | undefined;+ mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce(+ () =>+ new Promise<MCPOAuthTokens>((res) => {+ resolveRefresh = res;+ }),+ );+ 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+ }++ // Fire two concurrent oauthRequired events; both must share the same+ // in-flight refresh attempt.+ const first = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ const second = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });++ // Let the in-flight lock register, then resolve the single redemption.+ await Promise.resolve();+ resolveRefresh!(refreshedTokens);+ await Promise.all([first, second]);++ // Exactly one refresh-token redemption was issued.+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);+ // Both callers set the connection's tokens with the same refreshed value.+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(refreshedTokens);+ });++ 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+ // refresh settles so another 401 cannot immediately redeem the same+ // rotating refresh token.+ 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(),+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ const refreshedTokens: MCPOAuthTokens = {+ access_token: 'late-refresh',+ refresh_token: 'refresh456',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };+ let refreshSignal: AbortSignal | undefined;+ let resolveRefresh: ((tokens: MCPOAuthTokens) => void) | undefined;+ mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce((params) => {+ refreshSignal = params.signal;+ return new Promise<MCPOAuthTokens>((resolve) => {+ resolveRefresh = resolve;+ });+ });+ // Provide a no-op interactive fallback so the handler can complete.+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'state-x',+ },+ });+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(null);+ mockConnectionInstance.connect.mockRejectedValue(new Error('OAuth authentication required'));+ 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 — initial connection mocked to fail.+ }++ // Switch to fake timers only for the silent-refresh attempt so we can+ // fast-forward past its timeout without slowing the test suite.+ jest.useFakeTimers();+ try {+ const firstAttempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ await jest.advanceTimersByTimeAsync(2_001);+ await firstAttempt;++ const inflightMap = (+ MCPConnectionFactory as unknown as {+ inflightSilentRefreshes: Map<string, unknown>;+ }+ ).inflightSilentRefreshes;+ expect(inflightMap.size).toBe(1);+ expect(refreshSignal?.aborted).toBe(true);+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();++ const secondAttempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ await secondAttempt;+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);++ resolveRefresh!(refreshedTokens);+ for (let i = 0; i < 10; i += 1) {+ await Promise.resolve();+ }+ expect(inflightMap.size).toBe(0);+ } finally {+ jest.useRealTimers();+ }+ });++ it('should drop timed-out silent-refresh locks after abort grace if refresh stays hung', 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(),+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ let firstRefreshSignal: AbortSignal | undefined;+ let secondRefreshSignal: AbortSignal | undefined;+ mockMCPTokenStorage.forceRefreshTokens+ .mockImplementationOnce((params) => {+ firstRefreshSignal = params.signal;+ return new Promise<MCPOAuthTokens>(() => {});+ })+ .mockImplementationOnce((params) => {+ secondRefreshSignal = params.signal;+ return Promise.resolve(null as unknown as MCPOAuthTokens);+ });+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'state-x',+ },+ });+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(null);+ mockConnectionInstance.connect.mockRejectedValue(new Error('OAuth authentication required'));+ 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+ }++ jest.useFakeTimers();+ try {+ const firstAttempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ await jest.advanceTimersByTimeAsync(2_001);+ await firstAttempt;++ const inflightMap = (+ MCPConnectionFactory as unknown as {+ inflightSilentRefreshes: Map<string, unknown>;+ }+ ).inflightSilentRefreshes;+ expect(inflightMap.size).toBe(1);+ expect(firstRefreshSignal?.aborted).toBe(true);++ await jest.advanceTimersByTimeAsync(1_001);+ expect(inflightMap.size).toBe(0);++ const secondAttempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ await secondAttempt;++ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);+ expect(secondRefreshSignal).toBeDefined();+ } finally {+ jest.useRealTimers();+ }+ });++ it('should reserve interactive OAuth fallback time when initTimeout is omitted', async () => {+ const sseConfig = {+ 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(),+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ let refreshSignal: AbortSignal | undefined;+ mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce((params) => {+ refreshSignal = params.signal;+ return new Promise<MCPOAuthTokens>(() => {});+ });+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'state-x',+ },+ });+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(null);+ mockConnectionInstance.connect.mockRejectedValue(new Error('OAuth authentication required'));+ 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+ }++ jest.useFakeTimers();+ try {+ const attempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ await jest.advanceTimersByTimeAsync(5_001);+ await attempt;++ expect(refreshSignal?.aborted).toBe(true);+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });++ it('should cap silent refresh below half of a small connection timeout', async () => {+ const sseConfig = {+ ...mockServerConfig,+ url: 'https://api.example.com',+ type: 'sse' as const,+ initTimeout: 5000,+ } 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(),+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ let refreshSignal: AbortSignal | undefined;+ mockMCPTokenStorage.forceRefreshTokens.mockImplementationOnce((params) => {+ refreshSignal = params.signal;+ return new Promise<MCPOAuthTokens>(() => {});+ });+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'state-x',+ },+ });+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(null);+ mockConnectionInstance.connect.mockRejectedValue(new Error('OAuth authentication required'));+ 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+ }++ jest.useFakeTimers();+ try {+ const attempt = oauthRequiredHandler!({ serverUrl: 'https://api.example.com' });+ await jest.advanceTimersByTimeAsync(1_999);+ expect(refreshSignal?.aborted).not.toBe(true);+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();++ await jest.advanceTimersByTimeAsync(2);+ await attempt;++ expect(refreshSignal?.aborted).toBe(true);+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });++ it('should skip silent refresh for 403 OAuth reauthorization failures', 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(),+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'state-x',+ },+ });+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockFlowManager.createFlow.mockResolvedValue(null);+ 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+ }++ const forbiddenError = Object.assign(new Error('Non-200 status code (403)'), { code: 403 });+ await oauthRequiredHandler!({+ serverUrl: 'https://api.example.com',+ error: forbiddenError,+ });++ expect(mockMCPTokenStorage.forceRefreshTokens).not.toHaveBeenCalled();+ expect(mockConnectionInstance.setOAuthTokens).not.toHaveBeenCalled();+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();+ });++ it('should not process already resolved configs for request OAuth handlers', () => {+ const sseConfig = {+ ...mockServerConfig,+ url: 'https://api.example.com/${SHOULD_NOT_EXPAND}',+ type: 'sse' as const,+ } as t.SSEOptions;+ mockProcessMCPEnv.mockClear();++ const cleanup = MCPConnectionFactory.attachRequestOAuthHandler(+ {+ serverName: 'test-server',+ serverConfig: sseConfig,+ skipEnvProcessing: true,+ },+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ oauthStart: jest.fn(),+ },+ mockConnectionInstance,+ );++ expect(mockProcessMCPEnv).not.toHaveBeenCalled();+ expect(mockConnectionInstance.on).toHaveBeenCalledWith(+ 'oauthReauthenticationRequired',+ expect.any(Function),+ );++ cleanup();+ });++ it('should not reuse request-scoped OAuth callbacks after connection is cached', async () => {+ const sseConfig = {+ ...mockServerConfig,+ url: 'https://api.example.com',+ type: 'sse' as const,+ } as t.SSEOptions;++ const basicOptions = {+ serverName: 'test-server',+ serverConfig: sseConfig,+ };++ const oauthStart = jest.fn();+ const oauthEnd = jest.fn();+ const requestAbortController = new AbortController();+ const initialTokens: MCPOAuthTokens = {+ access_token: 'initial-access',+ refresh_token: 'initial-refresh',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ const oauthOptions = {+ useOAuth: true as const,+ user: mockUser,+ flowManager: mockFlowManager,+ oauthStart,+ oauthEnd,+ signal: requestAbortController.signal,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockFlowManager.createFlowWithHandler.mockResolvedValue(initialTokens);+ mockConnectionInstance.connect.mockResolvedValue(undefined);+ mockConnectionInstance.isConnected.mockResolvedValue(true);++ 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;+ });++ await MCPConnectionFactory.create(basicOptions, oauthOptions);++ requestAbortController.abort();+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);++ await oauthRequiredHandler!({+ serverUrl: 'https://api.example.com',+ error: new Error('Non-200 status code (401)'),+ });++ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();+ expect(mockFlowManager.initFlow).not.toHaveBeenCalled();+ expect(mockFlowManager.createFlow).not.toHaveBeenCalled();+ expect(oauthStart).not.toHaveBeenCalled();+ expect(oauthEnd).not.toHaveBeenCalled();+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith(+ 'oauthFailed',+ expect.objectContaining({ message: 'OAuth reauthentication required' }),+ );+ });++ it('should clear request-scoped OAuth callbacks after successful connection', async () => {+ const sseConfig = {+ ...mockServerConfig,+ url: 'https://api.example.com',+ type: 'sse' as const,+ } as t.SSEOptions;+ const initialTokens: MCPOAuthTokens = {+ access_token: 'initial-access',+ refresh_token: 'initial-refresh',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };+ const oauthStart = jest.fn();+ const oauthEnd = jest.fn();+ const requestAbortController = new AbortController();+ const factory = new InspectableMCPConnectionFactory(+ {+ serverName: 'test-server',+ serverConfig: sseConfig,+ },+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ oauthStart,+ oauthEnd,+ signal: requestAbortController.signal,+ returnOnOAuth: true,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ },+ );++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockFlowManager.createFlowWithHandler.mockResolvedValue(initialTokens);+ mockConnectionInstance.connect.mockResolvedValue(undefined);+ mockConnectionInstance.isConnected.mockResolvedValue(true);++ await factory.createConnectionForTest();++ expect(mockConnectionInstance.on).toHaveBeenCalledWith('oauthRequired', expect.any(Function));+ expect(factory.getRequestScopedOAuthState()).toEqual({+ signal: undefined,+ oauthStart: undefined,+ oauthEnd: undefined,+ returnOnOAuth: false,+ });+ });++ it('should let a live request handle cached-connection reauthentication with fresh callbacks', async () => {+ const sseConfig = {+ ...mockServerConfig,+ url: 'https://api.example.com',+ type: 'sse' as const,+ } as t.SSEOptions;++ const basicOptions = {+ serverName: 'test-server',+ serverConfig: sseConfig,+ };++ const staleOAuthStart = jest.fn();+ const liveOAuthStart = jest.fn();+ const initialTokens: MCPOAuthTokens = {+ access_token: 'initial-access',+ refresh_token: 'initial-refresh',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };+ const callbackTokens: MCPOAuthTokens = {+ access_token: 'callback-access',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockFlowManager.createFlowWithHandler.mockResolvedValue(initialTokens);+ mockFlowManager.createFlow.mockResolvedValue(callbackTokens);+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'state-live',+ clientInfo: { client_id: 'client-live' },+ },+ });+ mockConnectionInstance.connect.mockResolvedValue(undefined);+ mockConnectionInstance.isConnected.mockResolvedValue(true);+ type Listener = (...args: unknown[]) => void;+ const handlers: Record<string, Listener[]> = {};+ mockConnectionInstance.on.mockImplementation((event, handler) => {+ const key = typeof event === 'symbol' ? event.toString() : event;+ (handlers[key] ??= []).push(handler as Listener);+ return mockConnectionInstance;+ });+ mockConnectionInstance.removeListener.mockImplementation((event, handler) => {+ const key = typeof event === 'symbol' ? event.toString() : event;+ const list = handlers[key];+ const index = list?.indexOf(handler as Listener) ?? -1;+ if (list && index !== -1) {+ list.splice(index, 1);+ }+ return mockConnectionInstance;+ });+ mockConnectionInstance.emit.mockImplementation((event, ...args) => {+ const key = typeof event === 'symbol' ? event.toString() : event;+ const list = handlers[key];+ if (!list?.length) {+ return false;+ }+ for (const fn of [...list]) {+ fn(...args);+ }+ return true;+ });++ await MCPConnectionFactory.create(basicOptions, {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ oauthStart: staleOAuthStart,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ });++ const liveStarted = new Promise<void>((resolve) => {+ liveOAuthStart.mockImplementation(async () => {+ resolve();+ });+ });+ const cleanup = MCPConnectionFactory.attachRequestOAuthHandler(+ basicOptions,+ {+ useOAuth: true,+ user: mockUser,+ flowManager: mockFlowManager,+ oauthStart: liveOAuthStart,+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ },+ mockConnectionInstance,+ );+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);++ mockConnectionInstance.emit('oauthRequired', {+ serverUrl: 'https://api.example.com',+ error: new Error('Non-200 status code (401)'),+ });++ await liveStarted;++ expect(staleOAuthStart).not.toHaveBeenCalled();+ expect(liveOAuthStart).toHaveBeenCalledWith('https://auth.example.com');+ expect(handlers.oauthReauthenticationRequired.length).toBe(1);++ cleanup();++ expect(handlers.oauthReauthenticationRequired.length).toBe(0);+ });++ it('should invalidate completed mcp_oauth cache before falling through to interactive OAuth', async () => {+ // Regression for the Codex finding "Bypass completed OAuth cache after a+ // rejected token": when silent refresh returns null and the handler+ // falls through to interactive OAuth, any recently COMPLETED mcp_oauth+ // flow must be cleared so the fast-reuse path in `handleOAuthRequired`+ // can't hand back the very tokens the resource server just rejected.+ 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 completedFlowState = {+ status: 'COMPLETED' as const,+ type: 'mcp_oauth',+ metadata: { state: 'old-csrf-state' },+ createdAt: Date.now(),+ completedAt: Date.now(),+ result: {+ access_token: 'just-rejected',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ } as MCPOAuthTokens,+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);+ // First lookup (from invalidateCompletedOAuthFlow) sees the stale+ // COMPLETED state with the just-rejected tokens; the second lookup+ // (inside handleOAuthRequired, after deletion) sees nothing and goes+ // straight to a fresh interactive OAuth flow.+ mockFlowManager.getFlowState+ .mockResolvedValueOnce(completedFlowState)+ .mockResolvedValue(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.createFlow.mockResolvedValue({+ access_token: 'freshly-issued',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ } as MCPOAuthTokens);+ 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' });++ // Completed `mcp_oauth` flow was deleted before the interactive path ran.+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('flow123', 'mcp_oauth');+ // And the old CSRF state mapping was cleaned up alongside it.+ expect(mockMCPOAuthHandler.deleteStateMapping).toHaveBeenCalledWith(+ 'old-csrf-state',+ mockFlowManager,+ );+ });++ it('should not invalidate a completed mcp_oauth flow from another tenant', 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 tenantBCompletedFlow = {+ status: 'COMPLETED' as const,+ type: 'mcp_oauth',+ metadata: { state: 'tenant-b-state', tenantId: 'tenant-b' },+ createdAt: Date.now(),+ completedAt: Date.now(),+ result: {+ access_token: 'tenant-b-token',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ } as MCPOAuthTokens,+ };++ (getTenantId as jest.Mock).mockReturnValue('tenant-a');+ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);+ mockFlowManager.getFlowState+ .mockResolvedValueOnce(tenantBCompletedFlow)+ .mockResolvedValue(null);+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: 'flow123',+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'tenant-a-state',+ },+ });+ mockFlowManager.createFlow.mockResolvedValue(null);+ 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(mockFlowManager.getFlowState).toHaveBeenCalledWith('flow123', 'mcp_oauth');+ expect(mockFlowManager.deleteFlow).not.toHaveBeenCalledWith('flow123', 'mcp_oauth');+ expect(mockMCPOAuthHandler.deleteStateMapping).not.toHaveBeenCalledWith(+ 'tenant-b-state',+ mockFlowManager,+ );+ expect(mockFlowManager.initFlow).toHaveBeenCalledWith(+ 'flow123',+ 'mcp_oauth',+ expect.objectContaining({ tenantId: 'tenant-a' }),+ );+ });++ it('should tenant-scope mcp_oauth flow lookup before completed-flow reuse', 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 tenantFlowId = 'tenant:tenant-a:user123:test-server';++ (getTenantId as jest.Mock).mockReturnValue('tenant-a');+ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(null);+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com',+ flowId: tenantFlowId,+ flowMetadata: {+ serverName: 'test-server',+ userId: 'user123',+ serverUrl: 'https://api.example.com',+ state: 'tenant-a-state',+ tenantId: 'tenant-a',+ },+ });+ mockFlowManager.createFlow.mockResolvedValue(null);+ 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(mockFlowManager.getFlowState).toHaveBeenCalledWith(tenantFlowId, 'mcp_oauth');+ expect(mockFlowManager.getFlowState).not.toHaveBeenCalledWith(+ 'user123:test-server',+ 'mcp_oauth',+ );+ expect(mockFlowManager.initFlow).toHaveBeenCalledWith(+ tenantFlowId,+ 'mcp_oauth',+ expect.objectContaining({ tenantId: 'tenant-a' }),+ );+ });++ it('should scope the silent-refresh in-flight lock by tenant', async () => {+ // Regression for the Codex finding "Scope silent refresh lock by+ // tenant": two tenants that share the same `userId` and `serverName`+ // (e.g. when IDs are username-based) must not join each other's+ // in-flight refresh; otherwise tokens minted under tenant A's+ // refresh-token would be applied to a tenant-B connection.+ const tenantMock = getTenantId as jest.MockedFunction<typeof getTenantId>;++ 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(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const tenantATokens: MCPOAuthTokens = {+ access_token: 'tenant-a-access',+ refresh_token: 'tenant-a-refresh',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };+ const tenantBTokens: MCPOAuthTokens = {+ access_token: 'tenant-b-access',+ refresh_token: 'tenant-b-refresh',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ 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;+ });++ // Build a factory whose tenantId was captured as "tenant-a", trigger a+ // refresh, then build a second factory under "tenant-b" with the same+ // userId and serverName. Each refresh must call `forceRefreshTokens`+ // independently and apply its own tokens.+ tenantMock.mockReturnValue('tenant-a');+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(tenantATokens);++ try {+ await MCPConnectionFactory.create(basicOptions, oauthOptions);+ } catch {+ // Expected+ }+ const tenantAHandler = oauthRequiredHandler!;++ // Reset oauthRequiredHandler capture for the second factory.+ tenantMock.mockReturnValue('tenant-b');+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(tenantBTokens);++ try {+ await MCPConnectionFactory.create(basicOptions, oauthOptions);+ } catch {+ // Expected+ }+ const tenantBHandler = oauthRequiredHandler!;++ await Promise.all([+ tenantAHandler({ serverUrl: 'https://api.example.com' }),+ tenantBHandler({ serverUrl: 'https://api.example.com' }),+ ]);++ // Each tenant ran its own refresh and applied its own tokens — no+ // cross-tenant coalescing.+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(tenantATokens);+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(tenantBTokens);+ });++ it('should restore captured tenant context while silently refreshing tokens', async () => {+ const capturedContext = {+ tenantId: 'tenant-a',+ userId: 'user123',+ requestId: 'req-123',+ };+ mockTenantStorage.getStore.mockReturnValueOnce(capturedContext);++ 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(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const refreshedTokens: MCPOAuthTokens = {+ access_token: 'tenant-access',+ refresh_token: 'tenant-refresh',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(refreshedTokens);+ 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(mockTenantStorage.run).toHaveBeenCalledWith(capturedContext, expect.any(Function));+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalled();+ expect(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(refreshedTokens);+ });++ it('should NOT delete a PENDING mcp_get_tokens flow after silent refresh', async () => {+ // Regression for the Codex findings around active token-fetch flows:+ // concurrent `getOAuthTokens` callers may be joined to a PENDING+ // `mcp_get_tokens` flow via `monitorFlow`. Deleting it under them makes+ // waiters fail; leaving it alone lets a stale handler publish rejected+ // tokens later. Completing the flow with the fresh tokens solves both.+ 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(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ };++ const refreshedTokens: MCPOAuthTokens = {+ access_token: 'refreshed-access',+ refresh_token: 'refresh789',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ (getTenantId as jest.Mock).mockReturnValue('tenant-a');+ mockProcessMCPEnv.mockReturnValue(sseConfig);+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValueOnce(refreshedTokens);+ // A concurrent `getOAuthTokens` for this user/server is currently+ // PENDING — joiners are monitoring it via `monitorFlow`.+ mockFlowManager.getFlowState.mockResolvedValue({+ status: 'PENDING' as const,+ type: 'mcp_get_tokens',+ metadata: {},+ createdAt: Date.now(),+ });+ 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.forceRefreshTokens).toHaveBeenCalled();+ expect(mockFlowManager.getFlowState).toHaveBeenCalledWith(+ 'tenant:tenant-a:flow123',+ 'mcp_get_tokens',+ );+ expect(mockFlowManager.completeFlow).toHaveBeenCalledWith(+ 'tenant:tenant-a:flow123',+ 'mcp_get_tokens',+ refreshedTokens,+ );+ expect(mockFlowManager.deleteFlow).not.toHaveBeenCalledWith(+ 'tenant:tenant-a:flow123',+ 'mcp_get_tokens',+ );+ });++ it('should invalidate mcp_get_tokens cache after interactive OAuth stores fresh tokens', async () => {+ // Regression for the Codex finding "Invalidate token cache after+ // interactive fallback": when silent refresh fails but interactive OAuth+ // succeeds, the old `mcp_get_tokens` flow cache could otherwise re-serve+ // stale tokens to the next `getOAuthTokens` call.+ 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 interactiveTokens: MCPOAuthTokens = {+ access_token: 'interactive-access',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ };++ 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',+ },+ });+ // First `getFlowState` (from `invalidateCompletedOAuthFlow`): no+ // completed mcp_oauth flow → no-op. Second (from `handleOAuthRequired`):+ // no existing flow either. Final (from `invalidateGetTokensFlow` after+ // interactive store): a COMPLETED `mcp_get_tokens` cache exists and+ // must be cleared so the next `getOAuthTokens` reads fresh tokens.+ mockFlowManager.getFlowState+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ status: 'COMPLETED' as const,+ type: 'mcp_get_tokens',+ metadata: {},+ createdAt: Date.now(),+ completedAt: Date.now(),+ result: {+ access_token: 'old-stale',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ } as MCPOAuthTokens,+ });+ mockFlowManager.createFlow.mockResolvedValue(interactiveTokens);+ 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(mockConnectionInstance.setOAuthTokens).toHaveBeenCalledWith(interactiveTokens);+ // The stale `mcp_get_tokens` cache is cleared so the next+ // `getOAuthTokens` reads the freshly persisted interactive tokens.+ expect(mockFlowManager.deleteFlow).toHaveBeenCalledWith('flow123', 'mcp_get_tokens');+ });});describe('connection retry logic', () => {diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 202785f13c..04b6ae2ac0 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -563,6 +563,66 @@ describe('MCPManager', () => {);});+ it('should attach request OAuth handler without reprocessing resolved config', async () => {+ const rawServerConfig = {+ type: 'sse',+ url: 'https://api.example.com/{{LIBRECHAT_USER_ID}}',+ headers: {+ Authorization: 'Bearer {{USER_TOKEN}}',+ },+ requiresOAuth: true,+ oauth: {+ authorization_url: 'https://auth.example.com/authorize',+ },+ } as t.ParsedServerConfig;+ const processedServerConfig = {+ ...rawServerConfig,+ url: 'https://api.example.com/user-123',+ headers: {+ Authorization: 'Bearer ${SHOULD_NOT_EXPAND}',+ },+ };+ const cleanupOAuthHandler = jest.fn();++ mockProcessMCPEnv.mockReturnValue(processedServerConfig);+ (MCPConnectionFactory.attachRequestOAuthHandler as jest.Mock).mockReturnValue(+ cleanupOAuthHandler,+ );+ mockAppConnections({+ get: jest.fn().mockResolvedValue(mockConnection),+ });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(rawServerConfig);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const oauthStart = jest.fn();++ await manager.callTool({+ user: mockUser as IUser,+ serverName,+ toolName: 'test_tool',+ provider: 'openai',+ oauthStart,+ flowManager: mockFlowManager as unknown as Parameters<+ typeof manager.callTool+ >[0]['flowManager'],+ });++ /** One pass from user-connection runtime resolution, one from callTool — none from the handler attach */+ expect(mockProcessMCPEnv).toHaveBeenCalledTimes(2);+ expect(MCPConnectionFactory.attachRequestOAuthHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ serverConfig: processedServerConfig,+ skipEnvProcessing: true,+ }),+ expect.objectContaining({+ oauthStart,+ user: mockUser,+ }),+ mockConnection,+ );+ expect(cleanupOAuthHandler).toHaveBeenCalled();+ });+it('should leave graph token placeholders sandboxed for user-sourced configs', async () => {const serverConfig: t.ParsedServerConfig = {type: 'sse',diff --git a/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.tsindex 08b28dd817..dcacd2b18e 100644--- a/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts+++ b/packages/api/src/mcp/__tests__/MCPOAuthConnectionEvents.test.ts@@ -5,12 +5,12 @@* oauthFailed rejection, timeout behavior, and token expiry mid-session.*/-import { MCPConnection } from '~/mcp/connection';-import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';-import { createOAuthMCPServer } from './helpers/oauthTestServer';import type { OAuthTestServer } from './helpers/oauthTestServer';import type { StreamableHTTPOptions } from '~/mcp/types';import type { MCPOAuthTokens } from '~/mcp/oauth';+import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';+import { createOAuthMCPServer } from './helpers/oauthTestServer';+import { MCPConnection } from '~/mcp/connection';jest.mock('@librechat/data-schemas', () => ({logger: {@@ -21,6 +21,7 @@ jest.mock('@librechat/data-schemas', () => ({},encryptV2: jest.fn(async (val: string) => `enc:${val}`),decryptV2: jest.fn(async (val: string) => val.replace(/^enc:/, '')),+ getTenantId: jest.fn(),}));jest.mock('~/auth', () => ({diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.tsindex a1db56f95d..674350f2b0 100644--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenStorage.test.ts@@ -348,6 +348,7 @@ describe('MCPTokenStorage', () => {expect(refreshTokens).toHaveBeenCalledWith('rt',expect.objectContaining({ userId: 'u1', serverName: 'srv1' }),+ undefined,);});@@ -475,6 +476,7 @@ describe('MCPTokenStorage', () => {expect.objectContaining({clientInfo: expect.objectContaining({ client_id: 'cid' }),}),+ undefined,);});@@ -716,6 +718,153 @@ 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({+ userId: 'u1',+ type: 'mcp_oauth',+ identifier: 'mcp:srv1',+ token: 'enc:stale-access-token',+ expiresIn: 3600,+ });+ await store.createToken({+ 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({+ userId: 'u1',+ serverName: 'srv1',+ findToken: store.findToken,+ createToken: store.createToken,+ updateToken: store.updateToken,+ deleteTokens: store.deleteTokens,+ refreshTokens,+ });++ expect(result).not.toBeNull();+ expect(result!.access_token).toBe('new-access-token');+ expect(refreshTokens).toHaveBeenCalledWith(+ 'rt',+ expect.objectContaining({+ userId: 'u1',+ serverName: 'srv1',+ identifier: 'mcp:srv1',+ }),+ undefined,+ );++ // The new access token is persisted, replacing the stale one.+ const saved = await store.findToken({+ userId: 'u1',+ type: 'mcp_oauth',+ identifier: 'mcp:srv1',+ });+ expect(saved!.token).toBe('enc:new-access-token');+ });++ 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({+ userId: 'u1',+ type: 'mcp_oauth',+ identifier: 'mcp:srv1',+ token: 'enc:any',+ expiresIn: 3600,+ });++ const refreshTokens = jest.fn();++ const result = await MCPTokenStorage.forceRefreshTokens({+ userId: 'u1',+ serverName: 'srv1',+ findToken: store.findToken,+ createToken: store.createToken,+ refreshTokens,+ });++ expect(result).toBeNull();+ expect(refreshTokens).not.toHaveBeenCalled();+ });++ it('should return null when refresh callback throws non-client-rejection error', async () => {+ await store.createToken({+ userId: 'u1',+ type: 'mcp_oauth_refresh',+ identifier: 'mcp:srv1:refresh',+ token: 'enc:rt',+ expiresIn: 86400,+ });++ const refreshTokens = jest.fn().mockRejectedValue(new Error('network blew up'));++ const result = await MCPTokenStorage.forceRefreshTokens({+ userId: 'u1',+ serverName: 'srv1',+ findToken: store.findToken,+ createToken: store.createToken,+ refreshTokens,+ });++ expect(result).toBeNull();+ });++ 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({+ userId: 'u1',+ type: 'mcp_oauth_refresh',+ identifier: 'mcp:srv1:refresh',+ token: 'enc:rt',+ expiresIn: 86400,+ });+ await store.createToken({+ userId: 'u1',+ type: 'mcp_oauth_client',+ identifier: 'mcp:srv1:client',+ token: 'enc:{"client_id":"cid"}',+ expiresIn: 86400,+ });++ const refreshTokens = jest.fn().mockRejectedValue(new Error('invalid_client'));++ await expect(+ MCPTokenStorage.forceRefreshTokens({+ userId: 'u1',+ serverName: 'srv1',+ findToken: store.findToken,+ createToken: store.createToken,+ deleteTokens: store.deleteTokens,+ refreshTokens,+ }),+ ).rejects.toThrow(ReauthenticationRequiredError);++ expect(+ await store.findToken({+ userId: 'u1',+ type: 'mcp_oauth_refresh',+ identifier: 'mcp:srv1:refresh',+ }),+ ).toBeNull();+ });+ });+describe('storeTokens + getTokens round-trip', () => {it('should store and retrieve tokens with full encrypt/decrypt cycle', async () => {await MCPTokenStorage.storeTokens({diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.tsindex f285ecfea2..34c32bfbbb 100644--- a/packages/api/src/mcp/__tests__/handler.test.ts+++ b/packages/api/src/mcp/__tests__/handler.test.ts@@ -1,6 +1,6 @@import { TokenExchangeMethodEnum } from 'librechat-data-provider';-import type { MCPOptions } from 'librechat-data-provider';import type { AuthorizationServerMetadata } from '@modelcontextprotocol/sdk/shared/auth.js';+import type { MCPOptions } from 'librechat-data-provider';import { MCPOAuthFlowMetadata, MCPOAuthHandler, MCPOAuthTokens } from '~/mcp/oauth';jest.mock('@librechat/data-schemas', () => ({@@ -83,6 +83,26 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {delete process.env.DOMAIN_SERVER;});+ describe('Flow IDs', () => {+ it('should tenant-scope OAuth flow IDs and parse the owning user', () => {+ const flowId = MCPOAuthHandler.generateFlowId('user-123', 'test-server', 'tenant/a');++ expect(flowId).toBe('tenant:tenant%2Fa:user-123:test-server');+ expect(MCPOAuthHandler.parseFlowId(flowId)).toEqual({+ tenantId: 'tenant/a',+ userId: 'user-123',+ serverName: 'test-server',+ });+ });++ it('should parse legacy unscoped OAuth flow IDs', () => {+ expect(MCPOAuthHandler.parseFlowId('user-123:test-server')).toEqual({+ userId: 'user-123',+ serverName: 'test-server',+ });+ });+ });+describe('Pre-configured OAuth Metadata Fields', () => {const baseConfig: MCPOptions['oauth'] = {authorization_url: 'https://auth.example.com/oauth/authorize',@@ -455,6 +475,79 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {});});+ it('should reuse the stored OAuth resource indicator on refresh', async () => {+ const metadata = {+ serverName: 'test-server',+ userId: 'user-123',+ serverUrl: 'https://api.example.com/mcp',+ resource: 'https://api.example.com/',+ clientInfo: {+ client_id: 'test-client-id',+ grant_types: ['authorization_code', 'refresh_token'],+ },+ };++ 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: ['none'],+ 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 () => ({+ access_token: 'new-access-token',+ expires_in: 3600,+ }),+ } as Response);++ await MCPOAuthHandler.refreshOAuthTokens(mockRefreshToken, metadata, {}, {});++ const body = mockFetch.mock.calls[0][1]?.body as URLSearchParams;+ expect(body.get('resource')).toBe('https://api.example.com/');+ });++ it('should not invent an OAuth resource indicator when the original flow had none', async () => {+ const metadata = {+ serverName: 'test-server',+ userId: 'user-123',+ serverUrl: 'https://api.example.com/mcp',+ clientInfo: {+ client_id: 'test-client-id',+ grant_types: ['authorization_code', 'refresh_token'],+ },+ };++ 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: ['none'],+ 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 () => ({+ access_token: 'new-access-token',+ expires_in: 3600,+ }),+ } as Response);++ await MCPOAuthHandler.refreshOAuthTokens(mockRefreshToken, metadata, {}, {});++ const body = mockFetch.mock.calls[0][1]?.body as URLSearchParams;+ expect(body.has('resource')).toBe(false);+ });+it('should use client_secret_basic when server only supports that method', async () => {const metadata = {serverName: 'test-server',diff --git a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.tsindex 9f75347778..453c3600dd 100644--- a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts+++ b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts@@ -62,10 +62,26 @@ export interface OAuthTestServerOptions {rotateRefreshTokens?: boolean;/** When true, /token validates client_id against the registered client that initiated /authorize */enforceClientId?: boolean;+ /** Scopes attached to newly issued tokens unless the authorization request asks for a scope. */+ tokenScopes?: string[];+ /** Scopes required by the protected MCP resource. Missing scopes produce a 403 insufficient_scope challenge. */+ requiredScopes?: string[];+ /** Scopes advertised by OAuth Protected Resource Metadata and authorization server metadata. */+ scopesSupported?: string[];+ /** When true, /authorize and /token reject requests that omit the MCP resource parameter. */+ requireResourceParameter?: boolean;+}++export interface OAuthTokenRequestRecord {+ grantType: string | null;+ resource: string | null;+ scope: string | null;+ clientId: string | null;}export interface OAuthTestServer {url: string;+ resourceUrl: string;port: number;close: () => Promise<void>;issuedTokens: Set<string>;@@ -73,6 +89,7 @@ export interface OAuthTestServer {tokenIssueTimes: Map<string, number>;issuedRefreshTokens: Map<string, string>;registeredClients: Map<string, { client_id: string; client_secret: string }>;+ tokenRequests: OAuthTokenRequestRecord[];getAuthCode: () => Promise<string>;}@@ -115,20 +132,97 @@ export async function createOAuthMCPServer(refreshTokenTTLMs = 365 * 24 * 60 * 60 * 1000,rotateRefreshTokens = false,enforceClientId = false,+ tokenScopes = [],+ requiredScopes = [],+ scopesSupported = [...new Set([...tokenScopes, ...requiredScopes])],+ requireResourceParameter = false,} = options;const sessions = new Map<string, StreamableHTTPServerTransport>();const issuedTokens = new Set<string>();const tokenIssueTimes = new Map<string, number>();+ const accessTokenScopes = new Map<string, string[]>();const issuedRefreshTokens = new Map<string, string>();const refreshTokenIssueTimes = new Map<string, number>();+ const refreshTokenScopes = new Map<string, string[]>();+ const tokenRequests: OAuthTokenRequestRecord[] = [];const authCodes = new Map<string,- { codeChallenge?: string; codeChallengeMethod?: string; clientId?: string }+ {+ codeChallenge?: string;+ codeChallengeMethod?: string;+ clientId?: string;+ resource?: string;+ scope?: string;+ }>();const registeredClients = new Map<string, { client_id: string; client_secret: string }>();let port = 0;+ const getBaseUrl = () => `http://127.0.0.1:${port}`;+ const getResourceUrl = () => `${getBaseUrl()}/`;+ const getResourceMetadataUrl = () => `${getBaseUrl()}/.well-known/oauth-protected-resource`;++ const parseScopes = (scope: string | null | undefined): string[] => {+ if (!scope) {+ return tokenScopes;+ }+ return scope.split(/\s+/).filter(Boolean);+ };++ const writeJson = (res: http.ServerResponse, status: number, payload: unknown): void => {+ res.writeHead(status, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(payload));+ };++ const writeBearerChallenge = (+ res: http.ServerResponse,+ status: number,+ error: 'invalid_token' | 'insufficient_scope',+ description: string,+ ): void => {+ let authenticate = `Bearer error="${error}", error_description="${description}", resource_metadata="${getResourceMetadataUrl()}"`;+ if (requiredScopes.length > 0) {+ authenticate += `, scope="${requiredScopes.join(' ')}"`;+ }+ res.writeHead(status, {+ 'Content-Type': 'application/json',+ 'WWW-Authenticate': authenticate,+ });+ res.end(JSON.stringify({ error, error_description: description }));+ };++ const requireValidResourceParameter = (+ res: http.ServerResponse,+ params: URLSearchParams,+ ): boolean => {+ if (!requireResourceParameter) {+ return true;+ }+ if (params.get('resource') === getResourceUrl()) {+ return true;+ }+ writeJson(res, 400, {+ error: 'invalid_target',+ error_description: 'resource parameter is required for this MCP resource',+ });+ return false;+ };++ const makeTokenResponse = (+ accessToken: string,+ scopes: string[],+ ): Record<string, string | number> => {+ const tokenResponse: Record<string, string | number> = {+ access_token: accessToken,+ token_type: 'Bearer',+ expires_in: Math.ceil(tokenTTLMs / 1000),+ };+ if (scopes.length > 0) {+ tokenResponse.scope = scopes.join(' ');+ }+ return tokenResponse;+ };const httpServer = http.createServer(async (req, res) => {const url = new URL(req.url ?? '/', `http://${req.headers.host}`);@@ -137,10 +231,11 @@ export async function createOAuthMCPServer(res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({- issuer: `http://127.0.0.1:${port}`,- authorization_endpoint: `http://127.0.0.1:${port}/authorize`,- token_endpoint: `http://127.0.0.1:${port}/token`,- registration_endpoint: `http://127.0.0.1:${port}/register`,+ issuer: getBaseUrl(),+ authorization_endpoint: `${getBaseUrl()}/authorize`,+ token_endpoint: `${getBaseUrl()}/token`,+ registration_endpoint: `${getBaseUrl()}/register`,+ scopes_supported: scopesSupported,response_types_supported: ['code'],grant_types_supported: issueRefreshTokens? ['authorization_code', 'refresh_token']@@ -152,6 +247,19 @@ export async function createOAuthMCPServer(return;}+ if (url.pathname === '/.well-known/oauth-protected-resource' && req.method === 'GET') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(+ JSON.stringify({+ resource: getResourceUrl(),+ authorization_servers: [getBaseUrl()],+ scopes_supported: scopesSupported,+ bearer_methods_supported: ['header'],+ }),+ );+ return;+ }+if (url.pathname === '/register' && req.method === 'POST') {const body = await readRequestBody(req);const data = JSON.parse(body) as { redirect_uris?: string[] };@@ -170,11 +278,20 @@ export async function createOAuthMCPServer(}if (url.pathname === '/authorize') {+ if (requireResourceParameter && url.searchParams.get('resource') !== getResourceUrl()) {+ writeJson(res, 400, {+ error: 'invalid_target',+ error_description: 'resource parameter is required for this MCP resource',+ });+ return;+ }const code = randomUUID();const codeChallenge = url.searchParams.get('code_challenge') ?? undefined;const codeChallengeMethod = url.searchParams.get('code_challenge_method') ?? undefined;const clientId = url.searchParams.get('client_id') ?? undefined;- authCodes.set(code, { codeChallenge, codeChallengeMethod, clientId });+ const resource = url.searchParams.get('resource') ?? undefined;+ const scope = url.searchParams.get('scope') ?? undefined;+ authCodes.set(code, { codeChallenge, codeChallengeMethod, clientId, resource, scope });const redirectUri = url.searchParams.get('redirect_uri') ?? '';const state = url.searchParams.get('state') ?? '';res.writeHead(302, {@@ -194,6 +311,17 @@ export async function createOAuthMCPServer(}const grantType = params.get('grant_type');+ tokenRequests.push({+ grantType,+ resource: params.get('resource'),+ scope: params.get('scope'),+ clientId:+ params.get('client_id') ?? parseBasicAuth(req.headers.authorization)?.clientId ?? null,+ });++ if (!requireValidResourceParameter(res, params)) {+ return;+ }if (grantType === 'authorization_code') {const code = params.get('code');@@ -241,19 +369,18 @@ export async function createOAuthMCPServer(authCodes.delete(code);const accessToken = randomUUID();+ const scopes = parseScopes(codeData.scope);issuedTokens.add(accessToken);tokenIssueTimes.set(accessToken, Date.now());+ accessTokenScopes.set(accessToken, scopes);- const tokenResponse: Record<string, string | number> = {- access_token: accessToken,- token_type: 'Bearer',- expires_in: Math.ceil(tokenTTLMs / 1000),- };+ const tokenResponse = makeTokenResponse(accessToken, scopes);if (issueRefreshTokens) {const refreshToken = randomUUID();issuedRefreshTokens.set(refreshToken, accessToken);refreshTokenIssueTimes.set(refreshToken, Date.now());+ refreshTokenScopes.set(refreshToken, scopes);tokenResponse.refresh_token = refreshToken;}@@ -280,21 +407,23 @@ export async function createOAuthMCPServer(}const newAccessToken = randomUUID();+ const scopes = params.has('scope')+ ? parseScopes(params.get('scope'))+ : (refreshTokenScopes.get(refreshToken) ?? tokenScopes);issuedTokens.add(newAccessToken);tokenIssueTimes.set(newAccessToken, Date.now());+ accessTokenScopes.set(newAccessToken, scopes);- const tokenResponse: Record<string, string | number> = {- access_token: newAccessToken,- token_type: 'Bearer',- expires_in: Math.ceil(tokenTTLMs / 1000),- };+ const tokenResponse = makeTokenResponse(newAccessToken, scopes);if (rotateRefreshTokens) {issuedRefreshTokens.delete(refreshToken);refreshTokenIssueTimes.delete(refreshToken);+ refreshTokenScopes.delete(refreshToken);const newRefreshToken = randomUUID();issuedRefreshTokens.set(newRefreshToken, newAccessToken);refreshTokenIssueTimes.set(newRefreshToken, Date.now());+ refreshTokenScopes.set(newRefreshToken, scopes);tokenResponse.refresh_token = newRefreshToken;}@@ -311,15 +440,13 @@ export async function createOAuthMCPServer(// All other paths require Bearer token authconst authHeader = req.headers.authorization;if (!authHeader || !authHeader.startsWith('Bearer ')) {- res.writeHead(401, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ error: 'invalid_token' }));+ writeBearerChallenge(res, 401, 'invalid_token', 'Missing Authorization header');return;}const token = authHeader.slice(7);if (!issuedTokens.has(token)) {- res.writeHead(401, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ error: 'invalid_token' }));+ writeBearerChallenge(res, 401, 'invalid_token', 'Token is invalid');return;}@@ -327,8 +454,15 @@ export async function createOAuthMCPServer(if (Date.now() - issueTime > tokenTTLMs) {issuedTokens.delete(token);tokenIssueTimes.delete(token);- res.writeHead(401, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ error: 'invalid_token' }));+ accessTokenScopes.delete(token);+ writeBearerChallenge(res, 401, 'invalid_token', 'Token has expired');+ return;+ }++ const scopes = accessTokenScopes.get(token) ?? [];+ const hasRequiredScopes = requiredScopes.every((scope) => scopes.includes(scope));+ if (!hasRequiredScopes) {+ writeBearerChallenge(res, 403, 'insufficient_scope', 'Insufficient scope');return;}@@ -361,17 +495,22 @@ export async function createOAuthMCPServer(return {url: `http://127.0.0.1:${port}/`,+ resourceUrl: `http://127.0.0.1:${port}/`,port,issuedTokens,tokenTTL: tokenTTLMs,tokenIssueTimes,issuedRefreshTokens,registeredClients,+ tokenRequests,getAuthCode: async () => {- const authRes = await fetch(- `http://127.0.0.1:${port}/authorize?redirect_uri=http://localhost&state=test`,- { redirect: 'manual' },- );+ const authUrl = new URL(`${getBaseUrl()}/authorize`);+ authUrl.searchParams.set('redirect_uri', 'http://localhost');+ authUrl.searchParams.set('state', 'test');+ if (requireResourceParameter) {+ authUrl.searchParams.set('resource', getResourceUrl());+ }+ const authRes = await fetch(authUrl, { redirect: 'manual' });const location = authRes.headers.get('location') ?? '';return new URL(location).searchParams.get('code') ?? '';},diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.tsindex db54e9600b..30d497b6d3 100644--- a/packages/api/src/mcp/oauth/handler.ts+++ b/packages/api/src/mcp/oauth/handler.ts@@ -18,6 +18,7 @@ import type { TokenMethods } from '@librechat/data-schemas';import type {OAuthClientInformation,OAuthProtectedResourceMetadata,+ OAuthStoredClientMetadata,MCPOAuthFlowMetadata,MCPOAuthTokens,OAuthMetadata,@@ -50,6 +51,7 @@ export class MCPOAuthHandler {clientInfo?: OAuthClientInformation,allowedDomains?: string[] | null,allowedAddresses?: string[] | null,+ signal?: AbortSignal,): FetchLike {const hardenedFetch = createHardenedOAuthFetch({ allowedDomains, allowedAddresses });@@ -120,11 +122,13 @@ export class MCPOAuthHandler {...init,body: params.toString(),headers: newHeaders,+ signal: init?.signal ?? signal,});}return hardenedFetch(url, {...init,headers: newHeaders,+ signal: init?.signal ?? signal,});};}@@ -357,6 +361,27 @@ export class MCPOAuthHandler {);}+ public static buildStoredClientMetadata(+ metadata?: OAuthMetadata,+ resourceMetadata?: OAuthProtectedResourceMetadata,+ ): OAuthStoredClientMetadata | undefined {+ if (!metadata) {+ return undefined;+ }+ const storedMetadata: OAuthStoredClientMetadata = { ...metadata };+ if (resourceMetadata?.resource) {+ storedMetadata.resource = new URL(resourceMetadata.resource).href;+ }+ return storedMetadata;+ }++ private static appendResourceParameter(body: URLSearchParams, resource?: string): void {+ if (!resource) {+ return;+ }+ body.set('resource', resource);+ }+private static assertNoUnpinnedClientSecret(config?: MCPOptions['oauth']): void {if (config?.client_secret && !config.client_id) {throw new Error('[MCPOAuth] OAuth client_secret requires oauth.client_id.');@@ -478,12 +503,13 @@ export class MCPOAuthHandler {allowedDomains?: string[] | null,findToken?: TokenMethods['findToken'],allowedAddresses?: string[] | null,+ tenantId?: string,): Promise<{ authorizationUrl: string; flowId: string; flowMetadata: MCPOAuthFlowMetadata }> {logger.debug(`[MCPOAuth] initiateOAuthFlow called for ${serverName} with URL: ${sanitizeUrlForLogging(serverUrl)}`,);- const flowId = this.generateFlowId(userId, serverName);+ const flowId = this.generateFlowId(userId, serverName, tenantId);const state = this.generateState();logger.debug(`[MCPOAuth] Generated flowId: ${flowId}, state: ${state}`);@@ -597,6 +623,7 @@ export class MCPOAuthHandler {...(allowedDomains !== undefined && { allowedDomains }),...(allowedAddresses !== undefined && { allowedAddresses }),...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),+ ...(tenantId && { tenantId }),};logger.debug(@@ -778,6 +805,7 @@ export class MCPOAuthHandler {...(allowedAddresses !== undefined && { allowedAddresses }),...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),...(reusedStoredClient && { reusedStoredClient }),+ ...(tenantId && { tenantId }),};logger.debug(@@ -906,8 +934,55 @@ export class MCPOAuthHandler {* Generates a flow ID for the OAuth flow* @returns Consistent ID so concurrent requests share the same flow*/- public static generateFlowId(userId: string, serverName: string): string {- return `${userId}:${serverName}`;+ public static generateFlowId(userId: string, serverName: string, tenantId?: string): string {+ const flowId = `${userId}:${serverName}`;+ if (!tenantId) {+ return flowId;+ }+ return `tenant:${encodeURIComponent(tenantId)}:${flowId}`;+ }++ public static parseFlowId(+ flowId: string,+ ): { userId: string; serverName: string; tenantId?: string } | null {+ const parts = flowId.split(':');+ if (parts[0] === 'tenant') {+ if (parts.length < 4 || !parts[1] || !parts[2]) {+ return null;+ }+ let tenantId: string;+ try {+ tenantId = decodeURIComponent(parts[1]);+ } catch {+ return null;+ }+ const serverName = parts.slice(3).join(':');+ if (!serverName) {+ return null;+ }+ return {+ tenantId,+ userId: parts[2],+ serverName,+ };+ }++ if (parts.length < 2 || !parts[0]) {+ return null;+ }+ const serverName = parts.slice(1).join(':');+ if (!serverName) {+ return null;+ }+ return {+ userId: parts[0],+ serverName,+ };+ }++ /** Same shape as `generateFlowId`; kept distinct so token-fetch flows can diverge from OAuth flows */+ public static generateTokenFlowId(userId: string, serverName: string, tenantId?: string): string {+ return this.generateFlowId(userId, serverName, tenantId);}/**@@ -1104,8 +1179,9 @@ export class MCPOAuthHandler {headers: HeadersInit,body: URLSearchParams,serverName: string,+ signal?: AbortSignal,): Promise<Response> {- const response = await oauthFetch(tokenUrl, { method: 'POST', headers, body });+ const response = await oauthFetch(tokenUrl, { method: 'POST', headers, body, signal });if (response.ok || !body.has('scope')) {return response;}@@ -1122,7 +1198,7 @@ export class MCPOAuthHandler {`[MCPOAuth] ${serverName} rejected the scope parameter on token refresh (HTTP ${response.status}); retrying without scope per RFC 6749 §6`,);body.delete('scope');- return oauthFetch(tokenUrl, { method: 'POST', headers, body });+ return oauthFetch(tokenUrl, { method: 'POST', headers, body, signal });}/**@@ -1158,11 +1234,13 @@ export class MCPOAuthHandler {clientInfo?: OAuthClientInformation;storedTokenEndpoint?: string;storedAuthMethods?: string[];+ resource?: string;},oauthHeaders: Record<string, string>,config?: MCPOptions['oauth'],allowedDomains?: string[] | null,allowedAddresses?: string[] | null,+ signal?: AbortSignal,): Promise<MCPOAuthTokens> {logger.debug(`[MCPOAuth] Refreshing tokens for ${metadata.serverName}`);@@ -1216,6 +1294,7 @@ export class MCPOAuthHandler {undefined,allowedDomains,allowedAddresses,+ signal,);const oauthMetadata = await this.discoverWithOriginFallback(serverUrl, fetchFn);@@ -1250,6 +1329,7 @@ export class MCPOAuthHandler {if (metadata.clientInfo.scope) {body.append('scope', metadata.clientInfo.scope);}+ this.appendResourceParameter(body, metadata.resource);/*** Forward Auth0-style `audience` on refresh by default — Auth0 strips the@@ -1321,6 +1401,7 @@ export class MCPOAuthHandler {headers,body,metadata.serverName,+ signal,);if (!response.ok) {@@ -1353,6 +1434,7 @@ export class MCPOAuthHandler {if (config.scope) {body.append('scope', config.scope);}+ this.appendResourceParameter(body, metadata.resource);const headers: HeadersInit = {Accept: 'application/json',@@ -1407,6 +1489,7 @@ export class MCPOAuthHandler {headers,body,metadata.serverName,+ signal,);if (!response.ok) {@@ -1432,6 +1515,7 @@ export class MCPOAuthHandler {undefined,allowedDomains,allowedAddresses,+ signal,);const oauthMetadata = await this.discoverWithOriginFallback(serverUrl, fetchFn);@@ -1455,6 +1539,7 @@ export class MCPOAuthHandler {grant_type: 'refresh_token',refresh_token: refreshToken,});+ this.appendResourceParameter(body, metadata.resource);const headers: HeadersInit = {Accept: 'application/json',@@ -1467,6 +1552,7 @@ export class MCPOAuthHandler {method: 'POST',headers,body,+ signal,});if (!response.ok) {diff --git a/packages/api/src/mcp/oauth/pending.ts b/packages/api/src/mcp/oauth/pending.tsindex 38ee093e8e..76935ca7ef 100644--- a/packages/api/src/mcp/oauth/pending.ts+++ b/packages/api/src/mcp/oauth/pending.ts@@ -1,4 +1,4 @@-import { logger } from '@librechat/data-schemas';+import { logger, getTenantId } from '@librechat/data-schemas';import type { MCPOAuthFlowMetadata, MCPOAuthTokens } from './types';import type { FlowStateManager } from '~/flow/manager';@@ -60,7 +60,7 @@ export async function getReplayablePendingMCPOAuthStart({}try {- const flowId = MCPOAuthHandler.generateFlowId(userId, serverName);+ const flowId = MCPOAuthHandler.generateFlowId(userId, serverName, getTenantId());const flowState = await flowManager.getFlowState(flowId, MCP_OAUTH_FLOW_TYPE);return getReplayablePendingMCPOAuthStartFromFlow(flowState);} catch (error) {diff --git a/packages/api/src/mcp/oauth/tokens.ts b/packages/api/src/mcp/oauth/tokens.tsindex aae325f252..65c686e7ef 100644--- a/packages/api/src/mcp/oauth/tokens.ts+++ b/packages/api/src/mcp/oauth/tokens.ts@@ -2,7 +2,7 @@ import jwt from 'jsonwebtoken';import { logger, encryptV2, decryptV2 } 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, OAuthMetadata } from './types';+import type { MCPOAuthTokens, ExtendedOAuthTokens, OAuthStoredClientMetadata } from './types';import { isInvalidClientMessage } from '~/mcp/utils';import { isSystemUserId } from '~/mcp/enum';@@ -25,7 +25,7 @@ interface StoreTokensParams {updateToken?: TokenMethods['updateToken'];findToken?: TokenMethods['findToken'];clientInfo?: OAuthClientInformation;- metadata?: OAuthMetadata;+ metadata?: Partial<OAuthStoredClientMetadata>;/** Optional: Pass existing token state to avoid duplicate DB calls */existingTokens?: {accessToken?: IToken | null;@@ -47,12 +47,15 @@ interface GetTokensParams {clientInfo?: OAuthClientInformation;storedTokenEndpoint?: string;storedAuthMethods?: string[];+ resource?: string;},+ signal?: AbortSignal,) => Promise<MCPOAuthTokens>;createToken?: TokenMethods['createToken'];updateToken?: TokenMethods['updateToken'];/** Enables cleanup of stale client registration and refresh token on invalid_client errors during refresh. */deleteTokens?: TokenMethods['deleteTokens'];+ signal?: AbortSignal;}/**@@ -292,6 +295,183 @@ export class MCPTokenStorage {}}+ /**+ * Forces a refresh of OAuth tokens using the stored refresh token, regardless+ * of whether the access token appears locally expired. Use this when the+ * server has signaled token invalidity (e.g. a 401 mid-session) — the 401 is+ * the authoritative signal, not the local `expires_at`.+ *+ * Returns the new tokens, or `null` when refresh is not possible (no refresh+ * token stored, no refresh callback, etc.). Throws `ReauthenticationRequiredError`+ * when the refresh server response indicates the client registration is stale.+ */+ static async forceRefreshTokens({+ userId,+ serverName,+ findToken,+ createToken,+ updateToken,+ deleteTokens,+ refreshTokens,+ existingAccessToken,+ existingRefreshToken,+ signal,+ }: GetTokensParams & {+ existingAccessToken?: IToken | null;+ existingRefreshToken?: IToken | null;+ }): Promise<MCPOAuthTokens | null> {+ const logPrefix = this.getLogPrefix(userId, serverName);+ const identifier = `mcp:${serverName}`;++ const refreshTokenData =+ existingRefreshToken !== undefined+ ? existingRefreshToken+ : await findToken({+ userId,+ type: 'mcp_oauth_refresh',+ identifier: `${identifier}:refresh`,+ });++ if (!refreshTokenData) {+ logger.debug(`${logPrefix} No refresh token in storage`);+ return null;+ }++ if (!refreshTokens) {+ logger.warn(`${logPrefix} Refresh token available but no \`refreshTokens\` provided`);+ return null;+ }++ if (!createToken) {+ logger.warn(`${logPrefix} Refresh token available but no \`createToken\` function provided`);+ return null;+ }++ 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 resource: string | undefined;+ try {+ clientInfoData = await findToken({+ userId,+ type: 'mcp_oauth_client',+ identifier: `${identifier}:client`,+ });+ if (clientInfoData) {+ const decryptedClientInfo = await decryptV2(clientInfoData.token);+ clientInfo = JSON.parse(decryptedClientInfo);+ logger.debug(`${logPrefix} Retrieved client info:`, {+ client_id: clientInfo.client_id,+ has_client_secret: !!clientInfo.client_secret,+ });++ if (clientInfoData.metadata) {+ const raw =+ clientInfoData.metadata instanceof Map+ ? Object.fromEntries(clientInfoData.metadata)+ : (clientInfoData.metadata as Record<string, unknown>);+ storedClientMetadata = raw as Partial<OAuthStoredClientMetadata>;+ if (typeof raw.token_endpoint === 'string') {+ storedTokenEndpoint = raw.token_endpoint;+ }+ if (Array.isArray(raw.token_endpoint_auth_methods_supported)) {+ storedAuthMethods = raw.token_endpoint_auth_methods_supported as string[];+ }+ if (typeof raw.resource === 'string') {+ resource = raw.resource;+ }+ }+ }+ } catch {+ logger.debug(`${logPrefix} No client info found`);+ }++ const metadata = {+ userId,+ serverName,+ identifier,+ clientInfo,+ storedTokenEndpoint,+ storedAuthMethods,+ resource,+ };++ const newTokens = await refreshTokens(decryptedRefreshToken, metadata, signal);++ if (signal?.aborted) {+ throw new Error('Token refresh aborted');+ }++ logger.debug(`${logPrefix} Refresh completed`, {+ has_new_access_token: !!newTokens.access_token,+ has_new_refresh_token: !!newTokens.refresh_token,+ refresh_token_will_be_rotated: !!newTokens.refresh_token,+ expires_at: newTokens.expires_at,+ });++ // Store the refreshed tokens (handles both create and update)+ // Pass existing token state to avoid duplicate DB calls+ await this.storeTokens({+ userId,+ serverName,+ tokens: newTokens,+ createToken,+ updateToken,+ findToken,+ clientInfo,+ existingTokens: {+ accessToken: existingAccessToken,+ refreshToken: refreshTokenData,+ clientInfoToken: clientInfoData,+ },+ metadata: storedClientMetadata,+ });++ logger.info(`${logPrefix} Successfully refreshed and stored OAuth tokens`);+ return newTokens;+ } catch (refreshError) {+ logger.error(`${logPrefix} Failed to refresh tokens`, refreshError);+ // Check if it's an unauthorized_client error (refresh not supported)+ const errorMessage =+ refreshError instanceof Error ? refreshError.message : String(refreshError);+ if (errorMessage.toLowerCase().includes('unauthorized_client')) {+ logger.info(+ `${logPrefix} Server does not support refresh tokens for this client. New authentication required.`,+ );+ } else if (isInvalidClientMessage(errorMessage)) {+ if (deleteTokens) {+ logger.info(+ `${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 }),+ deleteTokens({+ userId,+ type: 'mcp_oauth_refresh',+ identifier: `${identifier}:refresh`,+ }),+ ]);+ for (const r of results) {+ if (r.status === 'rejected') {+ logger.warn(`${logPrefix} Failed to clear stale token data`, r.reason);+ }+ }+ throw new ReauthenticationRequiredError(serverName, 'invalid_client');+ }+ logger.warn(+ `${logPrefix} Client registration rejected during token refresh but deleteTokens not available — stale registration cannot be cleared`,+ );+ }+ return null;+ }+ }+/*** Retrieves OAuth tokens for an MCP server*/@@ -323,7 +503,8 @@ export class MCPTokenStorage {if (isMissing || isExpired) {logger.info(`${logPrefix} Access token ${isMissing ? 'missing' : 'expired'}`);- /** Refresh data if we have a refresh token and refresh function */+ /** Probe for a refresh token first so we can throw `ReauthenticationRequiredError`+ * when none exists, matching the prior contract. */const refreshTokenData = await findToken({userId,type: 'mcp_oauth_refresh',@@ -338,131 +519,17 @@ export class MCPTokenStorage {throw new ReauthenticationRequiredError(serverName, reason);}- if (!refreshTokens) {- logger.warn(- `${logPrefix} Access token ${isMissing ? 'missing' : 'expired'}, refresh token available but no \`refreshTokens\` provided`,- );- return null;- }-- if (!createToken) {- logger.warn(- `${logPrefix} Access token ${isMissing ? 'missing' : 'expired'}, refresh token available but no \`createToken\` function provided`,- );- return null;- }-- try {- logger.info(`${logPrefix} Attempting to refresh token`);- const decryptedRefreshToken = await decryptV2(refreshTokenData.token);-- let clientInfo;- let clientInfoData;- let storedTokenEndpoint: string | undefined;- let storedAuthMethods: string[] | undefined;- try {- clientInfoData = await findToken({- userId,- type: 'mcp_oauth_client',- identifier: `${identifier}:client`,- });- if (clientInfoData) {- const decryptedClientInfo = await decryptV2(clientInfoData.token);- clientInfo = JSON.parse(decryptedClientInfo);- logger.debug(`${logPrefix} Retrieved client info:`, {- client_id: clientInfo.client_id,- has_client_secret: !!clientInfo.client_secret,- });-- if (clientInfoData.metadata) {- const raw =- clientInfoData.metadata instanceof Map- ? Object.fromEntries(clientInfoData.metadata)- : (clientInfoData.metadata as Record<string, unknown>);- if (typeof raw.token_endpoint === 'string') {- storedTokenEndpoint = raw.token_endpoint;- }- if (Array.isArray(raw.token_endpoint_auth_methods_supported)) {- storedAuthMethods = raw.token_endpoint_auth_methods_supported as string[];- }- }- }- } catch {- logger.debug(`${logPrefix} No client info found`);- }-- const metadata = {- userId,- serverName,- identifier,- clientInfo,- storedTokenEndpoint,- storedAuthMethods,- };-- const newTokens = await refreshTokens(decryptedRefreshToken, metadata);-- logger.debug(`${logPrefix} Refresh completed`, {- has_new_access_token: !!newTokens.access_token,- has_new_refresh_token: !!newTokens.refresh_token,- refresh_token_will_be_rotated: !!newTokens.refresh_token,- expires_at: newTokens.expires_at,- });-- // Store the refreshed tokens (handles both create and update)- // Pass existing token state to avoid duplicate DB calls- await this.storeTokens({- userId,- serverName,- tokens: newTokens,- createToken,- updateToken,- findToken,- clientInfo,- existingTokens: {- accessToken: accessTokenData, // We know this is expired/missing- refreshToken: refreshTokenData, // We already have this- clientInfoToken: clientInfoData, // We already looked this up- },- });-- logger.info(`${logPrefix} Successfully refreshed and stored OAuth tokens`);- return newTokens;- } catch (refreshError) {- logger.error(`${logPrefix} Failed to refresh tokens`, refreshError);- // Check if it's an unauthorized_client error (refresh not supported)- const errorMessage =- refreshError instanceof Error ? refreshError.message : String(refreshError);- if (errorMessage.toLowerCase().includes('unauthorized_client')) {- logger.info(- `${logPrefix} Server does not support refresh tokens for this client. New authentication required.`,- );- } else if (isInvalidClientMessage(errorMessage)) {- if (deleteTokens) {- logger.info(- `${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 }),- deleteTokens({- userId,- type: 'mcp_oauth_refresh',- identifier: `${identifier}:refresh`,- }),- ]);- for (const r of results) {- if (r.status === 'rejected') {- logger.warn(`${logPrefix} Failed to clear stale token data`, r.reason);- }- }- throw new ReauthenticationRequiredError(serverName, 'invalid_client');- }- logger.warn(- `${logPrefix} Client registration rejected during token refresh but deleteTokens not available — stale registration cannot be cleared`,- );- }- return null;- }+ return await this.forceRefreshTokens({+ userId,+ serverName,+ findToken,+ createToken,+ updateToken,+ deleteTokens,+ refreshTokens,+ existingAccessToken: accessTokenData,+ existingRefreshToken: refreshTokenData,+ });}// If we reach here, access token should exist and be validdiff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.tsindex 7e9d2d24b2..fea8b6a1c5 100644--- a/packages/api/src/mcp/oauth/types.ts+++ b/packages/api/src/mcp/oauth/types.ts@@ -26,6 +26,11 @@ export interface OAuthMetadata {revocation_endpoint_auth_methods_supported?: string[];}+export interface OAuthStoredClientMetadata extends OAuthMetadata {+ /** Canonical OAuth resource indicator used when the authorization code was exchanged. */+ resource?: string;+}+export interface OAuthProtectedResourceMetadata {/** Resource identifier */resource: string;diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex 25573609b7..253d7c43c2 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -192,6 +192,8 @@ export interface BasicConnectionOptions {allowedAddresses?: string[] | null;/** When true, only resolve customUserVars in processMCPEnv (for DB-stored servers) */dbSourced?: boolean;+ /** When true, serverConfig has already gone through processMCPEnv for this request */+ skipEnvProcessing?: boolean;}/** User context for placeholder resolution in MCP connections (non-OAuth and OAuth alike) */