Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🪫 fix: Recharge Direct OpenID MCP Bearer Sessions (#15704)
Danny Avilaf1bd85498e19
diff --git a/CONTEXT.md b/CONTEXT.mdindex fbc2f1085c..78f0f13a6a 100644--- a/CONTEXT.md+++ b/CONTEXT.md@@ -8,6 +8,7 @@- **Agent turn execution plan**: the immutable, request-local decision compiled once after authentication, agent resolution, and tool initialization. It records the trusted turn origin, conversation lineage, pause capability, binding/action context, and the preferred checkpoint, history, or fresh state-loading strategy without executing the model or owning persistence. Checkpoint failure falls back to durable history within the same Agents lifecycle.- **Effective agent selection**: the resolved endpoint and agent identity after an enforced model spec is applied. Authorization and agent loading must consume this same identity before the Agent run envelope is initialized.- **MCP runtime request body**: trusted chat identifiers supplied only while an MCP server handles an agent request. It enables request-scoped header placeholders without retaining user-specific request data on a shared server definition.+- **MCP direct OpenID bearer**: an operator-trusted remote MCP credential mode that resolves the logged-in user's live OpenID access token into an Authorization header. It may replace one rejected connection after a forced session refresh, but it never replays the rejected tool invocation automatically.- **MCP OAuth prompt projection**: the client-safe, generation-scoped view of authorization prompts that remain actionable in a resumable Agent stream. It is derived from durable OAuth step state, carries no tokens or flow internals, and lets reconnecting clients render current state without interpreting the replay log.- **Caller Capability Projection**: the versioned, SDK-owned classification of currently active tools by direct and programmatic callers. Event-driven execution transports this projection as data; LibreChat intersects it with its trusted registry and never recomputes deferred-tool discovery policy or treats the projection as authorization.- **Subagent thread**: a durable, view-only child conversation owned by one parent conversation and subagent identity. A parent agent may continue it by stable `threadId`; each continuation uses a fresh execution lease restored from the canonical child transcript. It is not an ordinary human-writable chat.diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.jsindex 7dc81c8f90..7c904af969 100644--- a/api/server/routes/mcp.js+++ b/api/server/routes/mcp.js@@ -27,6 +27,9 @@ const {getServerCustomUserVars,hasCustomUserVars,requiresEphemeralUserConnection,+ MCPAuthenticationRejectedError,+ MCPAuthenticationRefreshError,+ OpenIDReauthRequiredError,} = require('@librechat/api');const {createMCPServerController,@@ -899,7 +902,7 @@ router.post(requireJwtAuth,checkMCPUsePermissions,setOAuthSession,- async (req, res) => {+ async (req, res, next) => {try {const { serverName } = req.params;const user = createSafeUser(req.user);@@ -996,6 +999,13 @@ router.post(connectionDeferred,});} catch (error) {+ if (+ error instanceof MCPAuthenticationRejectedError ||+ error instanceof MCPAuthenticationRefreshError ||+ error instanceof OpenIDReauthRequiredError+ ) {+ return next(error);+ }logger.error('[MCP Reinitialize] Unexpected error', error);res.status(500).json({ error: 'Internal server error' });}diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 4635b4a703..cd30328e2c 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -41,7 +41,10 @@ const {createAuthIdentityContext,isOAuthServer,isAbortError,+ isDirectOpenIDBearerRecoveryEnabled,OpenIDReauthRequiredError,+ MCPAuthenticationRefreshError,+ MCPAuthenticationRejectedError,} = require('@librechat/api');const {Time,@@ -700,18 +703,23 @@ function createOAuthCallback({ runStepEmitter, runStepDeltaEmitter }) {}function resolveToolCallUserId({ effectiveUser, capturedUser, invocationUserId, serverConfig }) {- if (serverConfig?.obo == null) {+ const identityBoundCredential =+ serverConfig?.obo != null || isDirectOpenIDBearerRecoveryEnabled(serverConfig ?? {});+ if (!identityBoundCredential) {return effectiveUser?.id || invocationUserId || capturedUser?.id;}const effectiveUserId = effectiveUser?.id;const capturedUserId = capturedUser?.id;+ const credentialLabel = serverConfig?.obo != null ? 'OBO' : 'Direct OpenID bearer';if (!effectiveUserId || !capturedUserId) {- throw new Error('OBO tool calls require matching captured and effective user ids');+ throw new Error(+ `${credentialLabel} tool calls require matching captured and effective user ids`,+ );}if (effectiveUserId !== capturedUserId) {- throw new Error('OBO tool call user mismatch');+ throw new Error(`${credentialLabel} tool call user mismatch`);}return effectiveUserId;@@ -1326,7 +1334,11 @@ function createToolInstance({}/** Carries the actionable re-auth message; the substring heuristic below would misreport it as an OAuth configuration problem */- if (error instanceof OpenIDReauthRequiredError) {+ if (+ error instanceof OpenIDReauthRequiredError ||+ error instanceof MCPAuthenticationRefreshError ||+ error instanceof MCPAuthenticationRejectedError+ ) {throw error;}diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex bd30fce319..b79190eda0 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -2564,6 +2564,47 @@ describe('User parameter passing tests', () => {expect(mockGetMCPManager).not.toHaveBeenCalled();});+ it('should reject direct OpenID bearer execution when effective and captured users differ', async () => {+ const capturedUser = { id: 'captured-user', email: '[email protected]', role: 'USER' };+ const effectiveUser = { id: 'effective-user', email: '[email protected]', role: 'USER' };+ const mockRes = { write: jest.fn(), flush: jest.fn() };++ const mcpTool = await createMCPTool({+ res: mockRes,+ user: capturedUser,+ toolKey: `test-tool${D}direct-server`,+ provider: 'openai',+ userMCPAuthMap: {},+ config: {+ type: 'streamable-http',+ url: 'https://direct.example.com',+ source: 'yaml',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ },+ availableTools: {+ [`test-tool${D}direct-server`]: {+ function: {+ description: 'Cached direct bearer tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ });++ await expect(+ mcpTool.invoke(+ {},+ {+ configurable: { user: effectiveUser },+ metadata: { provider: 'openai', thread_id: 't1', run_id: 'r1' },+ toolCall: {},+ },+ ),+ ).rejects.toThrow('Direct OpenID bearer tool call user mismatch');++ expect(mockGetMCPManager).not.toHaveBeenCalled();+ });+it('should reject OBO tool execution when an effective or captured user id is missing', async () => {const capturedUser = { email: '[email protected]', role: 'USER' };const effectiveUser = { id: 'effective-user', email: '[email protected]', role: 'USER' };diff --git a/api/server/services/OpenIDRefreshFlight.spec.js b/api/server/services/OpenIDRefreshFlight.spec.jsindex b19ac1753f..c570d51486 100644--- a/api/server/services/OpenIDRefreshFlight.spec.js+++ b/api/server/services/OpenIDRefreshFlight.spec.js@@ -564,6 +564,94 @@ describe('OpenIDRefreshFlight', () => {expect(result).toEqual(tokens);});+ it('waits for validated publication instead of returning deferred credentials', async () => {+ db.findOpenIDRefreshFlight+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ status: 'pending' })+ .mockResolvedValueOnce({+ status: 'completed',+ ownerId: 'owner-1',+ encryptedResult: 'encrypted:{"access_token":"unpublished","__deferredPublication":true}',+ })+ .mockResolvedValueOnce({+ status: 'completed',+ ownerId: 'owner-1',+ encryptedResult: 'encrypted:{"access_token":"published"}',+ });+ await expect(+ waitForOpenIDRefreshFlight({+ key: 'flight-key',+ requirePublication: true,+ timeoutMs: 1000,+ intervalMs: 1,+ }),+ ).resolves.toEqual({ access_token: 'published' });+ expect(db.findOpenIDRefreshFlight).toHaveBeenCalledTimes(4);+ });++ it.each(['before-read', 'during-read', 'during-delay'])(+ 'cancels publication polling %s without another database read',+ async (phase) => {+ const controller = new AbortController();+ const reason = new Error('request stopped');+ let finishRead;+ db.findOpenIDRefreshFlight.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishRead = resolve;+ }),+ );+ if (phase === 'before-read') controller.abort(reason);+ const waiting = waitForOpenIDRefreshFlight({+ key: 'publication-key',+ requirePublication: true,+ timeoutMs: 10000,+ intervalMs: 5000,+ signal: controller.signal,+ });+ const outcome = waiting.then(+ (value) => ({ value }),+ (error) => ({ error }),+ );+ if (phase !== 'before-read') {+ if (phase === 'during-read') controller.abort(reason);+ finishRead(null);+ await new Promise((resolve) => setImmediate(resolve));+ if (phase === 'during-delay') controller.abort(reason);+ }+ await expect(outcome).resolves.toEqual({ error: reason });+ expect(db.findOpenIDRefreshFlight).toHaveBeenCalledTimes(phase === 'before-read' ? 0 : 1);+ },+ );++ it('bounds the publication wait without returning an unvalidated result', async () => {+ db.findOpenIDRefreshFlight.mockResolvedValue({+ status: 'completed',+ ownerId: 'owner-1',+ expiresAt: new Date(Date.now() + 60000),+ encryptedResult: 'encrypted:{"access_token":"unpublished","__deferredPublication":true}',+ });+ await expect(+ waitForOpenIDRefreshFlight({+ key: 'flight-key',+ requirePublication: true,+ timeoutMs: 5,+ intervalMs: 1,+ }),+ ).resolves.toBeNull();+ });++ it('keeps cross-worker pre-grant cancellation retryable rather than requiring sign-in', async () => {+ db.findOpenIDRefreshFlight.mockResolvedValueOnce({+ status: 'failed',+ errorMessage: 'OPENID_REFRESH_CANCELLED_BEFORE_GRANT',+ });+ await expect(waitForOpenIDRefreshFlight({ key: 'flight-key' })).rejects.toMatchObject({+ status: 503,+ retryable: true,+ });+ });+it('throws when another worker records a failed flight', async () => {db.findOpenIDRefreshFlight.mockResolvedValueOnce({status: 'failed',diff --git a/api/server/services/OpenIDSessionRefresh.js b/api/server/services/OpenIDSessionRefresh.jsindex 297a174a9b..065ff00582 100644--- a/api/server/services/OpenIDSessionRefresh.js+++ b/api/server/services/OpenIDSessionRefresh.js@@ -40,6 +40,7 @@ module.exports = api.createOpenIDSessionRefreshService({flight.assertOpenIDRefreshSessionGenerationAvailable,completeOpenIDRefreshFlight: flight.completeOpenIDRefreshFlight,createOpenIDRefreshFlightKey: flight.createOpenIDRefreshFlightKey,+ createRefreshTokenBridgeFlightKey: bridge.createRefreshTokenBridgeFlightKey,failOpenIDRefreshFlight: flight.failOpenIDRefreshFlight,waitForOpenIDRefreshFlight: flight.waitForOpenIDRefreshFlight,withOpenIDRefreshFlightLease: flight.withOpenIDRefreshFlightLease,diff --git a/api/server/services/OpenIDSessionRefresh.spec.js b/api/server/services/OpenIDSessionRefresh.spec.jsindex b48061a89d..022bd80fce 100644--- a/api/server/services/OpenIDSessionRefresh.spec.js+++ b/api/server/services/OpenIDSessionRefresh.spec.js@@ -123,6 +123,9 @@ jest.mock('./RefreshTokenBridge', () => ({OPENID_REFRESH_BRIDGE_GRACE_MS: 60 * 1000,storeRefreshTokenBridge: jest.fn(),deleteRefreshTokenBridges: jest.fn(),+ createRefreshTokenBridgeFlightKey: jest.fn(+ ({ userId, oldRefreshToken }) => `publication:${userId}:${oldRefreshToken}`,+ ),}));jest.mock('./OpenIDRefreshFlight', () => ({acquireOpenIDRefreshFlight: jest.fn(),@@ -1864,7 +1867,7 @@ describe('OpenIDSessionRefresh', () => {});await expect(leaderPromise).resolves.toBeDefined();- await expect(joinerPromise).rejects.toThrow('awaiting identity validation');+ await expect(joinerPromise).rejects.toMatchObject({ status: 503, retryable: true });expect(joinerReq.session.save).not.toHaveBeenCalled();expect(storeOpenIdSession).not.toHaveBeenCalled();expect(setRefreshTokenCookie).not.toHaveBeenCalled();@@ -1888,7 +1891,7 @@ describe('OpenIDSessionRefresh', () => {await expect(refreshOpenIDSession(req, buildRes(), makeOpenIdUser(), 'access_token'),- ).rejects.toThrow('awaiting identity validation');+ ).rejects.toMatchObject({ status: 503, retryable: true });expect(storeOpenIdSession).not.toHaveBeenCalled();expect(setRefreshTokenCookie).not.toHaveBeenCalled();@@ -2183,6 +2186,313 @@ describe('OpenIDSessionRefresh', () => {await expect(provider()).rejects.toThrow('invalid_grant');});++ it('forces a refresh when the caller reports that a live access token was rejected', async () => {+ const farFutureExp = Math.floor(Date.now() / 1000) + 600;+ const sessionTokens = {+ accessToken: makeJwt(farFutureExp),+ idToken: makeJwt(farFutureExp),+ refreshToken: 'rt-force',+ };+ openIdClient.refreshTokenGrant.mockResolvedValueOnce({+ access_token: 'forced-access-token',+ expires_in: 3600,+ });+ const provider = createOpenIDSessionTokenProvider({+ req: buildReq(sessionTokens),+ user: makeOpenIdUser(),+ tokenPreference: 'access_token',+ });++ const result = await provider({ forceRefresh: true });++ expect(openIdClient.refreshTokenGrant).toHaveBeenCalledWith(+ expect.anything(),+ 'rt-force',+ expect.anything(),+ );+ expect(result.access_token).toBe('forced-access-token');+ });++ it.each(['complete', 'abort-wait', 'abort-ownership', 'abort-reload'])(+ 'handles %s when a forced MCP refresh joins deferred browser publication',+ async (phase) => {+ const farFutureExp = Math.floor(Date.now() / 1000) + 600;+ const tokens = {+ accessToken: makeJwt(farFutureExp),+ idToken: makeJwt(farFutureExp),+ refreshToken: 'rt-deferred-forced',+ };+ const browserReq = buildReq(tokens);+ const mcpReq = buildReq(tokens);+ const controller = new AbortController();+ const reason = new Error('MCP request stopped');+ let finishGrant;+ let publish;+ openIdClient.refreshTokenGrant.mockReturnValueOnce(+ new Promise((resolve) => {+ finishGrant = resolve;+ }),+ );+ waitForOpenIDRefreshFlight.mockReturnValueOnce(+ new Promise((resolve) => {+ publish = resolve;+ }),+ );+ const browser = refreshOpenIDSession(+ browserReq,+ undefined,+ makeOpenIdUser(),+ 'access_token',+ undefined,+ { forceRefresh: true, deferPublication: true },+ );+ await Promise.resolve();+ const provider = createOpenIDSessionTokenProvider({+ req: mcpReq,+ user: makeOpenIdUser(),+ tokenPreference: 'access_token',+ });+ const mcp = provider({ forceRefresh: true, signal: controller.signal });+ const outcome = mcp.then(+ (value) => ({ value }),+ (error) => ({ error }),+ );+ await Promise.resolve();+ const refreshed = {+ access_token: makeJwt(farFutureExp + 3600),+ id_token: makeJwt(farFutureExp + 3600),+ refresh_token: 'rt-published',+ expires_in: 3600,+ };+ finishGrant(refreshed);+ await browser;+ for (+ let attempt = 0;+ attempt < 20 && !waitForOpenIDRefreshFlight.mock.calls.length;+ attempt+++ ) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ expect(waitForOpenIDRefreshFlight).toHaveBeenCalledWith({+ key: 'publication:local-id-1:rt-deferred-forced',+ requirePublication: true,+ timeoutMs: 10000,+ intervalMs: 250,+ signal: controller.signal,+ });+ expect(mcpReq.session.save).not.toHaveBeenCalled();+ if (phase === 'abort-wait') controller.abort(reason);+ if (phase === 'abort-ownership') {+ assertOpenIDRefreshFlightAvailable.mockImplementationOnce(async () => {+ controller.abort(reason);+ return true;+ });+ }+ mcpReq.session.reload = jest.fn((callback) => {+ if (phase === 'abort-reload') controller.abort(reason);+ callback();+ });+ publish({ tokenset: refreshed, __flightOwnerId: 'owner-1' });+ if (phase !== 'complete') {+ await expect(outcome).resolves.toEqual({ error: reason });+ expect(mcpReq.session.save).not.toHaveBeenCalled();+ expect(mcpReq.session.openidTokens.refreshToken).toBe('rt-deferred-forced');+ expect(storeOpenIdSession).not.toHaveBeenCalled();+ expect(openIdClient.refreshTokenGrant).toHaveBeenCalledTimes(1);+ if (phase !== 'abort-reload') expect(mcpReq.session.reload).not.toHaveBeenCalled();+ return;+ }+ await expect(mcp).resolves.toMatchObject({+ access_token: refreshed.access_token,+ refresh_token: 'rt-published',+ });+ expect(openIdClient.refreshTokenGrant).toHaveBeenCalledTimes(1);+ expect(mcpReq.session.openidTokens.refreshToken).toBe('rt-published');+ expect(assertOpenIDRefreshFlightAvailable).toHaveBeenCalledWith({+ key: 'publication:local-id-1:rt-deferred-forced',+ ownerId: 'owner-1',+ });+ },+ );++ it('fails an acquired lease when cancelled during acquisition and lets an active joiner proceed', async () => {+ const expiry = Math.floor(Date.now() / 1000) + 3600;+ const tokens = {+ accessToken: makeJwt(expiry),+ idToken: makeJwt(expiry),+ refreshToken: 'rt-cancel-acquisition',+ };+ const leaderReq = buildReq(tokens);+ const joinerReq = buildReq(tokens);+ const controller = new AbortController();+ const reason = new Error('request cancelled during acquisition');+ let finishAcquisition;+ acquireOpenIDRefreshFlight.mockReturnValueOnce(+ new Promise((resolve) => {+ finishAcquisition = resolve;+ }),+ );+ const refreshed = {+ access_token: makeJwt(expiry + 3600),+ refresh_token: 'rt-acquisition-successor',+ expires_in: 3600,+ };+ openIdClient.refreshTokenGrant.mockResolvedValueOnce(refreshed);+ const providerFor = (req) =>+ createOpenIDSessionTokenProvider({+ req,+ user: makeOpenIdUser(),+ tokenPreference: 'access_token',+ });+ const leader = providerFor(leaderReq)({ forceRefresh: true, signal: controller.signal });+ const outcome = leader.then(+ (value) => ({ value }),+ (error) => ({ error }),+ );+ await Promise.resolve();+ const joiner = providerFor(joinerReq)({ forceRefresh: true });+ await Promise.resolve();+ controller.abort(reason);+ finishAcquisition({ acquired: true, ownerId: 'cancelled-owner' });+ await expect(outcome).resolves.toEqual({ error: reason });+ await expect(joiner).resolves.toMatchObject({+ access_token: refreshed.access_token,+ refresh_token: refreshed.refresh_token,+ });+ expect(failOpenIDRefreshFlight).toHaveBeenCalledWith({+ key: 'flight:session-A:rt-cancel-acquisition',+ ownerId: 'cancelled-owner',+ error: new Error('OPENID_REFRESH_CANCELLED_BEFORE_GRANT'),+ });+ expect(leaderReq.session.save).not.toHaveBeenCalled();+ expect(joinerReq.session.save).toHaveBeenCalledTimes(1);+ expect(openIdClient.refreshTokenGrant).toHaveBeenCalledTimes(1);+ expect(failOpenIDRefreshFlight.mock.invocationCallOrder[0]).toBeLessThan(+ openIdClient.refreshTokenGrant.mock.invocationCallOrder[0],+ );+ });++ it('settles a rotating grant that was already admitted before cancellation', async () => {+ const expiry = Math.floor(Date.now() / 1000) + 3600;+ const req = buildReq({+ accessToken: makeJwt(expiry),+ idToken: makeJwt(expiry),+ refreshToken: 'rt-admitted',+ });+ const controller = new AbortController();+ let finishGrant;+ openIdClient.refreshTokenGrant.mockReturnValueOnce(+ new Promise((resolve) => {+ finishGrant = resolve;+ }),+ );+ const provider = createOpenIDSessionTokenProvider({+ req,+ user: makeOpenIdUser(),+ tokenPreference: 'access_token',+ });+ const result = provider({ forceRefresh: true, signal: controller.signal });+ await Promise.resolve();+ expect(openIdClient.refreshTokenGrant).toHaveBeenCalledTimes(1);+ controller.abort(new Error('stopped after admission'));+ finishGrant({ access_token: 'new-access', refresh_token: 'rt-settled', expires_in: 3600 });+ await expect(result).resolves.toMatchObject({ access_token: 'new-access' });+ expect(req.session.openidTokens.refreshToken).toBe('rt-settled');+ expect(completeOpenIDRefreshFlight).toHaveBeenCalled();+ expect(failOpenIDRefreshFlight).not.toHaveBeenCalled();+ });++ it('keeps an active local joiner when a cross-worker publication follower is cancelled', async () => {+ const expiry = Math.floor(Date.now() / 1000) + 3600;+ const tokens = {+ accessToken: makeJwt(expiry),+ idToken: makeJwt(expiry),+ refreshToken: 'rt-publication-cancel',+ };+ const leaderReq = buildReq(tokens);+ const joinerReq = buildReq(tokens);+ const controller = new AbortController();+ const reason = new Error('leader stopped');+ const refreshed = { access_token: 'published-access', refresh_token: 'rt-successor' };+ let enteredPublication;+ const publicationStarted = new Promise((resolve) => {+ enteredPublication = resolve;+ });+ acquireOpenIDRefreshFlight.mockResolvedValue({ acquired: false });+ waitForOpenIDRefreshFlight.mockImplementation(async ({ requirePublication, signal }) => {+ if (!requirePublication) {+ return { ...refreshed, __deferredPublication: true, __flightOwnerId: 'browser-owner' };+ }+ if (signal === controller.signal) {+ enteredPublication();+ return new Promise((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });+ });+ }+ return { tokenset: refreshed, __flightOwnerId: 'publication-owner' };+ });+ const providerFor = (req) =>+ createOpenIDSessionTokenProvider({+ req,+ user: makeOpenIdUser(),+ tokenPreference: 'access_token',+ });+ const leader = providerFor(leaderReq)({ forceRefresh: true, signal: controller.signal });+ const outcome = leader.then(+ (value) => ({ value }),+ (error) => ({ error }),+ );+ await publicationStarted;+ const joiner = providerFor(joinerReq)({ forceRefresh: true });+ await Promise.resolve();+ controller.abort(reason);+ await expect(outcome).resolves.toEqual({ error: reason });+ await expect(joiner).resolves.toMatchObject(refreshed);+ expect(leaderReq.session.save).not.toHaveBeenCalled();+ expect(joinerReq.session.openidTokens.refreshToken).toBe('rt-successor');+ expect(joinerReq.session.save).toHaveBeenCalledTimes(1);+ expect(openIdClient.refreshTokenGrant).not.toHaveBeenCalled();+ });++ it('waits for a token-reuse flight before starting a rejection-driven forced refresh', async () => {+ const farFutureExp = Math.floor(Date.now() / 1000) + 600;+ const sessionTokens = {+ accessToken: makeJwt(farFutureExp),+ idToken: makeJwt(farFutureExp),+ refreshToken: 'rt-force-after-reuse',+ };+ let releaseReuse;+ assertOpenIDRefreshSessionGenerationAvailable.mockReturnValueOnce(+ new Promise((resolve) => {+ releaseReuse = resolve;+ }),+ );+ openIdClient.refreshTokenGrant.mockResolvedValueOnce({+ access_token: 'forced-after-reuse',+ expires_in: 3600,+ });+ const provider = createOpenIDSessionTokenProvider({+ req: buildReq(sessionTokens),+ user: makeOpenIdUser(),+ tokenPreference: 'access_token',+ });++ const reuse = provider();+ await Promise.resolve();+ const forced = provider({ forceRefresh: true });+ await Promise.resolve();++ expect(openIdClient.refreshTokenGrant).not.toHaveBeenCalled();+ releaseReuse();+ await expect(reuse).resolves.toEqual(+ expect.objectContaining({ refresh_token: sessionTokens.refreshToken }),+ );+ await expect(forced).resolves.toEqual(+ expect.objectContaining({ access_token: 'forced-after-reuse' }),+ );+ expect(openIdClient.refreshTokenGrant).toHaveBeenCalledTimes(1);+ });});/**diff --git a/api/server/services/Tools/mcp.js b/api/server/services/Tools/mcp.jsindex 25906f6377..69c55fbc72 100644--- a/api/server/services/Tools/mcp.js+++ b/api/server/services/Tools/mcp.js@@ -6,6 +6,9 @@ const {loadMCPServerCatalogs: loadCatalogs,requiresEphemeralUserConnection,getMissingRuntimeBodyPlaceholderFields,+ MCPAuthenticationRejectedError,+ MCPAuthenticationRefreshError,+ OpenIDReauthRequiredError,} = require('@librechat/api');const { CacheKeys, Constants } = require('librechat-data-provider');const { getMCPManager, getMCPServersRegistry, getFlowStateManager } = require('~/config');@@ -34,6 +37,11 @@ const MCP_REINITIALIZE_FAILURE_REASONS = {INITIALIZATION_FAILED: 'initialization_failed',};+const isMCPReauthenticationError = (error) =>+ error instanceof MCPAuthenticationRejectedError ||+ error instanceof MCPAuthenticationRefreshError ||+ error instanceof OpenIDReauthRequiredError;+/** Wires application dependencies into the passive, request-local catalog recovery service.* @param {Object} params* @param {IUser} params.user@@ -272,6 +280,9 @@ async function reinitMCPServer({logger.info('[MCP Reinitialize] Successfully established connection');} catch (err) {+ if (isMCPReauthenticationError(err)) {+ throw err;+ }logger.info('[MCP Reinitialize] Connection attempt failed');logger.info(`[MCP Reinitialize] OAuth state - oauthRequired: ${oauthRequired}, oauthUrl: ${oauthUrl ? 'present' : 'null'}`,@@ -313,7 +324,10 @@ async function reinitMCPServer({`[MCP Reinitialize] Discovered ${tools.length} tools without full authentication`,);}- } catch {+ } catch (error) {+ if (isMCPReauthenticationError(error)) {+ throw error;+ }logger.debug('[MCP Reinitialize] Tool discovery failed');}} else {@@ -429,7 +443,10 @@ async function reinitMCPServer({});return result;- } catch {+ } catch (error) {+ if (isMCPReauthenticationError(error)) {+ throw error;+ }logger.error('[MCP Reinitialize] Error loading MCP tools; servers may still be initializing');} finally {if (connection && ephemeralServer && !requestScopedConnections) {diff --git a/api/server/services/Tools/mcp.spec.js b/api/server/services/Tools/mcp.spec.jsindex 89e1ad5c82..e2e7d5bcf7 100644--- a/api/server/services/Tools/mcp.spec.js+++ b/api/server/services/Tools/mcp.spec.js@@ -440,6 +440,27 @@ describe('reinitMCPServer — customUserVars gating (issue #10969)', () => {});});+describe('reinitMCPServer — direct bearer authentication outcomes', () => {+ it('preserves a typed rejection instead of reducing it to a generic result', async () => {+ const { MCPAuthenticationRejectedError } = require('@librechat/api');+ const rejection = new MCPAuthenticationRejectedError('private-mcp', false);+ mockGetConnection.mockRejectedValue(rejection);++ await expect(+ reinitMCPServer({+ user: { id: 'user-123' },+ serverName: 'private-mcp',+ serverConfig: {+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ },+ }),+ ).rejects.toBe(rejection);+ });+});+describe('reinitMCPServer — runtime BODY placeholder pre-check (issue #14074)', () => {const user = { id: 'user-123' };const serverName = 'Thingy';diff --git a/librechat.example.yaml b/librechat.example.yamlindex 4971db7e48..e44bd8e811 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -474,6 +474,14 @@ actions:# url: http://localhost:3001/sse# # proxy: "${MCP_PROXY_URL}" # optional outbound proxy (http/https/socks/socks5)# timeout: 60000 # 1 minute timeout for this server, this is the default timeout for MCP servers.+# private-openid:+# type: streamable-http+# url: https://mcp.example.com/mcp+# headers:+# # Trusted operator configs automatically use the live session token and replace the+# # connection once after a 401/403. A rejected tools/call is never replayed automatically.+# # Enabled oauth or obo configuration takes precedence over this passthrough mode.+# Authorization: "Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}"# puppeteer:# type: stdio# command: npxdiff --git a/packages/api/src/auth/openid/errors.ts b/packages/api/src/auth/openid/errors.tsindex 5f87479e4b..f4844e9fc2 100644--- a/packages/api/src/auth/openid/errors.ts+++ b/packages/api/src/auth/openid/errors.ts@@ -1,6 +1,7 @@import type { LogArgument } from './types';export const OPENID_REFRESH_OWNERSHIP_LOST = 'OPENID_REFRESH_OWNERSHIP_LOST';+export const OPENID_REFRESH_CANCELLED_BEFORE_GRANT = 'OPENID_REFRESH_CANCELLED_BEFORE_GRANT';/** Express-session uses this exact error when reload cannot find the persisted session. */export function isOpenIDSessionMissingError(error: unknown): boolean {diff --git a/packages/api/src/auth/openid/flight.ts b/packages/api/src/auth/openid/flight.tsindex 903cee96c5..0226096c7e 100644--- a/packages/api/src/auth/openid/flight.ts+++ b/packages/api/src/auth/openid/flight.ts@@ -11,6 +11,7 @@ import type {RefreshKeyInput,} from './types';import {+ OPENID_REFRESH_CANCELLED_BEFORE_GRANT,createOpenIDRefreshOwnershipError,isOpenIDRefreshOwnershipError,toOpenIDLogArgument,@@ -128,6 +129,8 @@ export interface OpenIDRefreshFlightService {key?: string | null;timeoutMs?: number;intervalMs?: number;+ requirePublication?: boolean;+ signal?: AbortSignal;}) => Promise<TokenResult | null>;withOpenIDRefreshFlightLease: <T>(args: {key?: string | null;@@ -592,6 +595,15 @@ export function createOpenIDRefreshFlightService({flight: RefreshFlightRecord | null,): Promise<TokenResult | null> {if (!flight) return null;+ if (+ flight.status === 'failed' &&+ flight.errorMessage === OPENID_REFRESH_CANCELLED_BEFORE_GRANT+ ) {+ throw Object.assign(new Error('OpenID refresh owner stopped before starting the grant'), {+ status: 503,+ retryable: true,+ });+ }if (flight.status === 'revoked')throw new Error(flight.errorMessage || 'OpenID refresh was revoked by logout');if (flight.status === 'failed')@@ -618,24 +630,38 @@ export function createOpenIDRefreshFlightService({key,timeoutMs,intervalMs = DEFAULT_WAIT_INTERVAL_MS,+ requirePublication = false,+ signal,}: {key?: string | null;timeoutMs?: number;intervalMs?: number;+ requirePublication?: boolean;+ signal?: AbortSignal;}): Promise<TokenResult | null> {+ signal?.throwIfAborted();if (!key) return null;- const followRenewals = timeoutMs == null;+ const followRenewals = timeoutMs == null && !requirePublication;let deadline = Date.now() + (timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS);while (Date.now() <= deadline) {+ signal?.throwIfAborted();const flight = await db.findOpenIDRefreshFlight({ key });+ signal?.throwIfAborted();const completed = await readCompletedFlight(flight);- if (completed) return completed;- if (flight?.status === 'completed') return null;- if (!flight) return null;+ signal?.throwIfAborted();+ const awaitingPublication = requirePublication && completed?.__deferredPublication;+ if (completed && !awaitingPublication) return completed;+ if (flight?.status === 'completed' && !awaitingPublication) return null;+ if (!flight && !requirePublication) return null;if (followRenewals) {deadline = getRenewedWaitDeadline(deadline, flight);}- await delay(intervalMs);+ try {+ await delay(intervalMs, undefined, { signal });+ } catch (error) {+ signal?.throwIfAborted();+ throw error;+ }}logger.warn('[OpenIDRefreshFlight] Timed out waiting for refresh flight', { key });return null;diff --git a/packages/api/src/auth/openid/session.ts b/packages/api/src/auth/openid/session.tsindex a402874e00..6782bbb45b 100644--- a/packages/api/src/auth/openid/session.ts+++ b/packages/api/src/auth/openid/session.ts@@ -25,11 +25,15 @@ import type {import type { OpenIdSessionDeps, OpenIdSessionParams } from '~/images/session';import type { TokenResult } from './flight';import {+ OPENID_REFRESH_CANCELLED_BEFORE_GRANT,createOpenIDRefreshOwnershipError,isOpenIDRefreshOwnershipError,toOpenIDLogArgument,} from './errors';+const PUBLICATION_WAIT_TIMEOUT_MS = 10_000;+const PUBLICATION_WAIT_INTERVAL_MS = 250;+interface OpenIDSessionRefreshDeps {jwt: {decode: (token: string) => (Partial<OpenIDClaims> & { exp?: number }) | string | null;@@ -102,12 +106,21 @@ interface OpenIDSessionRefreshDeps {tokens?: TokenResult | null;}) => Promise<RefreshFlightRecord | null>;createOpenIDRefreshFlightKey: (input: RefreshKeyInput) => string | null;+ createRefreshTokenBridgeFlightKey?: (+ input: RefreshTokenBridgeIdentity & { oldRefreshToken: string },+ ) => string | null;failOpenIDRefreshFlight: (args: {key?: string | null;ownerId?: string;error?: Error | null;}) => Promise<RefreshFlightRecord | null>;- waitForOpenIDRefreshFlight: (args: { key?: string | null }) => Promise<TokenResult | null>;+ waitForOpenIDRefreshFlight: (args: {+ key?: string | null;+ requirePublication?: boolean;+ signal?: AbortSignal;+ timeoutMs?: number;+ intervalMs?: number;+ }) => Promise<TokenResult | null>;assertOpenIDRefreshFlightAvailable: (args: {key?: string | null;ownerId?: string;@@ -136,6 +149,7 @@ interface MarkedOIDCTokens extends OIDCTokens {interface RefreshSessionOptions {forceRefresh?: boolean;+ signal?: AbortSignal;assertLeaseOwned?: LeaseAssertion;deferPublication?: boolean;}@@ -162,7 +176,7 @@ interface CreateOpenIDSessionTokenProviderInput {export interface OpenIDSessionRefreshService {createOpenIDSessionTokenProvider: (input: CreateOpenIDSessionTokenProviderInput,- ) => () => Promise<OIDCTokens | null>;+ ) => (options?: { forceRefresh?: boolean; signal?: AbortSignal }) => Promise<OIDCTokens | null>;refreshOpenIDSession: (req: OpenIDRequest,res: OpenIDResponse | undefined,@@ -207,6 +221,7 @@ export function createOpenIDSessionRefreshService(isOpenIDSessionIdentityMatch,createOpenIDRefreshIdentityTuple,createRefreshTokenBridgeIdentity,+ createRefreshTokenBridgeFlightKey,serializeAuthIdentityTuple,buildOpenIDRefreshParams,setRefreshTokenCookie,@@ -291,6 +306,7 @@ export function createOpenIDSessionRefreshService(* grants for the same key.*/const inFlightRefreshes = new Map<string, Promise<MarkedOIDCTokens | null>>();+ const flightSignals = new WeakMap<Promise<MarkedOIDCTokens | null>, AbortSignal>();/*** Returns the single-flight key for a refresh attempt, composed from the user's@@ -1410,6 +1426,7 @@ export function createOpenIDSessionRefreshService(resolvedTokens,predecessorRefreshToken,tokenPreference,+ signal,}: {key: string;req: OpenIDRequest;@@ -1419,9 +1436,44 @@ export function createOpenIDSessionRefreshService(resolvedTokens: MarkedOIDCTokens;predecessorRefreshToken?: string;tokenPreference: TokenPreference;+ signal?: AbortSignal;}): Promise<MarkedOIDCTokens> {+ signal?.throwIfAborted();if (resolvedTokens.__deferredPublication) {- throw new Error('OpenID refresh result is awaiting identity validation');+ const predecessor =+ getPredecessorRefreshTokenMarker(resolvedTokens) ?? predecessorRefreshToken;+ const identity = createRefreshTokenBridgeIdentity({+ user,+ requestUser: req.user,+ userId: identityContext?.appUserId,+ tenantId: identityContext?.tenantId,+ openidIssuer: identityContext?.openidIssuer,+ });+ const publicationKey =+ predecessor && identity+ ? createRefreshTokenBridgeFlightKey?.({ ...identity, oldRefreshToken: predecessor })+ : null;+ const published = publicationKey+ ? await waitForOpenIDRefreshFlight({+ key: publicationKey,+ requirePublication: true,+ timeoutMs: PUBLICATION_WAIT_TIMEOUT_MS,+ intervalMs: PUBLICATION_WAIT_INTERVAL_MS,+ ...(signal ? { signal } : {}),+ })+ : null;+ signal?.throwIfAborted();+ if (!publicationKey || !published || published.__deferredPublication) {+ throw Object.assign(new Error('OpenID refresh publication is temporarily unavailable'), {+ status: 503,+ retryable: true,+ });+ }+ resolvedTokens = cloneResolvedTokens(published);+ key = publicationKey;+ if (published.tokenset) {+ Object.assign(resolvedTokens, published.tokenset);+ }}if (!resolvedTokens.__flightOwnerId) {throw new Error('OpenID refresh result is missing its publication generation');@@ -1441,7 +1493,12 @@ export function createOpenIDSessionRefreshService(resolvedTokens,predecessorRefreshToken,tokenPreference,- assertLeaseOwned: () => assertOpenIDRefreshFlightAvailable(publicationGeneration),+ assertLeaseOwned: async () => {+ signal?.throwIfAborted();+ const available = await assertOpenIDRefreshFlightAvailable(publicationGeneration);+ signal?.throwIfAborted();+ return available;+ },publicationGeneration,effects,});@@ -1470,6 +1527,7 @@ export function createOpenIDSessionRefreshService(tokenPreference: TokenPreference,identityContext?: AuthIdentityContext,deferPublication = false,+ signal?: AbortSignal,): Promise<MarkedOIDCTokens | null> {const refreshToken = req?.session?.openidTokens?.refreshToken;const predecessorAccessToken = req?.session?.openidTokens?.accessToken;@@ -1501,7 +1559,11 @@ export function createOpenIDSessionRefreshService(logger.debug('[OpenIDSessionRefresh] Joining shared refresh flight', {key: hashKeyForLogs(key),});- const resolvedTokens = await waitForOpenIDRefreshFlight({ key });+ const resolvedTokens = await waitForOpenIDRefreshFlight({+ key,+ ...(signal ? { signal } : {}),+ });+ signal?.throwIfAborted();if (resolvedTokens) {if (!deferPublication) {return publishCompletedFlightTokens({@@ -1513,6 +1575,7 @@ export function createOpenIDSessionRefreshService(resolvedTokens,predecessorRefreshToken: refreshToken,tokenPreference,+ signal,});}return resolvedTokens;@@ -1534,8 +1597,13 @@ export function createOpenIDSessionRefreshService(let resolvedTokens: MarkedOIDCTokens | null = null;let successorRefreshToken: string | undefined;let completionIndeterminate = false;+ let grantStarted = false;const publicationEffects = createSessionPublicationEffects();try {+ /** Cancellation before admission must fail the acquired lease. Once a grant+ * starts, settle its rotating credentials durably even if its caller stops. */+ signal?.throwIfAborted();+ grantStarted = true;resolvedTokens = await performIdpRefreshGrant(req,res,@@ -1662,10 +1730,15 @@ export function createOpenIDSessionRefreshService(}if (!completionIndeterminate) {try {+ let failure =+ error instanceof Error ? error : new Error('OpenID session refresh failed');+ if (!grantStarted && signal?.aborted) {+ failure = new Error(OPENID_REFRESH_CANCELLED_BEFORE_GRANT);+ }await failOpenIDRefreshFlight({key,ownerId: flight.ownerId,- error: error instanceof Error ? error : new Error('OpenID session refresh failed'),+ error: failure,});} catch (flightError) {logger.warn('[OpenIDSessionRefresh] Failed to mark shared refresh flight failed', {@@ -1799,6 +1872,7 @@ export function createOpenIDSessionRefreshService(identityContext?: AuthIdentityContext,forceRefresh = false,deferPublication = false,+ signal?: AbortSignal,): Promise<MarkedOIDCTokens | null> {const sessionTokens = req?.session?.openidTokens;if (!sessionTokens) {@@ -1815,7 +1889,16 @@ export function createOpenIDSessionRefreshService(return buildOIDCTokensFromSession(sessionTokens, tokenPreference);}- return performIdpRefresh(req, res, user, tokenPreference, identityContext, deferPublication);+ signal?.throwIfAborted();+ return performIdpRefresh(+ req,+ res,+ user,+ tokenPreference,+ identityContext,+ deferPublication,+ signal,+ );}/**@@ -1839,10 +1922,12 @@ export function createOpenIDSessionRefreshService(identityContext?: AuthIdentityContext,options: RefreshSessionOptions = {},): Promise<MarkedOIDCTokens | null> {+ options.signal?.throwIfAborted();const identityBinding = assertOpenIDSessionIdentityMatch(req, user, identityContext);if (identityBinding) {await identityBinding;}+ options.signal?.throwIfAborted();if (options.assertLeaseOwned) {return performIdpRefreshGrant(req,@@ -1864,10 +1949,32 @@ export function createOpenIDSessionRefreshService(identityContext,options.forceRefresh,options.deferPublication,+ options.signal,);}- const inFlight = inFlightRefreshes.get(key);+ const forcedKey = `${key}:forced`;+ /** A rejection-driven refresh must not join a normal flight that may merely reuse+ * the rejected-but-unexpired token. Join and publish that flight first, then force+ * a distinct refresh so rotating refresh-token state remains serialized. */+ const normalFlight = inFlightRefreshes.get(key);+ if (options.forceRefresh && normalFlight) {+ await refreshOpenIDSession(req, res, user, tokenPreference, identityContext, {+ ...options,+ forceRefresh: false,+ });+ /** The normal flight is resolved at this point. Remove it defensively before+ * the forced pass so promise-cleanup scheduling cannot make us rejoin it. */+ if (inFlightRefreshes.get(key) === normalFlight) {+ inFlightRefreshes.delete(key);+ }+ return refreshOpenIDSession(req, res, user, tokenPreference, identityContext, options);+ }++ /** Normal callers may safely join a forced flight and receive its fresher result. */+ const inFlightKey = !options.forceRefresh && inFlightRefreshes.has(forcedKey) ? forcedKey : key;+ const ownedFlightKey = options.forceRefresh ? forcedKey : inFlightKey;+ const inFlight = inFlightRefreshes.get(ownedFlightKey);if (inFlight) {const predecessorRefreshToken = req?.session?.openidTokens?.refreshToken;const sharedFlightKey = createOpenIDRefreshFlightKey({@@ -1876,8 +1983,26 @@ export function createOpenIDSessionRefreshService(refreshToken: predecessorRefreshToken,identityContext,});- logger.debug(`[OpenIDSessionRefresh] Joining in-flight refresh (key=${hashKeyForLogs(key)})`);- const resolvedTokens = await inFlight;+ logger.debug(+ `[OpenIDSessionRefresh] Joining in-flight refresh (key=${hashKeyForLogs(ownedFlightKey)})`,+ );+ let resolvedTokens: MarkedOIDCTokens | null;+ try {+ resolvedTokens = await inFlight;+ } catch (error) {+ options.signal?.throwIfAborted();+ const leaderSignal = flightSignals.get(inFlight);+ if (!leaderSignal?.aborted || error !== leaderSignal.reason) {+ throw error;+ }+ /** A cancelled follower publication must not strand active local joiners.+ * Rejoin durable coordination; never replay an already-settled IdP grant. */+ if (inFlightRefreshes.get(ownedFlightKey) === inFlight) {+ inFlightRefreshes.delete(ownedFlightKey);+ }+ return refreshOpenIDSession(req, res, user, tokenPreference, identityContext, options);+ }+ options.signal?.throwIfAborted();/*** The leader mutated only its own request's session. Copy the resolved* tokens into THIS request's session so a later OBO call on the joiner@@ -1885,7 +2010,20 @@ export function createOpenIDSessionRefreshService(*/if (!options.deferPublication) {if (resolvedTokens?.__deferredPublication) {- throw new Error('OpenID refresh result is awaiting identity validation');+ if (!sharedFlightKey) {+ throw new Error('OpenID refresh coordination key is unavailable for publication');+ }+ return publishCompletedFlightTokens({+ key: sharedFlightKey,+ req,+ res,+ user,+ identityContext,+ resolvedTokens,+ predecessorRefreshToken,+ tokenPreference,+ signal: options.signal,+ });}const currentSessionTokens = req.session?.openidTokens;const alreadyCurrent = Boolean(@@ -1917,6 +2055,7 @@ export function createOpenIDSessionRefreshService(resolvedTokens,predecessorRefreshToken,tokenPreference,+ signal: options.signal,});}return resolvedTokens;@@ -1930,12 +2069,16 @@ export function createOpenIDSessionRefreshService(identityContext,options.forceRefresh,options.deferPublication,+ options.signal,).finally(() => {- if (inFlightRefreshes.get(key) === promise) {- inFlightRefreshes.delete(key);+ if (inFlightRefreshes.get(ownedFlightKey) === promise) {+ inFlightRefreshes.delete(ownedFlightKey);}});- inFlightRefreshes.set(key, promise);+ inFlightRefreshes.set(ownedFlightKey, promise);+ if (options.signal) {+ flightSignals.set(promise, options.signal);+ }/** Swallow rejection on the cleanup chain; the original is delivered to the awaiter. */promise.catch(() => {});return promise;@@ -1986,7 +2129,7 @@ export function createOpenIDSessionRefreshService(* @param {import('@librechat/data-schemas').IUser} [args.user]* @param {import('@librechat/api').AuthIdentityContext} [args.identityContext]* @param {'access_token' | 'id_token'} args.tokenPreference- * @returns {() => Promise<import('@librechat/data-schemas').OIDCTokens | null>}+ * @returns {(options?: { forceRefresh?: boolean, signal?: AbortSignal }) => Promise<import('@librechat/data-schemas').OIDCTokens | null>}*/function createOpenIDSessionTokenProvider({req,@@ -1994,13 +2137,17 @@ export function createOpenIDSessionRefreshService(user,tokenPreference,identityContext,- }: CreateOpenIDSessionTokenProviderInput): () => Promise<OIDCTokens | null> {+ }: CreateOpenIDSessionTokenProviderInput): (options?: {+ forceRefresh?: boolean;+ signal?: AbortSignal;+ }) => Promise<OIDCTokens | null> {if (tokenPreference !== 'access_token' && tokenPreference !== 'id_token') {throw new Error(`[OpenIDSessionRefresh] createOpenIDSessionTokenProvider requires tokenPreference 'access_token' or 'id_token', got: ${tokenPreference}`,);}- return async function upstreamTokenProvider() {+ return async function upstreamTokenProvider(options = {}) {+ options.signal?.throwIfAborted();if (!isOIDCRefreshApplicable(user)) {return null;}@@ -2024,7 +2171,10 @@ export function createOpenIDSessionRefreshService(user,requestUser: req?.user,});- return refreshOpenIDSession(req, res, user, tokenPreference, resolvedIdentityContext);+ return refreshOpenIDSession(req, res, user, tokenPreference, resolvedIdentityContext, {+ forceRefresh: options.forceRefresh,+ signal: options.signal,+ });};}diff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex 4479e69b3a..3262c4dade 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -24,6 +24,7 @@ export * from './mcp/oauth';export * from './mcp/auth';export * from './mcp/zod';export * from './mcp/errors';+export * from './mcp/openid';export * from './mcp/cache';export * from './mcp/tools';export * from './mcp/catalog/store';diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 00ed13e81e..bc15f82667 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -24,9 +24,18 @@ import {ReauthenticationRequiredError,resolveOboToken,} from '~/mcp/oauth';+import {+ isDirectOpenIDBearerRecoveryEnabled,+ resolveDirectOpenIDBearerConfig,+ usesDirectOpenIDBearerRecovery,+} from './openid';+import {+ isOAuthAuthenticationError,+ isMCPTransportAuthenticationError,+ MCPAuthenticationRejectedError,+} from './errors';import { createDeadlineAbortSignal, isClientRejectionMessage, isOAuthServer } from './utils';import { PENDING_STALE_MS, normalizeExpiresAt } from '~/flow/manager';-import { isOAuthAuthenticationError } from './errors';import { preProcessGraphTokens } from '~/utils/graph';import { MCPConnection } from './connection';import { processMCPEnv } from '~/utils';@@ -37,6 +46,7 @@ export interface ToolDiscoveryResult {connection: MCPConnection | null;oauthRequired: boolean;oauthUrl: string | null;+ authenticationError?: unknown;}type OAuthRequiredEvent = {@@ -65,6 +75,7 @@ export class MCPConnectionFactory {protected readonly allowedDomains?: string[] | null;protected readonly allowedAddresses?: string[] | null;protected readonly ephemeralConnection: boolean;+ protected readonly directBearerRecoveryEnabled: boolean;// OAuth-related properties (only set when useOAuth is true)protected readonly userId?: string;@@ -79,7 +90,7 @@ export class MCPConnectionFactory {protected readonly deadlineMs?: number;protected readonly oboTokenResolver?: OboTokenResolver;protected readonly oboTrustChecker?: OboTrustChecker;- protected readonly upstreamTokenProvider?: UpstreamTokenProvider;+ protected upstreamTokenProvider?: UpstreamTokenProvider;protected readonly oboIdentityContext?: AuthIdentityContext;/** Why the OBO re-exchange failed, when that is more actionable than the server's 401. */private oboRefreshError?: Error;@@ -122,8 +133,53 @@ export class MCPConnectionFactory {basic: t.BasicConnectionOptions,oauth?: t.OAuthConnectionOptions | t.UserConnectionContext,): Promise<MCPConnection> {- const factory = new this(await this.prepareBasicConnectionOptions(basic, oauth), oauth);- return factory.createConnection();+ const directBearerRecoveryState = basic.directBearerRecoveryState ?? { attempted: false };+ const directBearerSourceConfig =+ basic.directBearerSourceConfig ??+ (isDirectOpenIDBearerRecoveryEnabled(basic.serverConfig)+ ? (basic.serverConfig as t.ParsedServerConfig)+ : undefined);+ const create = async (candidate: t.BasicConnectionOptions): Promise<MCPConnection> => {+ const prepared = await this.prepareBasicConnectionOptions(+ { ...candidate, directBearerSourceConfig, directBearerRecoveryState },+ oauth,+ );+ if (directBearerSourceConfig && !directBearerRecoveryState.resolvedConfig) {+ directBearerRecoveryState.resolvedConfig = prepared.serverConfig;+ }+ const factory = new this(prepared, oauth);+ return factory.createConnection();+ };+ if (!directBearerSourceConfig) {+ return create(basic);+ }++ try {+ return await create(basic);+ } catch (error) {+ if (!isMCPTransportAuthenticationError(error) || this.isRequestCancelled(oauth)) {+ throw error;+ }+ if (directBearerRecoveryState.attempted) {+ throw new MCPAuthenticationRejectedError(basic.serverName, false, error);+ }+ directBearerRecoveryState.attempted = true;+ const refreshedConfig = await resolveDirectOpenIDBearerConfig({+ config: directBearerSourceConfig,+ upstreamTokenProvider: oauth?.upstreamTokenProvider,+ forceRefresh: true,+ signal: oauth?.signal,+ });+ directBearerRecoveryState.resolvedConfig = refreshedConfig;+ try {+ return await create({ ...basic, serverConfig: refreshedConfig });+ } catch (refreshedError) {+ if (isMCPTransportAuthenticationError(refreshedError)) {+ throw new MCPAuthenticationRejectedError(basic.serverName, false, refreshedError);+ }+ throw refreshedError;+ }+ }}static attachRequestOAuthHandler(@@ -146,20 +202,68 @@ export class MCPConnectionFactory {): Promise<ToolDiscoveryResult> {/** Checked before credential preparation begins: a spent budget or an already-cancelled* caller must not start Graph preprocessing or token resolution it cannot cancel. */- if (- (options?.deadlineMs != null && Date.now() >= options.deadlineMs) ||- options?.signal?.aborted === true- ) {+ if (this.isRequestCancelled(options)) {logger.debug('[MCP] [Discovery] Cancelled or out of budget before discovery began');return { tools: null, connection: null, oauthRequired: false, oauthUrl: null };}- const preparedBasic = await this.prepareBasicConnectionOptions(basic, options);- if (options != null && 'useOAuth' in options) {- const factory = new this(preparedBasic, { ...options, returnOnOAuth: true });+ const directBearerSourceConfig =+ basic.directBearerSourceConfig ??+ (usesDirectOpenIDBearerRecovery(basic.serverConfig)+ ? (basic.serverConfig as t.ParsedServerConfig)+ : undefined);+ const discover = async (candidate: t.BasicConnectionOptions): Promise<ToolDiscoveryResult> => {+ const prepared = await this.prepareBasicConnectionOptions(+ { ...candidate, directBearerSourceConfig },+ options,+ );+ if (options != null && 'useOAuth' in options) {+ const factory = new this(prepared, { ...options, returnOnOAuth: true });+ return factory.discoverToolsInternal();+ }+ const factory = new this(prepared, options);return factory.discoverToolsInternal();+ };++ const initial = await discover(basic);+ if (!directBearerSourceConfig || !this.hasDiscoveryAuthenticationRejection(initial)) {+ return initial;+ }++ if (initial.connection) {+ await initial.connection.dispose().catch(() => undefined);}- const factory = new this(preparedBasic, options);- return factory.discoverToolsInternal();+ if (this.isRequestCancelled(options)) {+ return { tools: null, connection: null, oauthRequired: false, oauthUrl: null };+ }+ const refreshedConfig = await resolveDirectOpenIDBearerConfig({+ config: directBearerSourceConfig,+ upstreamTokenProvider: options?.upstreamTokenProvider,+ forceRefresh: true,+ signal: options?.signal,+ });+ const refreshed = await discover({ ...basic, serverConfig: refreshedConfig });+ if (this.hasDiscoveryAuthenticationRejection(refreshed)) {+ if (refreshed.connection) {+ await refreshed.connection.dispose().catch(() => undefined);+ }+ throw new MCPAuthenticationRejectedError(+ basic.serverName,+ false,+ refreshed.authenticationError,+ );+ }+ return refreshed;+ }++ private static hasDiscoveryAuthenticationRejection(result: ToolDiscoveryResult): boolean {+ return result.oauthRequired || result.authenticationError != null;+ }++ private static isRequestCancelled(options?: t.UserConnectionContext): boolean {+ return (+ options?.signal?.aborted === true ||+ (options?.deadlineMs != null && Date.now() >= options.deadlineMs)+ );}/**@@ -171,19 +275,47 @@ export class MCPConnectionFactory {basic: t.BasicConnectionOptions,options?: t.OAuthConnectionOptions | t.UserConnectionContext,): Promise<t.BasicConnectionOptions> {+ const bearerConfig = await resolveDirectOpenIDBearerConfig({+ config: basic.serverConfig,+ upstreamTokenProvider: options?.upstreamTokenProvider,+ signal: options?.signal,+ });+ if (basic.directBearerRecoveryState && usesDirectOpenIDBearerRecovery(basic.serverConfig)) {+ basic.directBearerRecoveryState.resolvedConfig = bearerConfig;+ }+ const directBearerSourceConfig =+ basic.directBearerSourceConfig ??+ (usesDirectOpenIDBearerRecovery(basic.serverConfig)+ ? (basic.serverConfig as t.ParsedServerConfig)+ : undefined);+ const preparedBasic =+ bearerConfig === basic.serverConfig &&+ directBearerSourceConfig === basic.directBearerSourceConfig+ ? basic+ : {+ ...basic,+ serverConfig: bearerConfig,+ serverDefinition: basic.serverDefinition ?? basic.serverConfig,+ directBearerSourceConfig,+ };+if (basic.dbSourced || !options?.graphTokenResolver) {- return basic;+ return preparedBasic;}- const serverConfig = await preProcessGraphTokens(basic.serverConfig, {+ const serverConfig = await preProcessGraphTokens(preparedBasic.serverConfig, {user: options.user,graphTokenResolver: options.graphTokenResolver,scopes: process.env.GRAPH_API_SCOPES,});- return serverConfig === basic.serverConfig- ? basic- : { ...basic, serverConfig, serverDefinition: basic.serverDefinition ?? basic.serverConfig };+ return serverConfig === preparedBasic.serverConfig+ ? preparedBasic+ : {+ ...preparedBasic,+ serverConfig,+ serverDefinition: preparedBasic.serverDefinition ?? basic.serverConfig,+ };}protected async discoverToolsInternal(): Promise<ToolDiscoveryResult> {@@ -231,6 +363,7 @@ export class MCPConnectionFactory {useSSRFProtection: this.useSSRFProtection,allowedAddresses: this.allowedAddresses,ephemeralConnection: this.ephemeralConnection,+ ...(this.directBearerRecoveryEnabled && { directBearerRecoveryEnabled: true }),});oauthHandler = () => {@@ -256,6 +389,9 @@ export class MCPConnectionFactory {connection,oauthRequired: false,oauthUrl: null,+ ...(snapshot.authenticationError != null && {+ authenticationError: snapshot.authenticationError,+ }),};}} catch {@@ -434,6 +570,9 @@ export class MCPConnectionFactory {this.allowedDomains = basic.allowedDomains;this.allowedAddresses = basic.allowedAddresses;this.ephemeralConnection = basic.ephemeralConnection === true;+ this.directBearerRecoveryEnabled = isDirectOpenIDBearerRecoveryEnabled(+ basic.directBearerSourceConfig ?? basic.serverConfig,+ );this.connectionTimeout = options?.connectionTimeout;this.deadlineMs = options?.deadlineMs;this.signal = options?.signal;@@ -442,6 +581,7 @@ export class MCPConnectionFactory {this.logPrefix = options?.user ? `[MCP][User: ${options.user.id}]` : '[MCP]';this.user = options?.user;+ this.upstreamTokenProvider = options?.upstreamTokenProvider;if (options != null && 'useOAuth' in options) {this.useOAuth = true;@@ -453,7 +593,6 @@ export class MCPConnectionFactory {this.returnOnOAuth = options.returnOnOAuth;this.oboTokenResolver = options.oboTokenResolver;this.oboTrustChecker = options.oboTrustChecker;- this.upstreamTokenProvider = options.upstreamTokenProvider;this.oboIdentityContext = options.oboIdentityContext;} else {this.useOAuth = false;@@ -553,6 +692,9 @@ export class MCPConnectionFactory {useSSRFProtection: this.useSSRFProtection,allowedAddresses: this.allowedAddresses,ephemeralConnection: this.ephemeralConnection,+ ...(this.directBearerRecoveryEnabled && {+ directBearerRecoveryEnabled: true,+ }),});let cleanupOAuthHandlers: (() => void) | null = null;@@ -580,7 +722,7 @@ export class MCPConnectionFactory {await this.attemptToConnect(connection);this.connectionReady = true;// Keep the `oauthRequired` listener for cached-connection 401 recovery,- // but drop response/tool-call callbacks from the completed request.+ // but drop request-bound callbacks and credentials from the completed request.this.releaseRequestScopedOAuthState();return connection;} catch (error) {@@ -611,6 +753,7 @@ export class MCPConnectionFactory {this.oauthStart = undefined;this.oauthEnd = undefined;this.returnOnOAuth = false;+ this.upstreamTokenProvider = undefined;}private getServerUrl(): string | undefined {@@ -1516,6 +1659,7 @@ export class MCPConnectionFactory {/** Attempts to establish connection with timeout handling */protected async attemptToConnect(connection: MCPConnection): Promise<void> {+ this.signal?.throwIfAborted();const baseTimeout = this.connectionTimeout ?? this.serverConfig.initTimeout ?? 30000;// OAuth servers may pause mid-connect to wait for the user to authorize in the browser.// The transport connect itself is still bounded by initTimeout inside connection.connect(),@@ -1530,6 +1674,17 @@ export class MCPConnectionFactory {? Math.max(baseTimeout, oauthHandlingTimeout + 60000): baseTimeout;const retryController = new AbortController();+ const callerSignal = this.signal;+ let onAbort: (() => void) | undefined;+ const cancelled = new Promise<never>((_, reject) => {+ if (callerSignal) {+ onAbort = () => {+ retryController.abort(callerSignal.reason);+ reject(callerSignal.reason);+ };+ callerSignal.addEventListener('abort', onAbort, { once: true });+ }+ });let timeoutId: NodeJS.Timeout | undefined;const timeout = new Promise<never>((_, reject) => {timeoutId = setTimeout(() => {@@ -1539,15 +1694,21 @@ export class MCPConnectionFactory {});try {- await Promise.race([this.connectTo(connection, retryController.signal), timeout]);+ await Promise.race([this.connectTo(connection, retryController.signal), timeout, cancelled]);} finally {if (timeoutId) {clearTimeout(timeoutId);}retryController.abort();+ if (onAbort) {+ callerSignal?.removeEventListener('abort', onAbort);+ }}- if (await connection.isConnected()) return;+ callerSignal?.throwIfAborted();+ const connected = await connection.isConnected(callerSignal);+ callerSignal?.throwIfAborted();+ if (connected) return;logger.error(`${this.logPrefix} Failed to establish connection.`);}@@ -1591,7 +1752,10 @@ export class MCPConnectionFactory {throw error;}- if (this.useOAuth && isOAuthAuthenticationError(error)) {+ if (+ (this.useOAuth || this.directBearerRecoveryEnabled) &&+ isOAuthAuthenticationError(error)+ ) {logger.info(`${this.logPrefix} OAuth required, stopping connection attempts`);throw error;}diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex b5aff7b21f..fb02ede64f 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -23,6 +23,8 @@ import {resolveServerInstructions,} from './utils';import { getMCPAppToolsPublicationGeneration, getMCPToolsChangedGeneration } from './toolsChanged';+import { MCPAuthenticationRejectedError, isMCPTransportAuthenticationError } from './errors';+import { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from './openid';import { MCPServersInitializer } from './registry/MCPServersInitializer';import { OboTokenResolutionError, resolveOboToken } from '~/mcp/oauth';import { MCPServerInspector } from './registry/MCPServerInspector';@@ -76,13 +78,20 @@ const OAUTH_RECOVERY_RECONNECT_DELAY_MS = 2000;*/export class MCPManager extends UserConnectionManager {private static instance: MCPManager | null;+ private readonly recoveryCancellation = new WeakMap<+ Promise<void>,+ { controller: AbortController; waiters: number; connection: MCPConnection }+ >();+private readonly oauthRecoveries = new WeakMap<MCPConnection,{promise: Promise<void>;- callbacks: OAuthLifecycleRelay;+ callbacks?: OAuthLifecycleRelay;allowsTakeover: boolean;takeoverClaimed?: boolean;+ directBearerRecoveryConsumed?: boolean;+ directBearerRecoveryState?: t.DirectBearerRecoveryState;}>();@@ -125,6 +134,11 @@ export class MCPManager extends UserConnectionManager {opts.serverConfig?.updatedAt != null &&connection.isStale(opts.serverConfig.updatedAt);if (recovery && !providedConfigIsNewer) {+ if (recovery.directBearerRecoveryConsumed && opts.directBearerRecoveryState) {+ opts.directBearerRecoveryState.attempted = true;+ opts.directBearerRecoveryState.resolvedConfig =+ recovery.directBearerRecoveryState?.resolvedConfig;+ }if (recovery.callbacks) {await recovery.callbacks.add({oauthStart: opts.oauthStart,@@ -135,6 +149,9 @@ export class MCPManager extends UserConnectionManager {});}await this.waitForActiveRecovery(recovery.promise, opts.signal);+ if (opts.directBearerRecoveryState && recovery.directBearerRecoveryState) {+ Object.assign(opts.directBearerRecoveryState, recovery.directBearerRecoveryState);+ }}return super.getUserConnection(opts);@@ -164,32 +181,60 @@ export class MCPManager extends UserConnectionManager {}private waitForActiveRecovery(recovery: Promise<void>, signal?: AbortSignal): Promise<void> {+ const shared = this.recoveryCancellation.get(recovery);+ if (shared) {+ shared.waiters++;+ }+ let released = false;+ const release = (aborted: boolean) => {+ if (released || !shared) {+ return;+ }+ released = true;+ shared.waiters--;+ if (aborted && shared.waiters === 0) {+ const abortIfUnowned = () => {+ if (shared.waiters === 0 && !this.hasConnectionBorrowers(shared.connection)) {+ shared.controller.abort(signal?.reason);+ }+ };+ if (this.hasConnectionBorrowers(shared.connection)) {+ /** A leased call registers recovery before releasing its lease after a rejection. */+ void this.waitForConnectionBorrowersToDrain(shared.connection).then(abortIfUnowned);+ } else {+ abortIfUnowned();+ }+ }+ };if (!signal) {- return recovery;+ return recovery.finally(() => release(false));}return new Promise<void>((resolve, reject) => {const onRecoveryResolved = () => {+ release(false);signal.removeEventListener('abort', onAbort);resolve();};const onRecoveryRejected = (error: unknown) => {+ release(false);signal.removeEventListener('abort', onAbort);reject(error);};const onAbort = () => {+ release(true);signal.removeEventListener('abort', onAbort);const reason = signal.reason;reject(reason instanceof Error ? reason : new Error('OAuth recovery wait aborted'));};+ recovery.then(onRecoveryResolved, onRecoveryRejected);if (signal.aborted) {onAbort();return;}signal.addEventListener('abort', onAbort, { once: true });- recovery.then(onRecoveryResolved, onRecoveryRejected);});}@@ -199,6 +244,26 @@ export class MCPManager extends UserConnectionManager {return this.oauthRecoveries.get(connection)?.promise;}+ protected override propagateDirectBearerRecoveryState(+ connection: MCPConnection,+ state?: t.DirectBearerRecoveryState,+ ): void {+ const recovery = this.oauthRecoveries.get(connection);+ if (state && recovery?.directBearerRecoveryConsumed) {+ state.attempted = true;+ const sharedState = recovery.directBearerRecoveryState;+ if (sharedState) {+ state.resolvedConfig = sharedState.resolvedConfig;+ void recovery.promise.then(+ () => {+ state.resolvedConfig = sharedState.resolvedConfig;+ },+ () => undefined,+ );+ }+ }+ }+protected override waitForConnectionRecovery(recovery: Promise<void>,signal?: AbortSignal,@@ -226,6 +291,8 @@ export class MCPManager extends UserConnectionManager {flowManager?: FlowStateManager<MCPOAuthTokens | null>;/** Pre-resolved config for config-source servers not in YAML/DB */serverConfig?: t.ParsedServerConfig;+ /** One-shot direct-bearer recovery budget shared with the invoking tool call. */+ directBearerRecoveryState?: t.DirectBearerRecoveryState;} & Omit<t.OAuthConnectionOptions, 'useOAuth' | 'user' | 'flowManager'>,): Promise<MCPConnection> {const userId = args.user?.id;@@ -374,6 +441,7 @@ export class MCPManager extends UserConnectionManager {customUserVars: args.customUserVars,requestBody: args.requestBody,graphTokenResolver: args.graphTokenResolver,+ upstreamTokenProvider: args.upstreamTokenProvider,connectionTimeout: args.connectionTimeout,deadlineMs: args.deadlineMs,signal: args.signal,@@ -693,6 +761,131 @@ Please follow these instructions when using tools from the respective MCP serverawait this.waitForActiveRecovery(recovery, signal);}+ private recoverDirectOpenIDBearerConnection({+ connection,+ serverName,+ serverConfig,+ user,+ flowManager,+ tokenMethods,+ oauthStart,+ oauthEnd,+ customUserVars,+ requestBody,+ requestScopedConnections,+ graphTokenResolver,+ upstreamTokenProvider,+ oboIdentityContext,+ signal,+ directBearerRecoveryState = { attempted: true },+ }: {+ connection: MCPConnection;+ serverName: string;+ serverConfig: t.ParsedServerConfig;+ user: IUser;+ flowManager: FlowStateManager<MCPOAuthTokens | null>;+ tokenMethods?: TokenMethods;+ oauthStart?: t.OAuthStartHandler;+ oauthEnd?: () => Promise<void>;+ customUserVars?: Record<string, string>;+ requestBody?: RequestBody;+ requestScopedConnections?: t.RequestScopedMCPConnectionStore;+ graphTokenResolver?: GraphTokenResolver;+ upstreamTokenProvider?: UpstreamTokenProvider;+ oboIdentityContext?: AuthIdentityContext;+ signal?: AbortSignal;+ directBearerRecoveryState?: t.DirectBearerRecoveryState;+ }): Promise<void> {+ const existing = this.oauthRecoveries.get(connection);+ if (existing) {+ return this.waitForActiveRecovery(existing.promise, signal).then(() => {+ if (existing.directBearerRecoveryState) {+ Object.assign(directBearerRecoveryState, existing.directBearerRecoveryState);+ }+ });+ }++ const mutationFence = this.createConnectionMutationFence(user.id, serverName);+ const recoveryController = new AbortController();+ const recoverySignal = recoveryController.signal;+ const recovery = Promise.resolve().then(async () => {+ let replacementPromise: Promise<MCPConnection>;+ try {+ recoverySignal.throwIfAborted();+ const refreshedConfig = await resolveDirectOpenIDBearerConfig({+ config: serverConfig,+ upstreamTokenProvider,+ forceRefresh: true,+ signal: recoverySignal,+ });+ directBearerRecoveryState.resolvedConfig = refreshedConfig;+ recoverySignal.throwIfAborted();+ connection.stopReconnecting();+ await this.waitForConnectionBorrowersToDrain(connection);+ recoverySignal.throwIfAborted();+ const requestConnectionKey = `${user.id}:${serverName}`;+ if (requestScopedConnections?.connections.get(requestConnectionKey) === connection) {+ requestScopedConnections.connections.delete(requestConnectionKey);+ await this.disposeEvictedConnection(+ connection,+ `[MCP][Request-scoped: ${requestConnectionKey}]`,+ );+ }+ mutationFence.assertCurrent();+ recoverySignal.throwIfAborted();+ /** Invocation is synchronous through the replacement's own guard registration, closing+ * the mutation window before this outer reservation is released. */+ replacementPromise = this.getUserConnection({+ serverName,+ serverConfig,+ user,+ forceNew: true,+ flowManager,+ tokenMethods,+ oauthStart,+ oauthEnd,+ customUserVars,+ requestBody,+ requestScopedConnections,+ graphTokenResolver,+ upstreamTokenProvider,+ oboIdentityContext,+ directBearerRecoveryState,+ directBearerResolvedConfig: refreshedConfig,+ signal: recoverySignal,+ });+ } finally {+ mutationFence.release();+ }+ const replacement = await replacementPromise;+ if (requiresEphemeralUserConnection(serverConfig) && !requestScopedConnections) {+ await this.disposeEvictedConnection(+ replacement,+ `[MCP][User: ${user.id}][${serverName}] Unowned recovery replacement`,+ );+ }+ });+ const recoveryEntry = {+ promise: recovery,+ allowsTakeover: false,+ directBearerRecoveryConsumed: true,+ directBearerRecoveryState,+ };+ this.recoveryCancellation.set(recovery, {+ controller: recoveryController,+ waiters: 0,+ connection,+ });+ this.oauthRecoveries.set(connection, recoveryEntry);+ const clearRecovery = () => {+ if (this.oauthRecoveries.get(connection) === recoveryEntry) {+ this.oauthRecoveries.delete(connection);+ }+ };+ void recovery.then(clearRecovery, clearRecovery);+ return this.waitForActiveRecovery(recovery, signal);+ }+private async connectAfterOAuthRecovery(connection: MCPConnection,requestInteractiveRecovery: (error: unknown) => Promise<void>,@@ -855,6 +1048,7 @@ Please follow these instructions when using tools from the respective MCP serverconst logPrefix = userId ? `[MCP][User: ${userId}][${serverName}]` : `[MCP][${serverName}]`;this.bindRequestScopedConnectionStore(requestScopedConnections);let recoveryTakeoverConsumed = false;+ const directBearerRecoveryState: t.DirectBearerRecoveryState = { attempted: false };while (true) {/** User-specific connection */let connection: MCPConnection | undefined;@@ -917,12 +1111,16 @@ Please follow these instructions when using tools from the respective MCP serverrequestBody,requestScopedConnections,serverConfig: providedConfig,+ directBearerRecoveryState,});retainConnectionLease();const checkoutRecovery = this.oauthRecoveries.get(connection);if (!checkoutRecovery || checkoutRecovery.promise === awaitedCheckoutRecovery) {break;}+ if (checkoutRecovery.directBearerRecoveryConsumed) {+ directBearerRecoveryState.attempted = true;+ }if (checkoutRecovery.callbacks) {await checkoutRecovery.callbacks.add({oauthStart,@@ -936,6 +1134,9 @@ Please follow these instructions when using tools from the respective MCP serverawait releaseConnectionLease();try {await this.waitForConnectionRecovery(checkoutRecovery.promise, options?.signal);+ if (checkoutRecovery.directBearerRecoveryState) {+ Object.assign(directBearerRecoveryState, checkoutRecovery.directBearerRecoveryState);+ }} catch (recoveryError) {if (options?.signal?.aborted ||@@ -952,22 +1153,6 @@ Please follow these instructions when using tools from the respective MCP server}}- const connectionIsActive = await connection.isConnected();- const connectionCheckError = connectionIsActive- ? undefined- : connection.getLastConnectionCheckError();-- if (- !connectionIsActive &&- (!userId || !connection.isOAuthAuthenticationError(connectionCheckError))- ) {- /** May happen if getUserConnection failed silently or app connection dropped */- throw new McpError(- ErrorCode.InternalError,- `${logPrefix} Connection is not active. Cannot execute tool ${toolName}.`,- );- }-const registry = MCPServersRegistry.getInstance();const rawConfig = providedConfig ?? (await registry.getServerConfig(serverName, userId));if (!rawConfig) {@@ -989,11 +1174,18 @@ Please follow these instructions when using tools from the respective MCP servergraphTokenResolver,scopes: process.env.GRAPH_API_SCOPES,});+ const directBearerRecovery = usesDirectOpenIDBearerRecovery(rawConfig);+ const bearerConfig = await resolveDirectOpenIDBearerConfig({+ config: graphProcessedConfig,+ upstreamTokenProvider,+ resolvedConfig: directBearerRecoveryState.resolvedConfig,+ signal: options?.signal,+ });const currentOptions = processMCPEnv({user,body: requestBody,dbSourced: isDbSourced,- options: graphProcessedConfig,+ options: bearerConfig,customUserVars,});@@ -1112,6 +1304,56 @@ Please follow these instructions when using tools from the respective MCP serverconnection.setRequestHeaders(resolvedHeaders);+ const connectionIsActive = await connection.isConnected(options?.signal);+ const connectionCheckError = connectionIsActive+ ? undefined+ : connection.getLastConnectionCheckError();++ if (+ !connectionIsActive &&+ (!userId || !connection.isOAuthAuthenticationError(connectionCheckError))+ ) {+ /** May happen if getUserConnection failed silently or app connection dropped */+ throw new McpError(+ ErrorCode.InternalError,+ `${logPrefix} Connection is not active. Cannot execute tool ${toolName}.`,+ );+ }++ if (+ !connectionIsActive &&+ directBearerRecovery &&+ userId &&+ user &&+ isMCPTransportAuthenticationError(connectionCheckError)+ ) {+ if (directBearerRecoveryState.attempted) {+ throw new MCPAuthenticationRejectedError(serverName, false, connectionCheckError);+ }+ directBearerRecoveryState.attempted = true;+ const recovery = this.recoverDirectOpenIDBearerConnection({+ connection,+ serverName,+ serverConfig: rawConfig,+ user,+ flowManager,+ tokenMethods,+ oauthStart,+ oauthEnd,+ customUserVars,+ requestBody,+ requestScopedConnections,+ graphTokenResolver,+ upstreamTokenProvider,+ oboIdentityContext,+ signal: options?.signal,+ directBearerRecoveryState,+ });+ await releaseConnectionLease();+ await recovery;+ continue;+ }+if (!connectionIsActive) {const requestOAuthHandler = attachSharedOAuthHandler;if (!requestOAuthHandler || !userId) {@@ -1172,6 +1414,33 @@ Please follow these instructions when using tools from the respective MCP servertry {result = await requestTool();} catch (error) {+ if (directBearerRecovery && user && isMCPTransportAuthenticationError(error)) {+ if (directBearerRecoveryState.attempted) {+ throw new MCPAuthenticationRejectedError(serverName, false, error);+ }+ directBearerRecoveryState.attempted = true;+ const recovery = this.recoverDirectOpenIDBearerConnection({+ connection,+ serverName,+ serverConfig: rawConfig,+ user,+ flowManager,+ tokenMethods,+ oauthStart,+ oauthEnd,+ customUserVars,+ requestBody,+ requestScopedConnections,+ graphTokenResolver,+ upstreamTokenProvider,+ oboIdentityContext,+ signal: options?.signal,+ directBearerRecoveryState,+ });+ await releaseConnectionLease();+ await recovery;+ throw new MCPAuthenticationRejectedError(serverName, true, error);+ }/*** An OBO server rejecting the bearer mid-session is recoverable here and* nowhere else: the downstream token is minted from the upstream sessiondiff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.tsindex bf87869556..d1ff7e7561 100644--- a/packages/api/src/mcp/UserConnectionManager.ts+++ b/packages/api/src/mcp/UserConnectionManager.ts@@ -16,9 +16,11 @@ import {notifyMCPToolsChanged,renewMCPToolsChangedGeneration,} from '~/mcp/toolsChanged';+import { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from '~/mcp/openid';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { ConnectionsRepository } from '~/mcp/ConnectionsRepository';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';+import { MCPAuthenticationRejectedError } from '~/mcp/errors';import { processMCPEnv, isPluginSourced } from '~/utils/env';import { OAuthLifecycleRelay } from '~/mcp/oauth/pending';import { preProcessGraphTokens } from '~/utils/graph';@@ -31,6 +33,8 @@ import { isEnabled } from '~/utils';type PendingConnection = {promise: Promise<MCPConnection>;oauth: OAuthLifecycleRelay;+ directBearerRecoveryState: t.DirectBearerRecoveryState;+ signal?: AbortSignal;};/**@@ -50,6 +54,11 @@ type ConnectionTeardownOptions = {type ConnectionCreationGuard = { cancelledBy: ConnectionTeardownReason | null };+type ConnectionMutationFence = {+ assertCurrent: () => void;+ release: () => void;+};+/** Signals that a teardown fenced an in-flight creation before it could finish. */class ConnectionCreationCancelledError extends Error {constructor(@@ -79,6 +88,12 @@ export abstract class UserConnectionManager {protected userLastActivity: Map<string, number> = new Map();/** In-flight connection promises keyed by `userId:serverName` — coalesces concurrent attempts */protected pendingConnections: Map<string, PendingConnection> = new Map();+ /** Recovery state owned by request-scoped promises, which the public store intentionally keeps opaque. */+ private readonly requestPendingDirectBearerRecoveryStates = new WeakMap<+ Promise<unknown>,+ t.DirectBearerRecoveryState+ >();+private readonly connectionBorrowers = new WeakMap<MCPConnection, number>();private readonly connectionBorrowerDrainWaiters = new WeakMap<MCPConnection, Set<() => void>>();private readonly deferredConnectionDisposalHolds = new WeakMap<MCPConnection, number>();@@ -154,6 +169,26 @@ export abstract class UserConnectionManager {);}+ /** Registers work that resolves a replacement before the ordinary creation queue begins. */+ protected createConnectionMutationFence(+ userId: string,+ serverName: string,+ ): ConnectionMutationFence {+ const key = `${userId}:${serverName}`;+ const guard: ConnectionCreationGuard = { cancelledBy: null };+ this.registerConnectionCreation(key, guard);+ return {+ assertCurrent: () => {+ /** Lifecycle churn does not invalidate the captured config; a committed mutation does. */+ if (guard.cancelledBy === 'lifecycle') {+ guard.cancelledBy = null;+ }+ this.assertCreationNotCancelled(guard, userId, serverName);+ },+ release: () => this.unregisterConnectionCreation(key, guard),+ };+ }+/** A mutation fence outranks a lifecycle one: the stale inputs stay stale either way. */private cancelConnectionCreations(key: string,@@ -299,6 +334,7 @@ export abstract class UserConnectionManager {/** Gets or creates a connection for a specific user, coalescing concurrent attempts */public async getUserConnection(opts: t.UserMCPConnectionOptions): Promise<MCPConnection> {const { serverName, forceNew, user } = opts;+ const directBearerRecoveryState = opts.directBearerRecoveryState ?? { attempted: false };const userId = user?.id;if (!userId) {throw new McpError(ErrorCode.InvalidRequest, `[MCP] User object missing id property`);@@ -321,6 +357,9 @@ export abstract class UserConnectionManager {? opts.requestScopedConnections: undefined;if (requestScopedConnections) {+ if (requestScopedConnections.cleanupStarted) {+ throw new Error(`[MCP][User: ${userId}] Request-scoped connection context is closed`);+ }this.bindRequestScopedConnectionStore(requestScopedConnections);const requestConnectionKey = `${userId}:${serverName}`;const existing = requestScopedConnections.connections.get(requestConnectionKey) as@@ -332,17 +371,23 @@ export abstract class UserConnectionManager {await this.disposeEvictedConnection(existing, `[MCP][User: ${userId}]`);} else {const activeRecovery = this.getActiveConnectionRecovery(existing);+ this.propagateDirectBearerRecoveryState(existing, opts.directBearerRecoveryState);let awaitedRecovery = activeRecovery;if (activeRecovery) {await this.waitForConnectionRecovery(activeRecovery, opts.signal);}let connected = await existing.isConnected();let recovery = this.getActiveConnectionRecovery(existing);+ this.propagateDirectBearerRecoveryState(existing, opts.directBearerRecoveryState);while (recovery && recovery !== awaitedRecovery) {awaitedRecovery = recovery;await this.waitForConnectionRecovery(recovery, opts.signal);connected = await existing.isConnected();recovery = this.getActiveConnectionRecovery(existing);+ this.propagateDirectBearerRecoveryState(existing, opts.directBearerRecoveryState);+ }+ if (requestScopedConnections.connections.get(requestConnectionKey) !== existing) {+ return this.getUserConnection({ ...opts, directBearerRecoveryState });}if (connected) {logger.debug(`[MCP][User: ${userId}] Reusing request-scoped connection`);@@ -358,7 +403,13 @@ export abstract class UserConnectionManager {| undefined;if (pending) {logger.debug(`[MCP][User: ${userId}] Joining in-flight request-scoped connection attempt`);- return pending;+ const connection = await pending;+ if (this.requestPendingDirectBearerRecoveryStates.get(pending)?.attempted) {+ directBearerRecoveryState.attempted = true;+ }+ directBearerRecoveryState.resolvedConfig =+ this.requestPendingDirectBearerRecoveryStates.get(pending)?.resolvedConfig;+ return connection;}const pendingOAuth = new OAuthLifecycleRelay({@@ -366,18 +417,35 @@ export abstract class UserConnectionManager {oauthEnd: opts.oauthEnd,logPrefix: `[MCP][User: ${userId}][${serverName}]`,});- const connectionPromise = this.createUserConnectionInternal(+ const creationGuard: ConnectionCreationGuard = { cancelledBy: null };+ this.registerConnectionCreation(requestConnectionKey, creationGuard);+ const connectionPromise = this.createUserConnectionWithLifecycleRestarts({...opts,forceNew: true,ephemeralConnection: true,serverConfig: config,+ directBearerRecoveryState,oauthStart: pendingOAuth.start,oauthEnd: pendingOAuth.end,},userId,forceNew === true,- ).then((connection) => {+ creationGuard,+ ).then(async (connection) => {+ try {+ opts.signal?.throwIfAborted();+ this.assertCreationNotCancelled(creationGuard, userId, serverName);+ if (requestScopedConnections.cleanupStarted) {+ throw new Error(`[MCP][User: ${userId}] Request-scoped connection context is closed`);+ }+ } catch (error) {+ await this.disposeEvictedConnection(+ connection,+ `[MCP][Request-scoped: ${requestConnectionKey}] Invalidated during connection creation`,+ );+ throw error;+ }requestScopedConnections.connections.set(requestConnectionKey, connection);return connection;});@@ -386,10 +454,15 @@ export abstract class UserConnectionManager {requestConnectionKey,connectionPromise as Promise<unknown>,);+ this.requestPendingDirectBearerRecoveryStates.set(+ connectionPromise,+ directBearerRecoveryState,+ );try {return await connectionPromise;} finally {+ this.unregisterConnectionCreation(requestConnectionKey, creationGuard);if (requestScopedConnections.pending.get(requestConnectionKey) === connectionPromise) {requestScopedConnections.pending.delete(requestConnectionKey);}@@ -405,14 +478,44 @@ export abstract class UserConnectionManager {const pending = this.pendingConnections.get(lockKey);if (pending) {logger.debug(`[MCP][User: ${userId}] Joining in-flight connection attempt`);- await pending.oauth.add({- oauthStart: opts.oauthStart,- oauthEnd: opts.oauthEnd,- flowManager: opts.flowManager,- userId,- serverName,- });- return pending.promise;+ const mutationFence = this.createConnectionMutationFence(userId, serverName);+ try {+ await pending.oauth.add({+ oauthStart: opts.oauthStart,+ oauthEnd: opts.oauthEnd,+ flowManager: opts.flowManager,+ userId,+ serverName,+ });+ opts.signal?.throwIfAborted();+ await this.waitForConnectionRecovery(+ pending.promise.then(() => undefined),+ opts.signal,+ );+ const connection = await pending.promise;+ opts.signal?.throwIfAborted();+ mutationFence?.assertCurrent();+ if (pending.directBearerRecoveryState.attempted) {+ directBearerRecoveryState.attempted = true;+ }+ directBearerRecoveryState.resolvedConfig =+ pending.directBearerRecoveryState.resolvedConfig;+ return connection;+ } catch (error) {+ opts.signal?.throwIfAborted();+ mutationFence?.assertCurrent();+ if (!mutationFence || !pending.signal?.aborted || error !== pending.signal.reason) {+ throw error;+ }+ /** The stopped leader owns its aborted attempt, not this still-active request.+ * Continue with an independently owned creation, preserving any spent auth budget. */+ directBearerRecoveryState.attempted ||= pending.directBearerRecoveryState.attempted;+ if (this.pendingConnections.get(lockKey) === pending) {+ this.pendingConnections.delete(lockKey);+ }+ } finally {+ mutationFence?.release();+ }}}@@ -430,6 +533,7 @@ export abstract class UserConnectionManager {forceNew: forceNewConnection,ephemeralConnection,serverConfig: config,+ directBearerRecoveryState,oauthStart: pendingOAuth.start,oauthEnd: pendingOAuth.end,},@@ -445,6 +549,8 @@ export abstract class UserConnectionManager {this.pendingConnections.set(lockKey, {promise: connectionPromise,oauth: pendingOAuth,+ directBearerRecoveryState,+ signal: opts.signal,});}@@ -482,11 +588,14 @@ export abstract class UserConnectionManager {graphTokenResolver,ephemeralConnection = false,serverConfig: providedConfig,+ directBearerRecoveryState = { attempted: false },+ directBearerResolvedConfig,}: t.UserMCPConnectionOptions,userId: string,clearCooldown: boolean,creationGuard?: ConnectionCreationGuard,): Promise<MCPConnection> {+ signal?.throwIfAborted();this.assertCreationNotCancelled(creationGuard, userId, serverName);if (await this.appConnections!.has(serverName)) {throw new McpError(@@ -587,18 +696,22 @@ export abstract class UserConnectionManager {connection = undefined;} else {const activeRecovery = this.getActiveConnectionRecovery(connection);+ this.propagateDirectBearerRecoveryState(connection, directBearerRecoveryState);let awaitedRecovery = activeRecovery;if (activeRecovery) {await this.waitForConnectionRecovery(activeRecovery, signal);}let connected = await connection.isConnected();let recovery = this.getActiveConnectionRecovery(connection);+ this.propagateDirectBearerRecoveryState(connection, directBearerRecoveryState);while (recovery && recovery !== awaitedRecovery) {awaitedRecovery = recovery;await this.waitForConnectionRecovery(recovery, signal);connected = await connection.isConnected();recovery = this.getActiveConnectionRecovery(connection);+ this.propagateDirectBearerRecoveryState(connection, directBearerRecoveryState);}+ this.assertCreationNotCancelled(creationGuard, userId, serverName);if (connected) {logger.debug(`[MCP][User: ${userId}] Reusing active connection`);await this.updateUserLastActivity(userId);@@ -632,8 +745,20 @@ export abstract class UserConnectionManager {logger.info(`[MCP][User: ${userId}] Establishing new connection`);try {+ signal?.throwIfAborted();+ const bearerConfig =+ directBearerResolvedConfig ??+ (await resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider,+ signal,+ }));+ signal?.throwIfAborted();+ if (usesDirectOpenIDBearerRecovery(config)) {+ directBearerRecoveryState.resolvedConfig = bearerConfig;+ }const runtimeConfig = await this.applyRuntimeOAuthDetection({- config,+ config: bearerConfig,user,customUserVars,requestBody,@@ -657,6 +782,8 @@ export abstract class UserConnectionManager {/** Runtime OAuth detection enriches the connection config. Keep the durable definition* separate so callback liveness compares against the config that actually owns it. */serverDefinition: config,+ ...(usesDirectOpenIDBearerRecovery(config) && { directBearerSourceConfig: config }),+ directBearerRecoveryState,serverName: serverName,dbSourced: isUserSourced(runtimeConfig),useSSRFProtection,@@ -665,7 +792,9 @@ export abstract class UserConnectionManager {ephemeralConnection,};- const useOAuth = requiresOAuthMachinery(runtimeConfig);+ const useOAuth = usesDirectOpenIDBearerRecovery(config)+ ? false+ : requiresOAuthMachinery(runtimeConfig);let connectionOptions: t.OAuthConnectionOptions | t.UserConnectionContext;if (useOAuth) {if (!flowManager) {@@ -699,7 +828,9 @@ export abstract class UserConnectionManager {customUserVars,requestBody,graphTokenResolver,+ upstreamTokenProvider,connectionTimeout,+ signal,};}@@ -729,8 +860,62 @@ export abstract class UserConnectionManager {throw new Error('Failed to establish connection after initialization attempt.');}+ const directBearerRecovery = usesDirectOpenIDBearerRecovery(config);+ if (!ephemeralConnection || directBearerRecovery) {+ const toolListSnapshot = await connection.refreshToolList(signal);+ signal?.throwIfAborted();+ const toolListAuthenticationError = toolListSnapshot?.authenticationError;+ if (toolListAuthenticationError && directBearerRecovery && user) {+ if (directBearerRecoveryState.attempted) {+ throw new MCPAuthenticationRejectedError(+ serverName,+ false,+ toolListAuthenticationError,+ );+ }+ directBearerRecoveryState.attempted = true;+ signal?.throwIfAborted();+ const refreshedConfig = await resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider,+ forceRefresh: true,+ signal,+ });+ signal?.throwIfAborted();+ connection.removeAllListeners('toolsChanged');+ await connection.dispose();+ return this.createUserConnectionInternal(+ {+ serverName,+ forceNew: true,+ user,+ flowManager,+ customUserVars,+ requestBody,+ tokenMethods,+ oauthStart,+ oauthEnd,+ oboTokenResolver,+ oboTrustChecker,+ upstreamTokenProvider,+ oboIdentityContext,+ signal,+ returnOnOAuth,+ connectionTimeout,+ graphTokenResolver,+ ephemeralConnection,+ serverConfig: config,+ directBearerRecoveryState,+ directBearerResolvedConfig: refreshedConfig,+ },+ userId,+ clearCooldown,+ creationGuard,+ );+ }+ }if (!ephemeralConnection) {- await connection.refreshToolList();+ signal?.throwIfAborted();this.assertCreationNotCancelled(creationGuard, userId, serverName);if (!this.userConnections.has(userId)) {this.userConnections.set(userId, new Map());@@ -740,11 +925,13 @@ export abstract class UserConnectionManager {logger.info(`[MCP][User: ${userId}][${serverName}] Connection successfully established`);await this.backfillResolvedInstructions(serverName, config, connection, userId);+ signal?.throwIfAborted();if (!ephemeralConnection) {await this.updateUserLastActivity(userId);await this.assertToolPublicationLeaseCurrent(connection, userId, serverName, creationGuard);}this.assertCreationNotCancelled(creationGuard, userId, serverName);+ signal?.throwIfAborted();return connection;} catch (error) {logger.error(`[MCP][User: ${userId}] Failed to establish connection`);@@ -998,6 +1185,11 @@ export abstract class UserConnectionManager {return undefined;}+ protected propagateDirectBearerRecoveryState(+ _connection: MCPConnection,+ _state?: t.DirectBearerRecoveryState,+ ): void {}+protected waitForConnectionRecovery(recovery: Promise<void>,_signal?: AbortSignal,@@ -1039,8 +1231,12 @@ export abstract class UserConnectionManager {}}+ protected hasConnectionBorrowers(connection: MCPConnection): boolean {+ return (this.connectionBorrowers.get(connection) ?? 0) > 0;+ }+protected waitForConnectionBorrowersToDrain(connection: MCPConnection): Promise<void> {- if ((this.connectionBorrowers.get(connection) ?? 0) === 0) {+ if (!this.hasConnectionBorrowers(connection)) {return Promise.resolve();}diff --git a/packages/api/src/mcp/__tests__/MCPConnectionDisposeRace.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionDisposeRace.test.tsindex 8851bff659..c005750a77 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionDisposeRace.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionDisposeRace.test.ts@@ -10,7 +10,10 @@*/import { Server } from '@modelcontextprotocol/sdk/server/index.js';import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';-import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';+import {+ ListToolsRequestSchema,+ InitializeRequestSchema,+} from '@modelcontextprotocol/sdk/types.js';import { MCPConnection } from '~/mcp/connection';jest.setTimeout(10_000);@@ -39,6 +42,52 @@ describe('MCPConnection disposal during connect', () => {server = undefined;});+ it('does not charge a disposed initialize attempt to connection health', async () => {+ server = new Server({ name: 'cancelled-initialize', version: '1.0.0' }, { capabilities: {} });+ let started: (() => void) | undefined;+ const initializeStarted = new Promise<void>((resolve) => {+ started = resolve;+ });+ let finish: (() => void) | undefined;+ const gate = new Promise<void>((resolve) => {+ finish = resolve;+ });+ server.setRequestHandler(InitializeRequestSchema, async (request) => {+ started?.();+ await gate;+ return {+ protocolVersion: request.params.protocolVersion,+ capabilities: {},+ serverInfo: { name: 'cancelled-initialize', version: '1.0.0' },+ };+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ const connection = new MCPConnection({+ serverName: 'cancelled-initialize',+ serverConfig: { type: 'streamable-http', url: 'http://localhost/mcp' },+ useSSRFProtection: false,+ directBearerRecoveryEnabled: true,+ });+ jest+ .spyOn(+ connection as unknown as { constructTransport: () => Promise<unknown> },+ 'constructTransport',+ )+ .mockResolvedValue(clientTransport);+ const recordFailedRound = jest.spyOn(+ connection as unknown as { recordFailedRound: () => void },+ 'recordFailedRound',+ );+ const connecting = connection.connectClient().catch((error: Error) => error);+ await initializeStarted;+ await connection.dispose();+ finish?.();+ await connecting;+ expect(recordFailedRound).not.toHaveBeenCalled();+ expect(await connection.isConnected()).toBe(false);+ });+it('leaves no live session when disposal lands while the transport is being constructed', async () => {server = new Server({ name: 'dispose-race-server', version: '1.0.0' },diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.tsindex d8c9f9ad76..d77dc30d41 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts@@ -5,6 +5,7 @@ import type { MCPOAuthTokens } from '~/mcp/oauth';import type * as t from '~/mcp/types';import { MCPOAuthHandler, MCPTokenStorage, OboTokenResolutionError } from '~/mcp/oauth';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';+import { MCPAuthenticationRejectedError } from '~/mcp/errors';import { preProcessGraphTokens } from '~/utils/graph';import { PENDING_STALE_MS } from '~/flow/manager';import { MCPConnection } from '~/mcp/connection';@@ -93,6 +94,10 @@ class InspectableMCPConnectionFactory extends MCPConnectionFactory {returnOnOAuth: this.returnOnOAuth,};}++ public hasUpstreamTokenProviderForTest(): boolean {+ return this.upstreamTokenProvider != null;+ }}describe('MCPConnectionFactory', () => {@@ -226,6 +231,36 @@ describe('MCPConnectionFactory', () => {}});+ it('disposes a direct-bearer transport when cancellation races initialize', async () => {+ const controller = new AbortController();+ const config = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.com',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ mockProcessMCPEnv.mockImplementation(({ options }) => options);+ let finishConnect: (() => void) | undefined;+ mockConnectionInstance.connect.mockReturnValue(+ new Promise<void>((resolve) => {+ finishConnect = resolve;+ }),+ );+ const factory = new InspectableMCPConnectionFactory(+ { serverName: 'cancelled-direct', serverConfig: config },+ { user: mockUser, signal: controller.signal },+ );+ const connection = factory.createConnectionForTest();+ const outcome = connection.catch((error: Error) => error);+ await new Promise((resolve) => setImmediate(resolve));+ controller.abort(new Error('request stopped'));+ await expect(outcome).resolves.toMatchObject({ message: 'request stopped' });+ expect(mockConnectionInstance.dispose).toHaveBeenCalledTimes(1);+ finishConnect?.();+ await new Promise((resolve) => setImmediate(resolve));+ expect(mockConnectionInstance.connect).toHaveBeenCalledTimes(1);+ });+it('aborts only the local waiter for a shared OAuth flow', async () => {const abortController = new AbortController();const abortReason = new Error('owner request aborted');@@ -2641,6 +2676,7 @@ describe('MCPConnectionFactory', () => {const oauthStart = jest.fn();const oauthEnd = jest.fn();const requestAbortController = new AbortController();+ const upstreamTokenProvider = jest.fn();const factory = new InspectableMCPConnectionFactory({serverName: 'test-server',@@ -2653,6 +2689,7 @@ describe('MCPConnectionFactory', () => {oauthStart,oauthEnd,signal: requestAbortController.signal,+ upstreamTokenProvider,returnOnOAuth: true,tokenMethods: {findToken: jest.fn(),@@ -2677,6 +2714,7 @@ describe('MCPConnectionFactory', () => {oauthEnd: undefined,returnOnOAuth: false,});+ expect(factory.hasUpstreamTokenProviderForTest()).toBe(false);});it('should let a live request handle cached-connection reauthentication with fresh callbacks', async () => {@@ -3978,6 +4016,233 @@ describe('MCPConnectionFactory', () => {expect(result.connection).toBe(mockConnectionInstance);});+ it('forces one direct bearer refresh when the initial connection handshake rejects it', async () => {+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ const rejectedConnection = {+ ...mockConnectionInstance,+ connect: jest.fn().mockRejectedValue(authError),+ dispose: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<MCPConnection>;+ const refreshedConnection = {+ ...mockConnectionInstance,+ connect: jest.fn().mockResolvedValue(undefined),+ isConnected: jest.fn().mockResolvedValue(true),+ } as unknown as jest.Mocked<MCPConnection>;+ mockMCPConnection+ .mockImplementationOnce(() => rejectedConnection)+ .mockImplementationOnce(() => refreshedConnection);+ mockProcessMCPEnv.mockImplementation(({ options }) => options);+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });+ const directBearerSourceConfig = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.com',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.MCPOptions;+ const serverConfig = {+ ...directBearerSourceConfig,+ headers: { Authorization: 'Bearer stale-token' },+ } as t.MCPOptions;+ const directBearerRecoveryState: t.DirectBearerRecoveryState = { attempted: false };++ const connection = await MCPConnectionFactory.create(+ {+ serverName: 'direct-bearer',+ serverConfig,+ directBearerSourceConfig,+ directBearerRecoveryState,+ },+ { user: mockUser, upstreamTokenProvider },+ );++ expect(connection).toBe(refreshedConnection);+ expect(rejectedConnection.connect).toHaveBeenCalledTimes(1);+ expect(rejectedConnection.dispose).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).toHaveBeenCalledWith({ forceRefresh: true });+ expect(directBearerRecoveryState.resolvedConfig).toMatchObject({+ headers: { Authorization: 'Bearer fresh-token' },+ });+ expect(mockMCPConnection).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ serverConfig: expect.objectContaining({+ headers: { Authorization: 'Bearer fresh-token' },+ }),+ directBearerRecoveryEnabled: true,+ }),+ );+ });++ it('treats a replacement handshake rejection as terminal without refreshing again', async () => {+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ const rejectedConnection = {+ ...mockConnectionInstance,+ connect: jest.fn().mockRejectedValue(authError),+ dispose: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<MCPConnection>;+ mockMCPConnection.mockImplementationOnce(() => rejectedConnection);+ mockProcessMCPEnv.mockImplementation(({ options }) => options);+ const upstreamTokenProvider = jest.fn();+ const directBearerSourceConfig = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.com',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.MCPOptions;++ await expect(+ MCPConnectionFactory.create(+ {+ serverName: 'direct-bearer',+ serverConfig: {+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ headers: { Authorization: 'Bearer refreshed-token' },+ } as t.MCPOptions,+ directBearerSourceConfig,+ directBearerRecoveryState: { attempted: true },+ },+ { user: mockUser, upstreamTokenProvider },+ ),+ ).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ } satisfies Partial<MCPAuthenticationRejectedError>);++ expect(mockMCPConnection).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ });++ it('replaces one direct OpenID bearer connection and rediscovers after tools/list rejects it', async () => {+ const staleError = Object.assign(new Error('unauthorized'), { status: 401 });+ const firstConnection = {+ ...mockConnectionInstance,+ connect: jest.fn().mockResolvedValue(undefined),+ isConnected: jest.fn().mockResolvedValue(true),+ fetchOrderedToolsSnapshot: jest.fn().mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError: staleError,+ }),+ dispose: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<MCPConnection>;+ const refreshedConnection = {+ ...mockConnectionInstance,+ connect: jest.fn().mockResolvedValue(undefined),+ isConnected: jest.fn().mockResolvedValue(true),+ fetchOrderedToolsSnapshot: jest+ .fn()+ .mockResolvedValue({ tools: mockTools, complete: true }),+ } as unknown as jest.Mocked<MCPConnection>;+ mockMCPConnection+ .mockImplementationOnce(() => firstConnection)+ .mockImplementationOnce(() => refreshedConnection);+ mockProcessMCPEnv.mockImplementation(({ options }) => options);+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'stale-token' })+ .mockResolvedValueOnce({ access_token: 'fresh-token' });+ const serverConfig = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.com',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.MCPOptions;++ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'direct-bearer', serverConfig },+ { user: mockUser, upstreamTokenProvider },+ );++ expect(result.tools).toEqual(mockTools);+ expect(firstConnection.dispose).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).toHaveBeenNthCalledWith(1, { forceRefresh: false });+ expect(upstreamTokenProvider).toHaveBeenNthCalledWith(2, { forceRefresh: true });+ expect(mockMCPConnection).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ serverConfig: expect.objectContaining({+ headers: { Authorization: 'Bearer fresh-token' },+ }),+ }),+ );+ });++ it('returns a terminal auth outcome after the replacement discovery is also rejected', async () => {+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ const rejectedConnection = (): jest.Mocked<MCPConnection> =>+ ({+ ...mockConnectionInstance,+ connect: jest.fn().mockResolvedValue(undefined),+ isConnected: jest.fn().mockResolvedValue(true),+ fetchOrderedToolsSnapshot: jest.fn().mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError: authError,+ }),+ dispose: jest.fn().mockResolvedValue(undefined),+ }) as unknown as jest.Mocked<MCPConnection>;+ mockMCPConnection+ .mockImplementationOnce(() => rejectedConnection())+ .mockImplementationOnce(() => rejectedConnection());+ mockProcessMCPEnv.mockImplementation(({ options }) => options);+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'stale-token' })+ .mockResolvedValueOnce({ access_token: 'fresh-token' });+ const serverConfig = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.com',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.MCPOptions;++ await expect(+ MCPConnectionFactory.discoverTools(+ { serverName: 'direct-bearer', serverConfig },+ { user: mockUser, upstreamTokenProvider },+ ),+ ).rejects.toBeInstanceOf(MCPAuthenticationRejectedError);+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(2);+ expect(mockMCPConnection).toHaveBeenCalledTimes(2);+ });++ it('does not force-refresh after an authentication rejection when discovery was cancelled', async () => {+ const controller = new AbortController();+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ const rejectedConnection = {+ ...mockConnectionInstance,+ connect: jest.fn().mockResolvedValue(undefined),+ isConnected: jest.fn().mockResolvedValue(true),+ fetchOrderedToolsSnapshot: jest.fn().mockImplementation(async () => {+ controller.abort();+ return { tools: [], complete: false, authenticationError: authError };+ }),+ dispose: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<MCPConnection>;+ mockMCPConnection.mockImplementationOnce(() => rejectedConnection);+ mockProcessMCPEnv.mockImplementation(({ options }) => options);+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'stale-token' });+ const serverConfig = {+ type: 'streamable-http' as const,+ url: 'https://mcp.example.com',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.MCPOptions;++ const result = await MCPConnectionFactory.discoverTools(+ { serverName: 'direct-bearer', serverConfig },+ { user: mockUser, upstreamTokenProvider, signal: controller.signal },+ );++ expect(result.tools).toBeNull();+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).not.toHaveBeenCalledWith({ forceRefresh: true });+ expect(mockMCPConnection).toHaveBeenCalledTimes(1);+ });+it('does not expose an incomplete discovery snapshot as authoritative', async () => {const basicOptions = {serverName: 'test-server',diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.tsindex 705b9ef89d..8a23c26258 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFetchTools.test.ts@@ -9,6 +9,7 @@*/import { logger } from '@librechat/data-schemas';+import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';import { MCPConnection } from '~/mcp/connection';import { mcpConfig } from '~/mcp/mcpConfig';@@ -48,11 +49,15 @@ const makeTool = (name: string) => ({});/** Build a bare MCPConnection (no real transport) with an injected, controllable client. */-function createConnectionWithListTools(listTools: jest.Mock): MCPConnection {+function createConnectionWithListTools(+ listTools: jest.Mock,+ directBearerRecoveryEnabled = false,+): MCPConnection {const conn = new MCPConnection({serverName: 'pagination-test',serverConfig: { type: 'streamable-http', url: 'http://localhost/mcp' },useSSRFProtection: false,+ directBearerRecoveryEnabled,});conn.client.listTools = listTools;return conn;@@ -130,6 +135,60 @@ describe('MCPConnection.fetchTools pagination', () => {});});+ it.each([+ { notificationFirst: true, interruption: 'none' },+ { notificationFirst: false, interruption: 'none' },+ { notificationFirst: true, interruption: 'abort' },+ { notificationFirst: true, interruption: 'disconnect' },+ ])(+ 'orders auth rejection with notificationFirst=$notificationFirst, interruption=$interruption',+ async ({ notificationFirst, interruption }) => {+ let releaseStale!: (value: { tools: ReturnType<typeof makeTool>[] }) => void;+ let rejectRefresh!: (error: Error) => void;+ const stale = new Promise<{ tools: ReturnType<typeof makeTool>[] }>((resolve) => {+ releaseStale = resolve;+ });+ const refresh = new Promise<never>((_, reject) => {+ rejectRefresh = reject;+ });+ const listTools = jest.fn().mockReturnValueOnce(stale).mockReturnValueOnce(refresh);+ const conn = createConnectionWithListTools(listTools, true);+ Reflect.set(conn, 'connectionState', 'connected');+ jest.spyOn(conn.client, 'getServerCapabilities').mockReturnValue({ tools: {} });+ const authenticationError = Object.assign(new Error('Unauthorized'), { status: 401 });++ const controller = new AbortController();+ const requested = conn.fetchOrderedToolsSnapshot(undefined, controller.signal);+ await Promise.resolve();+ const notified = conn.refreshToolList();+ if (notificationFirst) {+ rejectRefresh(authenticationError);+ await notified;+ if (interruption === 'abort') {+ controller.abort();+ } else if (interruption === 'disconnect') {+ await conn.disconnect();+ }+ releaseStale({ tools: [makeTool('stale')] });+ } else {+ releaseStale({ tools: [makeTool('stale')] });+ await Promise.resolve();+ rejectRefresh(authenticationError);+ await notified;+ }++ if (interruption === 'none') {+ await expect(requested).resolves.toEqual(+ expect.objectContaining({ complete: false, authenticationError }),+ );+ } else {+ await expect(requested).resolves.toEqual({ tools: [], complete: false });+ }+ expect(listTools).toHaveBeenCalledTimes(2);+ await conn.disconnect();+ },+ );+it('follows nextCursor across pages, concatenating every tool and passing the cursor back', async () => {const listTools = jest.fn(async (params?: { cursor?: string }) => {switch (params?.cursor) {@@ -350,7 +409,7 @@ describe('MCPConnection.fetchTools pagination', () => {const conn = createConnectionWithListTools(jest.fn());const mutable = conn as unknown as {toolListChangeGeneration: number;- toolListRefreshPromise: Promise<void> | null;+ toolListRefreshPromise: Promise<unknown> | null;};/** A `list_changed` lands mid-fetch, so the ordered read must wait on a refresh... */const listTools = jest.fn(async () => {@@ -374,7 +433,7 @@ describe('MCPConnection.fetchTools pagination', () => {const conn = createConnectionWithListTools(jest.fn());const mutable = conn as unknown as {toolListChangeGeneration: number;- toolListRefreshPromise: Promise<void> | null;+ toolListRefreshPromise: Promise<unknown> | null;};const listTools = jest.fn(async () => {mutable.toolListChangeGeneration = 1;@@ -465,6 +524,119 @@ describe('MCPConnection.fetchTools pagination', () => {expect(listTools).toHaveBeenCalledTimes(1);expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining('Failed to fetch tools'));});++ it('preserves an authentication rejection without scheduling a health retry', async () => {+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ const listTools = jest.fn().mockRejectedValue(authError);+ const conn = createConnectionWithListTools(listTools, true);+ Reflect.set(conn, 'connectionState', 'connected');+ jest.spyOn(conn.client, 'getServerCapabilities').mockReturnValue({ tools: {} });++ const snapshot = await conn.refreshToolList();++ expect(snapshot?.authenticationError).toBe(authError);+ expect(Reflect.get(conn, 'toolListRefreshFailures')).toBe(0);+ expect(Reflect.get(conn, 'toolListRefreshRetryTimer')).toBeNull();+ expect(Reflect.get(conn, 'toolListRefreshSuspended')).toBe(true);+ await Promise.resolve();+ expect(listTools).toHaveBeenCalledTimes(1);++ const ownerSnapshot = await conn.refreshToolList();+ expect(ownerSnapshot?.authenticationError).toBe(authError);+ expect(listTools).toHaveBeenCalledTimes(1);++ conn.emit('connectionChange', 'disconnected');+ expect(await conn.refreshToolList()).toBeUndefined();+ listTools.mockResolvedValue({ tools: [makeTool('recovered')] });+ conn.emit('connectionChange', 'connected');+ const recoveredSnapshot = await conn.refreshToolList();+ expect(recoveredSnapshot?.complete).toBe(true);+ expect(recoveredSnapshot?.authenticationError).toBeUndefined();+ });++ it('cancels an owned catalog read without retrying it in the background', async () => {+ const controller = new AbortController();+ const listTools = jest.fn(+ (_params, options) =>+ new Promise((_resolve, reject) => {+ options.signal.addEventListener('abort', () => reject(options.signal.reason), {+ once: true,+ });+ }),+ );+ const conn = createConnectionWithListTools(listTools, true);+ Reflect.set(conn, 'connectionState', 'connected');+ jest.spyOn(conn.client, 'getServerCapabilities').mockReturnValue({ tools: {} });+ const read = conn.refreshToolList(controller.signal);+ const outcome = read.catch((error: Error) => error);+ await new Promise((resolve) => setImmediate(resolve));+ controller.abort(new Error('request stopped'));+ await expect(outcome).resolves.toMatchObject({ message: 'request stopped' });+ await new Promise((resolve) => setImmediate(resolve));+ expect(listTools).toHaveBeenCalledTimes(1);+ expect(Reflect.get(conn, 'toolListRefreshRetryTimer')).toBeNull();+ });++ it('does not treat a JSON-RPC catalog error mentioning auth as transport rejection', async () => {+ const conn = createConnectionWithListTools(+ jest+ .fn()+ .mockRejectedValue(+ new McpError(ErrorCode.InternalError, 'downstream HTTP 401 invalid_token'),+ ),+ true,+ );+ expect((await conn.fetchToolsSnapshot()).authenticationError).toBeUndefined();+ });++ it('keeps ordinary authentication modes eligible for tool-list retry', async () => {+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ const listTools = jest.fn().mockRejectedValue(authError);+ const conn = createConnectionWithListTools(listTools);+ Reflect.set(conn, 'connectionState', 'connected');+ jest.spyOn(conn.client, 'getServerCapabilities').mockReturnValue({ tools: {} });++ await conn.refreshToolList();++ expect(Reflect.get(conn, 'toolListRefreshSuspended')).toBe(false);+ expect(Reflect.get(conn, 'toolListRefreshFailures')).toBe(1);+ const retryTimer = Reflect.get(conn, 'toolListRefreshRetryTimer') as NodeJS.Timeout;+ expect(retryTimer).toBeDefined();+ clearTimeout(retryTimer);+ });++ it('does not classify an ordinary tools/list failure as authentication rejection', async () => {+ const conn = createConnectionWithListTools(jest.fn().mockRejectedValue(new Error('boom')));++ const snapshot = await conn.fetchToolsSnapshot();++ expect(snapshot.authenticationError).toBeUndefined();+ });++ it('scopes authentication rejection to the exact concurrent snapshot that observed it', async () => {+ const authError = Object.assign(new Error('unauthorized'), { status: 401 });+ let rejectFirst: ((error: unknown) => void) | undefined;+ const firstPage = new Promise<never>((_resolve, reject) => {+ rejectFirst = reject;+ });+ const listTools = jest+ .fn()+ .mockReturnValueOnce(firstPage)+ .mockResolvedValueOnce({ tools: [makeTool('healthy')] });+ const conn = createConnectionWithListTools(listTools);++ const rejected = conn.fetchToolsSnapshot();+ await Promise.resolve();+ const healthy = conn.fetchToolsSnapshot();+ rejectFirst?.(authError);++ await expect(healthy).resolves.toMatchObject({ complete: true });+ await expect(rejected).resolves.toMatchObject({+ complete: false,+ authenticationError: authError,+ });+ expect((await healthy).authenticationError).toBeUndefined();+ });});describe('MCPConnection.usesOAuth', () => {diff --git a/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.tsindex 83ff8823a6..83b90e47e2 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts@@ -319,6 +319,43 @@ async function createOversizedToolResultStreamableServer(};}+describe('direct bearer HTTP rejection', () => {+ it.each([+ ['sse', 401],+ ['sse', 403],+ ['streamable-http', 401],+ ['streamable-http', 403],+ ] as const)('preserves a structured %s POST status %s', async (type, status) => {+ const server = http.createServer((_req, res) => {+ res.writeHead(status);+ res.end('credential rejected');+ });+ const close = trackSockets(server);+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const url = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}/mcp`;+ const connection = new MCPConnection({+ serverName: 'direct-bearer',+ serverConfig: { type, url },+ useSSRFProtection: false,+ directBearerRecoveryEnabled: true,+ });+ const createFetch = Reflect.get(connection, 'createFetchFunction') as (+ getHeaders: () => Record<string, string>,+ ) => CustomFetch;+ try {+ await expect(+ createFetch.call(connection, () => ({ Authorization: 'Bearer token' }))(url, {+ method: 'POST',+ body: '{}',+ }),+ ).rejects.toMatchObject({ name: 'MCPTransportAuthenticationError', status });+ } finally {+ await connection.dispose();+ await close();+ }+ });+});+describe('MCP SSRF protection – redirect blocking', () => {let redirectServer: TestServer;let conn: MCPConnection | null;@@ -957,6 +994,68 @@ describe('MCP SSRF protection – customFetch input shapes', () => {const originalMaxResponseBytes = process.env.MCP_STREAMABLE_HTTP_MAX_RESPONSE_BYTES;const originalMaxLineBytes = process.env.MCP_STREAMABLE_HTTP_MAX_LINE_BYTES;+ it.each([true, false])(+ 'uses the live bearer on SSE stream reconnect only in direct mode: %s',+ async (directBearerRecoveryEnabled) => {+ const requests: http.IncomingHttpHeaders[] = [];+ let stream: http.ServerResponse | undefined;+ let reconnected!: () => void;+ const reconnect = new Promise<void>((resolve) => {+ reconnected = resolve;+ });+ const server = http.createServer((req, res) => {+ requests.push(req.headers);+ stream = res;+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ res.write('retry: 10\nevent: endpoint\ndata: /messages\n\n');+ if (requests.length === 2) {+ reconnected();+ }+ });+ const close = trackSockets(server);+ const port = await getFreePort();+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));+ const config = {+ type: 'sse' as const,+ url: `http://127.0.0.1:${port}/sse`,+ headers: {+ Authorization: 'Bearer old-token',+ 'X-Access-Token': 'old-token',+ 'X-Operator': 'configured',+ },+ };+ conn = new MCPConnection({+ serverName: 'sse-live-bearer',+ serverConfig: config,+ useSSRFProtection: false,+ directBearerRecoveryEnabled,+ });+ const transport = await conn['constructTransport'](config);+ try {+ await transport.start();+ conn.setRequestHeaders({+ AUTHORIZATION: 'Bearer fresh-token',+ 'X-Access-Token': 'fresh-token',+ 'X-Request': 'private',+ });+ stream?.end();+ await reconnect;+ expect(requests[0].authorization).toBe('Bearer old-token');+ expect(requests[1].authorization).toBe(+ directBearerRecoveryEnabled ? 'Bearer fresh-token' : 'Bearer old-token',+ );+ expect(requests[1]['x-operator']).toBe('configured');+ expect(requests[1]['x-access-token']).toBe(+ directBearerRecoveryEnabled ? 'fresh-token' : 'old-token',+ );+ expect(requests[1]['x-request']).toBeUndefined();+ } finally {+ await transport.close();+ await close();+ }+ },+ );+afterEach(async () => {if (originalMaxResponseBytes == null) {delete process.env.MCP_STREAMABLE_HTTP_MAX_RESPONSE_BYTES;diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex 9fff1b915f..5712fcd83a 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -1,5 +1,6 @@import { EventEmitter } from 'events';import { logger } from '@librechat/data-schemas';+import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';import type { IUser } from '@librechat/data-schemas';import type { GraphTokenResolver } from '~/utils/graph';import type * as t from '~/mcp/types';@@ -9,6 +10,8 @@ import { MCPServersInitializer } from '~/mcp/registry/MCPServersInitializer';import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';import { ConnectionsRepository } from '~/mcp/ConnectionsRepository';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';+import { MCPAuthenticationRejectedError } from '~/mcp/errors';+import { OpenIDReauthRequiredError } from '~/utils/oidc';import { isMCPDomainAllowed } from '~/auth/domain';import * as toolsChanged from '~/mcp/toolsChanged';import { MCPConnection } from '~/mcp/connection';@@ -371,7 +374,9 @@ describe('MCPManager', () => {serverConfig: { type: 'streamable-http', url: 'http://localhost/mcp' },useSSRFProtection: false,});- const refreshToolList = jest.spyOn(connection, 'refreshToolList').mockResolvedValue();+ const refreshToolList = jest+ .spyOn(connection, 'refreshToolList')+ .mockResolvedValue(undefined);const getMany = jest.fn().mockResolvedValue(new Map([['dynamic', connection]]));mockAppConnections({ getMany });(mockRegistryInstance.getAllServerConfigs as jest.Mock).mockResolvedValue({@@ -2819,6 +2824,51 @@ describe('MCPManager', () => {expect(mockConnection.client.request).toHaveBeenCalled();});+ it('passes the OBO-cleaned config into runtime header processing', async () => {+ const mixedConfig = {+ ...serverConfig,+ source: 'yaml' as const,+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Service': 'private-mcp',+ },+ };+ mockResolveOboToken.mockResolvedValue({+ access_token: 'fresh-obo-token',+ token_type: 'Bearer',+ obtained_at: Date.now(),+ expires_at: Date.now() + 3600_000,+ });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(mixedConfig);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ jest.spyOn(manager, 'getUserConnection').mockResolvedValue(mockConnection);++ await manager.callTool({+ user: mockUser as IUser,+ serverName,+ toolName: 'test_tool',+ provider: 'openai',+ flowManager: mockFlowManager as unknown as Parameters<+ typeof manager.callTool+ >[0]['flowManager'],+ oboTokenResolver: mockOboTokenResolver,+ upstreamTokenProvider: mockUpstreamTokenProvider,+ });++ expect(mockProcessMCPEnv).toHaveBeenCalledWith(+ expect.objectContaining({+ options: expect.objectContaining({+ headers: { 'X-Service': 'private-mcp' },+ }),+ }),+ );+ expect(mockConnection.setRequestHeaders).toHaveBeenCalledWith({+ 'X-Service': 'private-mcp',+ Authorization: 'Bearer fresh-obo-token',+ });+ });+it('should fail closed with a retryable message when per-call OBO refresh has a transient failure', async () => {mockResolveOboToken.mockRejectedValue(new OboTokenResolutionError(@@ -3057,6 +3107,718 @@ describe('MCPManager', () => {});});+ describe('direct OpenID bearer recovery', () => {+ const serverName = 'direct-bearer-server';+ const serverConfig = {+ type: 'streamable-http' as const,+ url: 'https://api.example.com/mcp',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ const user = {+ id: 'direct-user',+ provider: 'openid',+ openidId: 'direct-subject',+ } as IUser;++ it('refreshes and replaces the connection without replaying a rejected tool call', async () => {+ const rejection = Object.assign(new Error('HTTP 401 Unauthorized'), { status: 401 });+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ stopReconnecting: jest.fn(),+ isOAuthAuthenticationError: jest.fn().mockReturnValue(true),+ timeout: 30000,+ client: { request: jest.fn().mockRejectedValue(rejection) },+ } as unknown as MCPConnection;+ const replacement = {+ isConnected: jest.fn().mockResolvedValue(true),+ } as unknown as MCPConnection;+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'current-token' })+ .mockResolvedValueOnce({ access_token: 'refreshed-token' });++ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(async (config) => config);+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnection = jest+ .spyOn(manager, 'getUserConnection')+ .mockResolvedValueOnce(connection)+ .mockResolvedValueOnce(replacement);++ await expect(+ manager.callTool({+ user,+ serverName,+ toolName: 'mutating_tool',+ provider: 'openai',+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ }),+ ).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: true,+ } satisfies Partial<MCPAuthenticationRejectedError>);++ expect(connection.client.request).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).toHaveBeenNthCalledWith(2, {+ forceRefresh: true,+ signal: expect.any(AbortSignal),+ });+ expect(connection.stopReconnecting).toHaveBeenCalled();+ expect(getUserConnection).toHaveBeenLastCalledWith(+ expect.objectContaining({+ forceNew: true,+ serverConfig,+ directBearerRecoveryState: expect.objectContaining({ attempted: true }),+ directBearerResolvedConfig: expect.objectContaining({+ headers: { Authorization: 'Bearer refreshed-token' },+ }),+ }),+ );+ });++ it('preserves a JSON-RPC tool failure that mentions downstream authentication', async () => {+ const toolError = new McpError(ErrorCode.InternalError, 'downstream HTTP 401 invalid_token');+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ stopReconnecting: jest.fn(),+ timeout: 30000,+ client: { request: jest.fn().mockRejectedValue(toolError) },+ } as unknown as MCPConnection;+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'valid-token' });+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(async (config) => config);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const checkout = jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);+ await expect(+ manager.callTool({+ user,+ serverName,+ serverConfig,+ toolName: 'mutating_tool',+ provider: 'openai',+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ }),+ ).rejects.toBe(toolError);+ expect(checkout).toHaveBeenCalledTimes(1);+ expect(connection.stopReconnecting).not.toHaveBeenCalled();+ expect(upstreamTokenProvider).not.toHaveBeenCalledWith({ forceRefresh: true });+ });++ it('reuses a recovered checkout bearer for the first tool request without another session read', async () => {+ const makeConnection = () =>+ ({+ isConnected: jest.fn().mockResolvedValue(true),+ isStale: jest.fn().mockReturnValue(false),+ setRequestHeaders: jest.fn(),+ on: jest.fn(),+ removeAllListeners: jest.fn(),+ dispose: jest.fn().mockResolvedValue(undefined),+ timeout: 30000,+ refreshToolList: jest.fn().mockResolvedValue({ tools: [], complete: true }),+ client: {+ request: jest.fn().mockResolvedValue({ content: [{ type: 'text', text: 'done' }] }),+ },+ }) as unknown as MCPConnection;+ const rejected = makeConnection();+ const replacement = makeConnection();+ (rejected.refreshToolList as jest.Mock).mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError: Object.assign(new Error('unauthorized'), { status: 401 }),+ });+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'stale-token' })+ .mockResolvedValueOnce({ access_token: 'fresh-token' });+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(async (config) => config);+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ (MCPConnectionFactory.create as jest.Mock)+ .mockResolvedValueOnce(rejected)+ .mockResolvedValueOnce(replacement);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await manager.callTool({+ user,+ serverName,+ serverConfig,+ toolName: 'mutating_tool',+ provider: 'openai',+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ });+ expect(upstreamTokenProvider.mock.calls).toEqual([+ [{ forceRefresh: false }],+ [{ forceRefresh: true }],+ ]);+ expect(replacement.setRequestHeaders).toHaveBeenCalledWith({+ Authorization: 'Bearer fresh-token',+ });+ expect(rejected.client.request).not.toHaveBeenCalled();+ expect(replacement.client.request).toHaveBeenCalledTimes(1);+ });++ it('shares a checkout recovery budget with the rejected tool call', async () => {+ const rejection = Object.assign(new Error('HTTP 401 Unauthorized'), { status: 401 });+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ stopReconnecting: jest.fn(),+ isOAuthAuthenticationError: jest.fn().mockReturnValue(true),+ timeout: 30000,+ client: { request: jest.fn().mockRejectedValue(rejection) },+ } as unknown as MCPConnection;+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });++ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(async (config) => config);+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnection = jest+ .spyOn(manager, 'getUserConnection')+ .mockImplementation(async (options) => {+ options.directBearerRecoveryState!.attempted = true;+ return connection;+ });++ await expect(+ manager.callTool({+ user,+ serverName,+ toolName: 'mutating_tool',+ provider: 'openai',+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ }),+ ).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ } satisfies Partial<MCPAuthenticationRejectedError>);++ expect(connection.client.request).toHaveBeenCalledTimes(1);+ expect(connection.stopReconnecting).not.toHaveBeenCalled();+ expect(getUserConnection).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).not.toHaveBeenCalledWith({ forceRefresh: true });+ });++ it('propagates direct recovery registered during the base cached checkout', async () => {+ let finishConnectionCheck: ((connected: boolean) => void) | undefined;+ const connectionCheck = new Promise<boolean>((resolve) => {+ finishConnectionCheck = resolve;+ });+ const connection = {+ isConnected: jest.fn().mockReturnValueOnce(connectionCheck).mockResolvedValue(true),+ isStale: jest.fn().mockReturnValue(false),+ } as unknown as MCPConnection;+ let finishRecovery: (() => void) | undefined;+ const recovery = new Promise<void>((resolve) => {+ finishRecovery = resolve;+ });++ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const internals = manager as unknown as {+ userConnections: Map<string, Map<string, MCPConnection>>;+ oauthRecoveries: WeakMap<+ MCPConnection,+ {+ promise: Promise<void>;+ allowsTakeover: boolean;+ directBearerRecoveryConsumed: boolean;+ directBearerRecoveryState?: t.DirectBearerRecoveryState;+ }+ >;+ };+ internals.userConnections.set(user.id, new Map([[serverName, connection]]));+ const directBearerRecoveryState: t.DirectBearerRecoveryState = { attempted: false };+ const sharedState: t.DirectBearerRecoveryState = { attempted: true };++ const checkout = manager.getUserConnection({+ serverName,+ serverConfig,+ user,+ directBearerRecoveryState,+ });+ while ((connection.isConnected as jest.Mock).mock.calls.length === 0) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ internals.oauthRecoveries.set(connection, {+ promise: recovery,+ allowsTakeover: false,+ directBearerRecoveryConsumed: true,+ directBearerRecoveryState: sharedState,+ });+ finishConnectionCheck?.(true);+ await new Promise((resolve) => setImmediate(resolve));++ expect(directBearerRecoveryState.attempted).toBe(true);+ internals.oauthRecoveries.delete(connection);+ sharedState.resolvedConfig = {+ ...serverConfig,+ headers: { Authorization: 'Bearer recovered-token' },+ };+ finishRecovery?.();++ await expect(checkout).resolves.toBe(connection);+ expect(connection.isConnected).toHaveBeenCalledTimes(2);+ expect(directBearerRecoveryState.resolvedConfig).toBe(sharedState.resolvedConfig);+ });++ it.each([false, true])(+ 'propagates a connection leader recovery budget to a pending checkout joiner (request-scoped=%s)',+ async (requestScoped) => {+ const rejection = Object.assign(new Error('HTTP 401 Unauthorized'), { status: 401 });+ const checkoutConfig = requestScoped+ ? {+ ...serverConfig,+ headers: {+ ...serverConfig.headers,+ 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}',+ },+ }+ : serverConfig;+ const requestScopedConnections = requestScoped+ ? {+ connections: new Map<string, unknown>(),+ pending: new Map<string, Promise<unknown>>(),+ }+ : undefined;+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ isStale: jest.fn().mockReturnValue(false),+ setRequestHeaders: jest.fn(),+ stopReconnecting: jest.fn(),+ isOAuthAuthenticationError: jest.fn().mockReturnValue(true),+ refreshToolList: jest.fn().mockResolvedValue({ tools: [], complete: true }),+ on: jest.fn(),+ removeAllListeners: jest.fn(),+ dispose: jest.fn().mockResolvedValue(undefined),+ timeout: 30000,+ client: { request: jest.fn().mockRejectedValue(rejection) },+ } as unknown as MCPConnection;+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });+ let releaseCreation: (() => void) | undefined;+ const creationGate = new Promise<void>((resolve) => {+ releaseCreation = resolve;+ });++ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(+ async (config) => config,+ );+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(checkoutConfig);+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (MCPConnectionFactory.create as jest.Mock).mockImplementation(+ async (basic: t.BasicConnectionOptions) => {+ basic.directBearerRecoveryState!.attempted = true;+ await creationGate;+ return connection;+ },+ );+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const invocation = () =>+ manager.callTool({+ user,+ serverName,+ serverConfig: checkoutConfig,+ toolName: 'mutating_tool',+ provider: 'openai',+ requestBody: requestScoped ? { conversationId: 'conversation-1' } : undefined,+ requestScopedConnections,+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ });++ const leader = invocation();+ while ((MCPConnectionFactory.create as jest.Mock).mock.calls.length === 0) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ const joiner = invocation();+ await new Promise((resolve) => setImmediate(resolve));+ releaseCreation?.();++ await Promise.all([+ expect(leader).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ }),+ expect(joiner).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ }),+ ]);+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);+ expect(connection.client.request).toHaveBeenCalledTimes(2);+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).not.toHaveBeenCalledWith({ forceRefresh: true });+ },+ );++ it('propagates an active direct recovery budget to a checkout waiter', async () => {+ const rejection = Object.assign(new Error('HTTP 401 Unauthorized'), { status: 401 });+ const oldConnection = {+ isConnected: jest.fn().mockResolvedValue(false),+ } as unknown as MCPConnection;+ const replacement = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ stopReconnecting: jest.fn(),+ isOAuthAuthenticationError: jest.fn().mockReturnValue(true),+ timeout: 30000,+ client: { request: jest.fn().mockRejectedValue(rejection) },+ } as unknown as MCPConnection;+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });++ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(async (config) => config);+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ jest+ .spyOn(manager, 'getConnection')+ .mockResolvedValueOnce(oldConnection)+ .mockResolvedValueOnce(replacement);+ (+ manager as unknown as {+ oauthRecoveries: WeakMap<+ MCPConnection,+ {+ promise: Promise<void>;+ allowsTakeover: boolean;+ directBearerRecoveryConsumed: boolean;+ }+ >;+ }+ ).oauthRecoveries.set(oldConnection, {+ promise: Promise.resolve(),+ allowsTakeover: false,+ directBearerRecoveryConsumed: true,+ });++ await expect(+ manager.callTool({+ user,+ serverName,+ serverConfig,+ toolName: 'mutating_tool',+ provider: 'openai',+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ }),+ ).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ });+ expect(replacement.client.request).toHaveBeenCalledTimes(1);+ expect(replacement.stopReconnecting).not.toHaveBeenCalled();+ expect(upstreamTokenProvider).not.toHaveBeenCalledWith({ forceRefresh: true });+ });++ it('installs an ephemeral replacement in the request-scoped store without leaking the old connection', async () => {+ const rejection = Object.assign(new Error('HTTP 401 Unauthorized'), { status: 401 });+ const scopedConfig = {+ ...serverConfig,+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}',+ },+ };+ const connection = {+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ stopReconnecting: jest.fn(),+ isOAuthAuthenticationError: jest.fn().mockReturnValue(true),+ timeout: 30000,+ client: { request: jest.fn().mockRejectedValue(rejection) },+ } as unknown as MCPConnection;+ const replacement = {+ isConnected: jest.fn().mockResolvedValue(true),+ } as unknown as MCPConnection;+ const requestScopedConnections = {+ connections: new Map([[`${user.id}:${serverName}`, connection]]),+ pending: new Map(),+ };+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'current-token' })+ .mockResolvedValueOnce({ access_token: 'refreshed-token' });++ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(async (config) => config);+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(scopedConfig);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const disposeEvicted = jest+ .spyOn(+ manager as unknown as {+ disposeEvictedConnection: (+ connection: MCPConnection,+ logPrefix: string,+ ) => Promise<void>;+ },+ 'disposeEvictedConnection',+ )+ .mockResolvedValue(undefined);+ jest+ .spyOn(manager, 'getUserConnection')+ .mockResolvedValueOnce(connection)+ .mockImplementationOnce(async () => {+ requestScopedConnections.connections.set(`${user.id}:${serverName}`, replacement);+ return replacement;+ });++ await expect(+ manager.callTool({+ user,+ serverName,+ serverConfig: scopedConfig,+ toolName: 'mutating_tool',+ provider: 'openai',+ requestBody: { conversationId: 'conversation-1' } as Parameters<+ typeof manager.callTool+ >[0]['requestBody'],+ requestScopedConnections,+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ }),+ ).rejects.toMatchObject({ code: 'MCP_AUTHENTICATION_REJECTED' });++ expect(disposeEvicted).toHaveBeenCalledWith(+ connection,+ expect.stringContaining('Request-scoped'),+ );+ expect(requestScopedConnections.connections.get(`${user.id}:${serverName}`)).toBe(+ replacement,+ );+ expect(connection.client.request).toHaveBeenCalledTimes(1);+ });++ it.each(['before', 'refresh', 'drain'] as const)(+ 'stops direct-bearer recovery when cancelled during %s',+ async (abortAt) => {+ const controller = new AbortController();+ const cancelled = new Error('request stopped');+ const connection = { stopReconnecting: jest.fn() } as unknown as MCPConnection;+ const upstreamTokenProvider = jest.fn(async () => {+ if (abortAt === 'refresh') {+ controller.abort(cancelled);+ }+ return { access_token: 'fresh-token' };+ });+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnection = jest.spyOn(manager, 'getUserConnection');+ const internals = manager as unknown as {+ waitForConnectionBorrowersToDrain: (connection: MCPConnection) => Promise<void>;+ recoverDirectOpenIDBearerConnection: (args: {+ connection: MCPConnection;+ serverName: string;+ serverConfig: t.ParsedServerConfig;+ user: IUser;+ flowManager: Parameters<typeof manager.callTool>[0]['flowManager'];+ upstreamTokenProvider: NonNullable<+ Parameters<typeof manager.callTool>[0]['upstreamTokenProvider']+ >;+ signal: AbortSignal;+ }) => Promise<void>;+ };+ jest.spyOn(internals, 'waitForConnectionBorrowersToDrain').mockImplementation(async () => {+ if (abortAt === 'drain') {+ controller.abort(cancelled);+ }+ });+ if (abortAt === 'before') {+ controller.abort(cancelled);+ }++ await expect(+ internals.recoverDirectOpenIDBearerConnection({+ connection,+ serverName,+ serverConfig,+ user,+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ signal: controller.signal,+ }),+ ).rejects.toBe(cancelled);+ await new Promise((resolve) => setImmediate(resolve));++ expect(upstreamTokenProvider).toHaveBeenCalledTimes(abortAt === 'before' ? 0 : 1);+ expect(getUserConnection).not.toHaveBeenCalled();+ },+ );++ it.each(['refresh', 'drain', 'initialize'] as const)(+ 'keeps shared recovery alive after its leader aborts during %s',+ async (stage) => {+ const leaderAbort = new AbortController();+ const waiterAbort = new AbortController();+ let entered!: () => void;+ let finish!: () => void;+ const started = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const pause = async () => {+ entered();+ await gate;+ };+ const connection = { stopReconnecting: jest.fn() } as unknown as MCPConnection;+ const replacement = {} as MCPConnection;+ const upstreamTokenProvider = jest.fn(async () => {+ if (stage === 'refresh') {+ await pause();+ }+ return { access_token: 'fresh-token' };+ });+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ jest+ .spyOn(+ manager as unknown as {+ waitForConnectionBorrowersToDrain: (connection: MCPConnection) => Promise<void>;+ },+ 'waitForConnectionBorrowersToDrain',+ )+ .mockImplementation(async () => {+ if (stage === 'drain') {+ await pause();+ }+ });+ const getConnection = jest+ .spyOn(manager, 'getUserConnection')+ .mockImplementation(async (options) => {+ if (stage === 'initialize') {+ await pause();+ }+ options.signal?.throwIfAborted();+ return replacement;+ });+ const options = {+ connection,+ serverName,+ serverConfig,+ user,+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ };+ const leader = manager['recoverDirectOpenIDBearerConnection']({+ ...options,+ signal: leaderAbort.signal,+ });+ const leaderOutcome = leader.catch((error: Error) => error);+ await started;+ const waiter = manager['recoverDirectOpenIDBearerConnection']({+ ...options,+ signal: waiterAbort.signal,+ });+ leaderAbort.abort(new Error('leader stopped'));+ await expect(leaderOutcome).resolves.toMatchObject({ message: 'leader stopped' });+ finish();+ await expect(waiter).resolves.toBeUndefined();+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(getConnection).toHaveBeenCalledTimes(1);+ expect(getConnection.mock.calls[0][0].signal?.aborted).toBe(false);+ },+ );++ it.each([true, false])(+ 'accounts for a borrower before it can join recovery (joins=%s)',+ async (joins) => {+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const connection = { stopReconnecting: jest.fn() } as unknown as MCPConnection;+ const controller = new AbortController();+ let finish!: () => void;+ let entered!: () => void;+ const gate = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const started = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const upstreamTokenProvider = jest.fn(async () => {+ entered();+ await gate;+ return { access_token: 'fresh-token' };+ });+ const getConnection = jest+ .spyOn(manager, 'getUserConnection')+ .mockResolvedValue({} as MCPConnection);+ manager['retainConnection'](connection);+ const options = {+ connection,+ serverName,+ serverConfig,+ user,+ upstreamTokenProvider,+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ };+ const leader = manager['recoverDirectOpenIDBearerConnection']({+ ...options,+ signal: controller.signal,+ });+ const outcome = leader.catch((error: Error) => error);+ await started;+ controller.abort(new Error('leader stopped'));+ await expect(outcome).resolves.toMatchObject({ message: 'leader stopped' });+ const waiter = joins ? manager['recoverDirectOpenIDBearerConnection'](options) : undefined;+ await manager['releaseConnection'](connection);+ finish();+ if (waiter) {+ await expect(waiter).resolves.toBeUndefined();+ }+ await new Promise((resolve) => setImmediate(resolve));+ expect(getConnection).toHaveBeenCalledTimes(joins ? 1 : 0);+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ },+ );++ it('fences a delayed direct-bearer replacement when the server config mutates', async () => {+ const connection = {+ stopReconnecting: jest.fn(),+ } as unknown as MCPConnection;+ let finishRefresh: ((tokens: { access_token: string }) => void) | undefined;+ const forcedRefresh = new Promise<{ access_token: string }>((resolve) => {+ finishRefresh = resolve;+ });+ const upstreamTokenProvider = jest.fn().mockReturnValue(forcedRefresh);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnection = jest.spyOn(manager, 'getUserConnection');+ const recovery = (+ manager as unknown as {+ recoverDirectOpenIDBearerConnection: (args: {+ connection: MCPConnection;+ serverName: string;+ serverConfig: t.ParsedServerConfig;+ user: IUser;+ flowManager: Parameters<typeof manager.callTool>[0]['flowManager'];+ upstreamTokenProvider: NonNullable<+ Parameters<typeof manager.callTool>[0]['upstreamTokenProvider']+ >;+ }) => Promise<void>;+ }+ ).recoverDirectOpenIDBearerConnection({+ connection,+ serverName,+ serverConfig,+ user,+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ upstreamTokenProvider,+ });+ while (upstreamTokenProvider.mock.calls.length === 0) {+ await new Promise((resolve) => setImmediate(resolve));+ }++ await manager.disconnectUserConnection(user.id, serverName);+ finishRefresh?.({ access_token: 'fresh-token' });++ await expect(recovery).rejects.toThrow('cancelled during teardown');+ expect(getUserConnection).not.toHaveBeenCalled();+ expect(connection.stopReconnecting).toHaveBeenCalledTimes(1);+ });+ });+describe('getConnection', () => {const mockUser: Partial<IUser> = {id: 'user-123',@@ -3628,6 +4390,300 @@ describe('MCPManager', () => {expect(mockConnection.refreshToolList).toHaveBeenCalledTimes(1);});+ it('recovers an ephemeral initial tools/list rejection once and fences the replacement', async () => {+ const authenticationError = Object.assign(new Error('unauthorized'), { status: 401 });+ const rejectedConnection = newUserConnection();+ const replacementConnection = newUserConnection();+ (rejectedConnection.refreshToolList as jest.Mock).mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError,+ });+ (replacementConnection.refreshToolList as jest.Mock).mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError,+ });+ const directBearerConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}',+ },+ };+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'stale-token' })+ .mockResolvedValueOnce({ access_token: 'fresh-token' })+ .mockResolvedValueOnce({ access_token: 'fresh-token' });+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(directBearerConfig);+ (MCPConnectionFactory.create as jest.Mock)+ .mockResolvedValueOnce(rejectedConnection)+ .mockResolvedValueOnce(replacementConnection);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await expect(+ manager.getUserConnection({+ serverName,+ user: mockUser,+ requestBody: { conversationId: 'conversation-1' },+ upstreamTokenProvider,+ }),+ ).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ } satisfies Partial<MCPAuthenticationRejectedError>);++ expect(rejectedConnection.dispose).toHaveBeenCalledTimes(1);+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(2);+ expect(MCPConnectionFactory.create).toHaveBeenLastCalledWith(+ expect.objectContaining({+ ephemeralConnection: true,+ directBearerRecoveryState: expect.objectContaining({ attempted: true }),+ }),+ expect.any(Object),+ );+ expect(upstreamTokenProvider.mock.calls).toEqual([+ [{ forceRefresh: false }],+ [{ forceRefresh: true }],+ ]);+ expect(MCPConnectionFactory.create).toHaveBeenLastCalledWith(+ expect.objectContaining({+ serverDefinition: directBearerConfig,+ directBearerSourceConfig: directBearerConfig,+ serverConfig: expect.objectContaining({+ headers: expect.objectContaining({ Authorization: 'Bearer fresh-token' }),+ }),+ }),+ expect.any(Object),+ );+ });++ it.each([false, true])(+ 'does not publish a cancelled initial catalog (request-scoped=%s)',+ async (requestScoped) => {+ const controller = new AbortController();+ const candidate = newUserConnection();+ let finishCatalog: (() => void) | undefined;+ (candidate.refreshToolList as jest.Mock).mockReturnValue(+ new Promise<void>((resolve) => {+ finishCatalog = resolve;+ }),+ );+ const config: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ ...(requestScoped && { 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}' }),+ },+ };+ const store = { connections: new Map(), pending: new Map() };+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(+ async (options) => options,+ );+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(candidate);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const creating = manager.getUserConnection({+ serverName,+ serverConfig: config,+ user: mockUser,+ signal: controller.signal,+ requestBody: { conversationId: 'conversation-1' },+ requestScopedConnections: requestScoped ? store : undefined,+ upstreamTokenProvider: jest.fn().mockResolvedValue({ access_token: 'token' }),+ });+ const outcome = creating.catch((error: Error) => error);+ for (+ let attempt = 0;+ attempt < 20 && !(candidate.refreshToolList as jest.Mock).mock.calls.length;+ attempt+++ ) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ expect(candidate.refreshToolList).toHaveBeenCalledWith(controller.signal);+ controller.abort(new Error('request stopped'));+ finishCatalog?.();+ await expect(outcome).resolves.toMatchObject({ message: 'request stopped' });+ expect(candidate.dispose).toHaveBeenCalledTimes(1);+ expect(manager.getUserConnections(mockUser.id)?.has(serverName)).not.toBe(true);+ expect(store.connections.size).toBe(0);+ },+ );++ it.each(+ [+ { stage: 'initialize', cancelJoiner: false, mutate: false },+ { stage: 'catalog', cancelJoiner: false, mutate: false },+ { stage: 'initialize', cancelJoiner: true, mutate: false },+ { stage: 'catalog', cancelJoiner: true, mutate: false },+ { stage: 'initialize', cancelJoiner: false, mutate: true },+ { stage: 'catalog', cancelJoiner: false, mutate: true },+ ].flatMap((scenario) => ['direct', 'oauth', 'custom'].map((mode) => ({ ...scenario, mode }))),+ )(+ 'isolates a stopped $mode creation leader during $stage (cancelJoiner=$cancelJoiner, mutate=$mutate)',+ async ({ stage, cancelJoiner, mutate, mode }) => {+ const leaderAbort = new AbortController();+ const joinerAbort = new AbortController();+ const candidate = newUserConnection();+ const replacement = newUserConnection();+ let entered!: () => void;+ const started = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const waitForAbort = () =>+ new Promise<never>((_, reject) => {+ leaderAbort.signal.addEventListener('abort', () => reject(leaderAbort.signal.reason), {+ once: true,+ });+ entered();+ });+ if (stage === 'catalog') {+ (candidate.refreshToolList as jest.Mock).mockImplementationOnce(waitForAbort);+ }+ const config: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ headers: {+ Authorization:+ mode === 'direct' ? 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' : '{{MCP_API_KEY}}',+ },+ ...(mode === 'oauth' && { oauth: { client_id: 'test-client' }, requiresOAuth: true }),+ };+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(+ async (options) => options,+ );+ (MCPConnectionFactory.create as jest.Mock)+ .mockReset()+ .mockImplementationOnce((basic: t.BasicConnectionOptions) => {+ basic.directBearerRecoveryState!.attempted = mode === 'direct';+ return stage === 'initialize' ? waitForAbort() : Promise.resolve(candidate);+ })+ .mockResolvedValue(replacement);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const opts = {+ serverName,+ serverConfig: config,+ user: mockUser,+ upstreamTokenProvider: jest.fn().mockResolvedValue({ access_token: 'token' }),+ customUserVars: { MCP_API_KEY: 'custom-key' },+ flowManager: {} as Parameters<typeof manager.callTool>[0]['flowManager'],+ };+ const leader = manager.getUserConnection({ ...opts, signal: leaderAbort.signal });+ const leaderOutcome = leader.catch((error: Error) => error);+ await started;+ const joiner = manager.getUserConnection({ ...opts, signal: joinerAbort.signal });+ const joinerOutcome = joiner.catch((error: Error) => error);+ await new Promise((resolve) => setImmediate(resolve));+ if (cancelJoiner) {+ joinerAbort.abort(new Error('joiner stopped'));+ }+ if (mutate) {+ await manager.disconnectUserConnection(mockUser.id, serverName);+ }+ leaderAbort.abort(new Error('leader stopped'));+ await expect(leaderOutcome).resolves.toMatchObject({ message: 'leader stopped' });+ if (cancelJoiner || mutate) {+ await expect(joinerOutcome).resolves.toMatchObject({+ message: cancelJoiner+ ? 'joiner stopped'+ : expect.stringContaining('cancelled during teardown'),+ });+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);+ } else {+ await expect(joinerOutcome).resolves.toBe(replacement);+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(2);+ expect(MCPConnectionFactory.create).toHaveBeenLastCalledWith(+ expect.objectContaining({+ directBearerRecoveryState: expect.objectContaining({ attempted: mode === 'direct' }),+ }),+ expect.objectContaining({ signal: joinerAbort.signal }),+ );+ }+ if (stage === 'catalog') {+ expect(candidate.dispose).toHaveBeenCalledTimes(1);+ }+ },+ );++ it('honors a direct bearer recovery budget consumed during factory initialization', async () => {+ const authenticationError = Object.assign(new Error('unauthorized'), { status: 401 });+ const connection = newUserConnection();+ (connection.refreshToolList as jest.Mock).mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError,+ });+ const directBearerConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'stale-token' });+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(directBearerConfig);+ (MCPConnectionFactory.create as jest.Mock).mockImplementation(+ async (basic: t.BasicConnectionOptions) => {+ basic.directBearerRecoveryState!.attempted = true;+ return connection;+ },+ );++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await expect(+ manager.getUserConnection({+ serverName,+ user: mockUser,+ upstreamTokenProvider,+ }),+ ).rejects.toMatchObject({+ code: 'MCP_AUTHENTICATION_REJECTED',+ connectionRefreshed: false,+ } satisfies Partial<MCPAuthenticationRejectedError>);++ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(upstreamTokenProvider).not.toHaveBeenCalledWith({ forceRefresh: true });+ });++ it('fails closed when initial tools/list rejects without a live provider', async () => {+ const authenticationError = Object.assign(new Error('unauthorized'), { status: 401 });+ const connection = newUserConnection();+ (connection.refreshToolList as jest.Mock).mockResolvedValue({+ tools: [],+ complete: false,+ authenticationError,+ });+ const directBearerConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(directBearerConfig);+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(connection);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await expect(+ manager.getUserConnection({+ serverName,+ user: mockUser,+ }),+ ).rejects.toBeInstanceOf(OpenIDReauthRequiredError);++ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);+ expect(connection.dispose).toHaveBeenCalledTimes(1);+ });+it.each([false, true])('cancels and disposes a pending connection during mutation teardown (forceNew=%s)',async (forceNew) => {@@ -4687,6 +5743,142 @@ describe('MCPManager', () => {);});+ it('rechecks the request-scoped owner after a late connection replacement', async () => {+ let finishProbe: ((connected: boolean) => void) | undefined;+ const oldConnection = {+ isConnected: jest.fn().mockReturnValue(+ new Promise<boolean>((resolve) => {+ finishProbe = resolve;+ }),+ ),+ isStale: jest.fn().mockReturnValue(false),+ } as unknown as MCPConnection;+ const replacement = newUserConnection();+ const store = {+ connections: new Map([[`${mockUser.id}:${serverName}`, oldConnection]]),+ pending: new Map(),+ };+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const checkout = manager.getUserConnection({+ serverName,+ user: mockUser,+ serverConfig: {+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ headers: { 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}' },+ },+ requestBody: { conversationId: 'conversation-1' },+ requestScopedConnections: store,+ });+ await new Promise((resolve) => setImmediate(resolve));+ expect(oldConnection.isConnected).toHaveBeenCalledTimes(1);+ store.connections.set(`${mockUser.id}:${serverName}`, replacement);+ finishProbe?.(true);+ await expect(checkout).resolves.toBe(replacement);+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();+ });++ it('does not create a connection in a request-scoped store after cleanup starts', async () => {+ const bodyUrlConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://api.example.com/messages/{{LIBRECHAT_BODY_MESSAGEID}}/mcp',+ source: 'yaml',+ requiresOAuth: false,+ };+ const requestScopedConnections: t.RequestScopedMCPConnectionStore = {+ connections: new Map(),+ pending: new Map(),+ cleanupStarted: true,+ };+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });++ const manager = await MCPManager.createInstance(newMCPServersConfig());++ await expect(+ manager.getUserConnection({+ serverName,+ user: mockUser,+ serverConfig: bodyUrlConfig,+ requestBody: { messageId: 'message-1' },+ requestScopedConnections,+ }),+ ).rejects.toThrow('Request-scoped connection context is closed');+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();+ expect(requestScopedConnections.connections.size).toBe(0);+ expect(requestScopedConnections.pending.size).toBe(0);+ });++ it.each(['cleanup', 'mutation'] as const)(+ 'disposes a request-scoped connection that finishes after %s',+ async (teardown) => {+ const bodyUrlConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://api.example.com/messages/{{LIBRECHAT_BODY_MESSAGEID}}/mcp',+ source: 'yaml',+ requiresOAuth: false,+ };+ const lateConnection = {+ dispose: jest.fn().mockResolvedValue(undefined),+ isConnected: jest.fn().mockResolvedValue(true),+ on: jest.fn(),+ refreshToolList: jest.fn().mockResolvedValue(undefined),+ } as unknown as MCPConnection;+ let finishCreation: ((connection: MCPConnection) => void) | undefined;+ const creation = new Promise<MCPConnection>((resolve) => {+ finishCreation = resolve;+ });+ const requestScopedConnections: t.RequestScopedMCPConnectionStore = {+ connections: new Map(),+ pending: new Map(),+ cleanupStarted: false,+ };+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (graphUtils.preProcessGraphTokens as jest.Mock).mockImplementation(+ async (config) => config,+ );+ mockProcessMCPEnv.mockImplementation(({ options, body }) => ({+ ...options,+ ...('url' in options && {+ url: options.url?.replace('{{LIBRECHAT_BODY_MESSAGEID}}', body?.messageId ?? ''),+ }),+ }));+ (MCPConnectionFactory.create as jest.Mock).mockReturnValue(creation);+ const manager = await MCPManager.createInstance(newMCPServersConfig());++ const connectionPromise = manager.getUserConnection({+ serverName,+ user: mockUser,+ serverConfig: bodyUrlConfig,+ requestBody: { messageId: 'message-1' },+ requestScopedConnections,+ });+ for (+ let attempt = 0;+ attempt < 20 && !(MCPConnectionFactory.create as jest.Mock).mock.calls.length;+ attempt+++ ) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);+ if (teardown === 'cleanup') {+ requestScopedConnections.cleanupStarted = true;+ } else {+ await manager.disconnectUserConnection(mockUser.id, serverName);+ }+ finishCreation?.(lateConnection);++ await expect(connectionPromise).rejects.toThrow(+ teardown === 'cleanup'+ ? 'Request-scoped connection context is closed'+ : 'cancelled during teardown',+ );+ expect(lateConnection.dispose).toHaveBeenCalledTimes(1);+ expect(requestScopedConnections.connections.size).toBe(0);+ expect(requestScopedConnections.pending.size).toBe(0);+ },+ );+it('should not clear server cooldowns for ephemeral runtime connections', async () => {const bodyUrlConfig: t.ParsedServerConfig = {type: 'streamable-http',diff --git a/packages/api/src/mcp/__tests__/utils.test.ts b/packages/api/src/mcp/__tests__/utils.test.tsindex bd917ef224..4a8229c9d4 100644--- a/packages/api/src/mcp/__tests__/utils.test.ts+++ b/packages/api/src/mcp/__tests__/utils.test.ts@@ -20,6 +20,7 @@ import {isUserSourced,validateMCPServerConfig,requiresEphemeralUserConnection,+ requiresOAuthMachinery,isChatSelectableMCPServer,filterChatSelectableMCPServers,} from '~/mcp/utils';@@ -689,6 +690,44 @@ describe('isUserSourced', () => {});});+describe('requiresOAuthMachinery', () => {+ it('preserves explicit OAuth when a direct bearer placeholder is also present', () => {+ expect(+ requiresOAuthMachinery({+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ oauth: { client_id: 'explicit-client' },+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ }),+ ).toBe(true);+ });+ it('suppresses MCP OAuth for a trusted direct OpenID bearer even if inspection stamped OAuth', () => {+ expect(+ requiresOAuthMachinery({+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ requiresOAuth: true,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ }),+ ).toBe(false);+ });++ it('keeps OBO wiring when both OBO and the direct bearer placeholder are present', () => {+ expect(+ requiresOAuthMachinery({+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source: 'yaml',+ requiresOAuth: true,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ obo: { scopes: 'api://mcp/.default' },+ }),+ ).toBe(true);+ });+});+describe('requiresUserScopedConnection', () => {it('returns true for OAuth servers', () => {expect(requiresUserScopedConnection({ requiresOAuth: true })).toBe(true);diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.tsindex cd61548ec1..722952466f 100644--- a/packages/api/src/mcp/connection.ts+++ b/packages/api/src/mcp/connection.ts@@ -26,6 +26,8 @@ import type * as t from './types';import {extractSSEErrorMessage,isOAuthAuthenticationError,+ isMCPTransportAuthenticationError,+ MCPTransportAuthenticationError,isStandaloneSseConflict,} from './errors';import { createSSRFSafeUndiciConnect, isSSRFTarget, resolveHostnameSSRF } from '~/auth';@@ -992,6 +994,8 @@ interface MCPConnectionParams {useSSRFProtection?: boolean;allowedAddresses?: string[] | null;ephemeralConnection?: boolean;+ /** The owner will replace this connection after a tools/list authentication rejection. */+ directBearerRecoveryEnabled?: boolean;}/** Result of an MCP `tools/list` request: one page of tools plus an optional pagination cursor. */@@ -1000,6 +1004,8 @@ type MCPListToolsResult = Awaited<ReturnType<Client['listTools']>>;export interface MCPToolsSnapshot {tools: MCPListToolsResult['tools'];complete: boolean;+ /** Authentication rejection observed by this exact catalog read. */+ authenticationError?: unknown;/** Ordering ticket reserved before this snapshot's `tools/list`; app scope only. */publicationRevision?: string;/** Set when reserving that ticket failed, which is retryable — unlike a scope that simply@@ -1033,14 +1039,16 @@ export class MCPConnection extends EventEmitter {private readonly useSSRFProtection: boolean;private readonly allowedAddresses?: string[] | null;private readonly ephemeralConnection: boolean;+ private readonly directBearerRecoveryEnabled: boolean;private readonly proxyConfig?: MCPProxyConfig;private toolListChangeGeneration = 0;private handledToolListChangeGeneration = 0;private toolListRefreshFailures = 0;- private toolListRefreshPromise: Promise<void> | null = null;+ private toolListRefreshPromise: Promise<MCPToolsSnapshot | undefined> | null = null;private toolListRefreshRetryTimer: ReturnType<typeof setTimeout> | null = null;private toolListRefreshEpoch = 0;private toolListRefreshSuspended = false;+ private suspendedToolListSnapshot?: MCPToolsSnapshot;private publishedToolListSnapshot: {epoch: number;generation: number;@@ -1190,6 +1198,7 @@ export class MCPConnection extends EventEmitter {this.useSSRFProtection = params.useSSRFProtection === true;this.allowedAddresses = params.allowedAddresses ?? null;this.ephemeralConnection = params.ephemeralConnection === true;+ this.directBearerRecoveryEnabled = params.directBearerRecoveryEnabled === true;this.proxyConfig = getMCPProxyConfig(params.serverConfig);this.iconPath = params.serverConfig.iconPath;this.timeout = params.serverConfig.timeout;@@ -1240,6 +1249,7 @@ export class MCPConnection extends EventEmitter {/** Capture only the fields needed by the fetch closure; see factory note above. */const agents = this.agents;const logPrefix = this.getLogPrefix();+ const rejectDirectBearerAuthentication = this.directBearerRecoveryEnabled;const effectiveTimeout = timeout || DEFAULT_TIMEOUT;const requestDispatchers = new Map<string, ManagedDispatcher>();const ssrfConnects = new Map<string, ReturnType<typeof createSSRFSafeUndiciConnect>>();@@ -1355,6 +1365,13 @@ export class MCPConnection extends EventEmitter {currentAllowedAddresses,);const response = await undiciFetch(currentUrlString, currentInit);+ if (+ rejectDirectBearerAuthentication &&+ (response.status === 401 || response.status === 403)+ ) {+ await response.body?.cancel().catch(() => undefined);+ throw new MCPTransportAuthenticationError(response.status);+ }const isMethodPreservingRedirect = response.status === 307 || response.status === 308;const responseContext = {logPrefix,@@ -1587,6 +1604,21 @@ export class MCPConnection extends EventEmitter {resolvedInit?.headers,headers,);+ const liveHeaders = this.directBearerRecoveryEnabled+ ? this.getRequestHeaders()+ : undefined;+ if (liveHeaders) {+ for (const key of Object.keys(fetchHeaders)) {+ const normalized = key.toLowerCase();+ if (+ sseConfiguredSecretHeaderKeys.has(normalized) &&+ liveHeaders[normalized] != null+ ) {+ delete fetchHeaders[key];+ fetchHeaders[normalized] = liveHeaders[normalized];+ }+ }+ }return undiciFetch(urlString, {...resolvedInit,redirect: 'manual',@@ -1669,6 +1701,7 @@ export class MCPConnection extends EventEmitter {this.isInitializing = true;this.on('connectionChange', (state: t.ConnectionState) => {this.connectionState = state;+ this.suspendedToolListSnapshot = undefined;if (state === 'connected') {this.lastConnectionCheckError = undefined;const isReconnect = this.hasConnected;@@ -1814,11 +1847,17 @@ export class MCPConnection extends EventEmitter {}/** Queues a live tool-list refresh through the same coalescing path used by notifications. */- public async refreshToolList(): Promise<void> {+ public async refreshToolList(signal?: AbortSignal): Promise<MCPToolsSnapshot | undefined> {+ signal?.throwIfAborted();this.toolListChangeGeneration++;this.clearToolListRefreshRetry();- this.startToolListRefresh();- await this.toolListRefreshPromise;+ this.startToolListRefresh(signal);+ const refresh = this.toolListRefreshPromise;+ if (signal && refresh) {+ await this.settlesBefore(refresh, undefined, signal);+ signal.throwIfAborted();+ }+ return (await refresh) ?? this.suspendedToolListSnapshot;}private clearToolListRefreshRetry(): void {@@ -1849,7 +1888,7 @@ export class MCPConnection extends EventEmitter {this.toolListRefreshRetryTimer.unref?.();}- private startToolListRefresh(): void {+ private startToolListRefresh(signal?: AbortSignal): void {if (this.isDisposed ||this.toolListRefreshSuspended ||@@ -1859,7 +1898,7 @@ export class MCPConnection extends EventEmitter {return;}- this.toolListRefreshPromise = this.refreshChangedTools().finally(() => {+ this.toolListRefreshPromise = this.refreshChangedTools(signal).finally(() => {this.toolListRefreshPromise = null;if (!this.toolListRefreshRetryTimer &&@@ -1870,14 +1909,22 @@ export class MCPConnection extends EventEmitter {});}- private async refreshChangedTools(): Promise<void> {+ private async refreshChangedTools(signal?: AbortSignal): Promise<MCPToolsSnapshot | undefined> {const refreshEpoch = this.toolListRefreshEpoch;+ let latestSnapshot: MCPToolsSnapshot | undefined;while (this.handledToolListChangeGeneration < this.toolListChangeGeneration) {const targetGeneration = this.toolListChangeGeneration;const snapshot: MCPToolsSnapshot =this.client.getServerCapabilities()?.tools == null? { tools: [], complete: true, ...(await this.reserveToolsPublicationRevision()) }- : await this.fetchToolsSnapshot();+ : await this.fetchToolsSnapshot(undefined, signal);+ if (signal?.aborted) {+ if (this.toolListRefreshEpoch === refreshEpoch) {+ this.toolListRefreshSuspended = true;+ }+ return;+ }+ latestSnapshot = snapshot;if (this.toolListRefreshEpoch !== refreshEpoch ||this.toolListRefreshSuspended ||@@ -1887,6 +1934,12 @@ export class MCPConnection extends EventEmitter {}/** Publishing unordered would drop this catalog silently; retry until it can be ordered. */if (!snapshot.complete || snapshot.orderingUnavailable) {+ if (snapshot.authenticationError && this.directBearerRecoveryEnabled) {+ /** Keep the stopped queue's outcome available to an owner arriving after settlement. */+ this.suspendedToolListSnapshot = snapshot;+ this.toolListRefreshSuspended = true;+ return snapshot;+ }this.toolListRefreshFailures++;this.scheduleToolListRefreshRetry();return;@@ -1902,6 +1955,7 @@ export class MCPConnection extends EventEmitter {};this.dispatchToolsChanged(snapshot.tools, snapshot.publicationRevision);}+ return latestSnapshot;}private dispatchToolsChanged(@@ -1983,6 +2037,9 @@ export class MCPConnection extends EventEmitter {);}} catch (error) {+ if (this.isDisposed) {+ throw error;+ }// Check if it's a rate limit error - stop immediately to avoid making it worseif (this.isRateLimitError(error)) {/**@@ -2003,7 +2060,11 @@ export class MCPConnection extends EventEmitter {}// Check if it's an OAuth authentication error- if (isOAuthAuthenticationError(error)) {+ if (+ this.directBearerRecoveryEnabled+ ? isMCPTransportAuthenticationError(error)+ : isOAuthAuthenticationError(error)+ ) {logger.warn(`${this.getLogPrefix()} OAuth authentication required`);this.oauthRequired = true;const serverUrl = this.url;@@ -2263,7 +2324,11 @@ export class MCPConnection extends EventEmitter {}// Check if it's an OAuth authentication error- if (isOAuthAuthenticationError(error)) {+ if (+ this.directBearerRecoveryEnabled+ ? isMCPTransportAuthenticationError(error)+ : isOAuthAuthenticationError(error)+ ) {logger.warn(`${this.getLogPrefix()} OAuth authentication error detected`);this.lastConnectionCheckError = error;this.connectionState = 'error';@@ -2349,6 +2414,7 @@ export class MCPConnection extends EventEmitter {public async disconnect(resetCycleTracking = true, forceAgentClose = false): Promise<void> {this.toolListRefreshEpoch++;+ this.suspendedToolListSnapshot = undefined;this.toolListRefreshSuspended = true;this.clearToolListRefreshRetry();try {@@ -2438,9 +2504,10 @@ export class MCPConnection extends EventEmitter {const seenCursors = new Set<string>();let cursor: string | undefined;let totalBytes = 0;- const snapshot = (complete: boolean): MCPToolsSnapshot => ({+ const snapshot = (complete: boolean, authenticationError?: unknown): MCPToolsSnapshot => ({tools: allTools,complete,+ ...(authenticationError != null && { authenticationError }),...ordering,});@@ -2462,10 +2529,12 @@ export class MCPConnection extends EventEmitter {return snapshot(false);}- const result = await this.listToolsPage(cursor, remainingMs, signal);- if (result == null) {+ let result: MCPListToolsResult;+ try {+ result = await this.listToolsPage(cursor, remainingMs, signal);+ } catch (error) {/** Request failed mid-pagination: return the pages already fetched instead of discarding them. */- return snapshot(false);+ return snapshot(false, isMCPTransportAuthenticationError(error) ? error : undefined);}for (const tool of result.tools) {@@ -2606,6 +2675,15 @@ export class MCPConnection extends EventEmitter {};}+ if (+ startEpoch === this.toolListRefreshEpoch &&+ !signal?.aborted &&+ (deadlineMs == null || Date.now() < deadlineMs) &&+ this.suspendedToolListSnapshot+ ) {+ return this.suspendedToolListSnapshot;+ }+return { tools: [], complete: false };}@@ -2646,12 +2724,12 @@ export class MCPConnection extends EventEmitter {);}- /** Fetches a single `tools/list` page, returning null (and logging) on failure so pagination can stop gracefully. */+ /** Fetches one `tools/list` page. The public snapshot interface classifies any rejection. */private async listToolsPage(cursor: string | undefined,timeoutMs: number,signal?: AbortSignal,- ): Promise<MCPListToolsResult | null> {+ ): Promise<MCPListToolsResult> {try {return await this.client.listTools(cursor != null ? { cursor } : undefined, {timeout: timeoutMs,@@ -2660,7 +2738,7 @@ export class MCPConnection extends EventEmitter {});} catch (error) {this.emitError(error, 'Failed to fetch tools');- return null;+ throw error;}}diff --git a/packages/api/src/mcp/errors.spec.ts b/packages/api/src/mcp/errors.spec.tsnew file mode 100644index 0000000000..6c9bb13661--- /dev/null+++ b/packages/api/src/mcp/errors.spec.ts@@ -0,0 +1,26 @@+import { ErrorEvent } from 'eventsource';+import { SseError } from '@modelcontextprotocol/sdk/client/sse.js';+import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';+import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';+import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { isMCPTransportAuthenticationError, MCPTransportAuthenticationError } from './errors';++describe('direct bearer transport rejection classification', () => {+ it.each([+ new StreamableHTTPError(401, 'unauthorized'),+ new SseError(403, 'forbidden', new ErrorEvent('error')),+ new UnauthorizedError(),+ new MCPTransportAuthenticationError(401),+ ])('recognizes a structured SDK or HTTP rejection: %s', (error) => {+ expect(isMCPTransportAuthenticationError(error)).toBe(true);+ });++ it.each([+ new McpError(ErrorCode.InternalError, 'downstream HTTP 401 invalid_token'),+ new McpError(401, 'invalid_token'),+ new Error('HTTP 401 invalid_token'),+ new StreamableHTTPError(500, 'downstream HTTP 401'),+ ])('does not infer transport rejection from tool codes or messages: %s', (error) => {+ expect(isMCPTransportAuthenticationError(error)).toBe(false);+ });+});diff --git a/packages/api/src/mcp/errors.ts b/packages/api/src/mcp/errors.tsindex 3c356b3bad..0399770db4 100644--- a/packages/api/src/mcp/errors.ts+++ b/packages/api/src/mcp/errors.ts@@ -1,12 +1,17 @@/*** MCP-specific error classes*/+import { McpError } from '@modelcontextprotocol/sdk/types.js';+import { SseError } from '@modelcontextprotocol/sdk/client/sse.js';+import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';export const MCPErrorCodes = {DOMAIN_NOT_ALLOWED: 'MCP_DOMAIN_NOT_ALLOWED',INSPECTION_FAILED: 'MCP_INSPECTION_FAILED',OAUTH_SECRET_REENTRY_REQUIRED: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',+ AUTHENTICATION_REJECTED: 'MCP_AUTHENTICATION_REJECTED',+ AUTHENTICATION_REFRESH_FAILED: 'MCP_AUTHENTICATION_REFRESH_FAILED',} as const;export type MCPErrorCode = (typeof MCPErrorCodes)[keyof typeof MCPErrorCodes];@@ -18,6 +23,33 @@ interface OAuthErrorLike {message?: string;}+/** A JSON-RPC tool error is never evidence that the MCP transport rejected its bearer. */+export function isMCPTransportAuthenticationError(error: unknown): boolean {+ if (!error || typeof error !== 'object' || error instanceof McpError) {+ return false;+ }+ if (error instanceof UnauthorizedError) {+ return true;+ }+ const candidate = error as OAuthErrorLike;+ const status = candidate.status ?? candidate.statusCode;+ if (status === 401 || status === 403) {+ return true;+ }+ return (+ (error instanceof StreamableHTTPError || error instanceof SseError) &&+ (error.code === 401 || error.code === 403)+ );+}++/** Preserves the actual HTTP status before legacy SSE reduces a failed POST to plain text. */+export class MCPTransportAuthenticationError extends Error {+ constructor(public readonly status: 401 | 403) {+ super(`MCP transport rejected authentication (HTTP ${status})`);+ this.name = 'MCPTransportAuthenticationError';+ }+}+const OAUTH_HTTP_STATUS_PATTERN =/(?:\bhttp\s+(?:401|403)\b|\bnon-2\d\d\s+status\s+code\s*\((?:401|403)\)|^(?:error:\s*)?(?:401|403)\b|\bunauthorized\s*\(\s*401\s*\)|\bforbidden\s*\(\s*403\s*\))/i;const MISSING_AUTHORIZATION_PATTERN = /\bno authorization (?:headers?|values?)\b/i;@@ -281,6 +313,49 @@ export class MCPOAuthSecretReentryRequiredError extends Error {}}+/**+ * A tool invocation was rejected before LibreChat could know whether the MCP+ * server executed it. Recovery may prepare a later deliberate retry, but this+ * outcome never authorizes an automatic replay of the original call.+ */+export class MCPAuthenticationRejectedError extends Error {+ public readonly code: 'MCP_AUTHENTICATION_REJECTED' = MCPErrorCodes.AUTHENTICATION_REJECTED;+ public readonly statusCode = 403;+ public readonly retryable: boolean;++ constructor(+ public readonly serverName: string,+ public readonly connectionRefreshed: boolean,+ cause?: unknown,+ ) {+ super(+ connectionRefreshed+ ? `MCP server "${serverName}" rejected the bearer credential. The connection was refreshed; retry the tool deliberately.`+ : `MCP server "${serverName}" rejected the bearer credential. Please sign in again.`,+ );+ this.name = 'MCPAuthenticationRejectedError';+ this.retryable = connectionRefreshed;+ this.cause = cause;+ Object.setPrototypeOf(this, MCPAuthenticationRejectedError.prototype);+ }+}++/** A temporary upstream-session refresh failure, distinct from expired login state. */+export class MCPAuthenticationRefreshError extends Error {+ public readonly code: 'MCP_AUTHENTICATION_REFRESH_FAILED' =+ MCPErrorCodes.AUTHENTICATION_REFRESH_FAILED;++ public readonly statusCode = 503;+ public readonly retryable = true;++ constructor(cause?: unknown) {+ super('The OpenID session could not refresh the MCP bearer credential temporarily.');+ this.name = 'MCPAuthenticationRefreshError';+ this.cause = cause;+ Object.setPrototypeOf(this, MCPAuthenticationRefreshError.prototype);+ }+}+/*** Type guard to check if an error is an MCPDomainNotAllowedError*/diff --git a/packages/api/src/mcp/oauth/obo.ts b/packages/api/src/mcp/oauth/obo.tsindex 65d26ef9ee..41b9b5baac 100644--- a/packages/api/src/mcp/oauth/obo.ts+++ b/packages/api/src/mcp/oauth/obo.ts@@ -38,7 +38,10 @@ export type OboTokenResolver = (* - throws: refresh was attempted and the IdP rejected it. Caller wraps as* `session_refresh_failed`.*/-export type UpstreamTokenProvider = () => Promise<OIDCTokens | null>;+export type UpstreamTokenProvider = (options?: {+ forceRefresh?: boolean;+ signal?: AbortSignal;+}) => Promise<OIDCTokens | null>;export type OboTokenResolutionReason =| 'missing_upstream_token'@@ -116,7 +119,7 @@ export class OboTokenResolutionError extends Error {}}-function isRetryableOboExchangeError(error: unknown): boolean {+export function isRetryableOboExchangeError(error: unknown): boolean {const taggedRetryable = getErrorRetryableFlag(error);if (taggedRetryable != null) {return taggedRetryable;diff --git a/packages/api/src/mcp/openid.spec.ts b/packages/api/src/mcp/openid.spec.tsnew file mode 100644index 0000000000..cf0794abff--- /dev/null+++ b/packages/api/src/mcp/openid.spec.ts@@ -0,0 +1,306 @@+import type { StreamableHTTPOptions } from './types';+import { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from './openid';+import { MCPAuthenticationRefreshError } from './errors';+import { OpenIDReauthRequiredError } from '~/utils/oidc';+import { processMCPEnv } from '~/utils/env';++const directBearerConfig = (+ source: 'yaml' | 'config' | 'user' | 'plugin',+): StreamableHTTPOptions & {+ source: typeof source;+} => ({+ type: 'streamable-http',+ url: 'https://mcp.example.com',+ source,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+});++describe('direct OpenID bearer recovery', () => {+ it('forwards cancellation to live refresh and preserves the caller abort reason', async () => {+ const controller = new AbortController();+ const reason = new Error('request stopped');+ const upstreamTokenProvider = jest.fn(async () => {+ controller.abort(reason);+ throw reason;+ });+ await expect(+ resolveDirectOpenIDBearerConfig({+ config: directBearerConfig('yaml'),+ upstreamTokenProvider,+ forceRefresh: true,+ signal: controller.signal,+ }),+ ).rejects.toBe(reason);+ expect(upstreamTokenProvider).toHaveBeenCalledWith({+ forceRefresh: true,+ signal: controller.signal,+ });+ });++ it.each(['basic', 'bearer', 'custom'] as const)(+ 'gives an admin %s Authorization key precedence',+ async (authorization_type) => {+ const config = {+ ...directBearerConfig('yaml'),+ headers: { authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ apiKey: {+ source: 'admin' as const,+ key: 'operator-key',+ authorization_type,+ custom_header: 'aUtHoRiZaTiOn',+ },+ };+ const upstreamTokenProvider = jest.fn();+ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ const resolved = await resolveDirectOpenIDBearerConfig({ config, upstreamTokenProvider });+ const runtime = processMCPEnv({ options: resolved });+ expect('headers' in runtime && Object.values(runtime.headers ?? {})).toEqual([+ authorization_type === 'custom'+ ? 'operator-key'+ : `${authorization_type === 'basic' ? 'Basic' : 'Bearer'} operator-key`,+ ]);+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ },+ );++ it('keeps direct recovery when the admin key owns a separate header', () => {+ expect(+ usesDirectOpenIDBearerRecovery({+ ...directBearerConfig('yaml'),+ apiKey: {+ source: 'admin',+ key: 'key',+ authorization_type: 'custom',+ custom_header: 'X-Api-Key',+ },+ }),+ ).toBe(true);+ });++ it.each([false, true])(+ 'uses one live token in every supported field and snapshot reuse (forced=%s)',+ async (forceRefresh) => {+ const config = {+ ...directBearerConfig('yaml'),+ url: 'https://mcp.example.com/{{LIBRECHAT_OPENID_TOKEN}}/{{LIBRECHAT_BODY_CONVERSATIONID}}',+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Access-Token': '{{LIBRECHAT_OPENID_TOKEN}}',+ },+ oauth_headers: { 'X-Access-Token': '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ };+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });+ const resolved = await resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider,+ forceRefresh,+ });+ const reused = await resolveDirectOpenIDBearerConfig({+ config: {+ ...config,+ url: config.url.replace('/{{LIBRECHAT_BODY_CONVERSATIONID}}', '/new-request'),+ },+ resolvedConfig: resolved,+ upstreamTokenProvider,+ });+ expect(reused).toMatchObject({+ url: 'https://mcp.example.com/fresh-token/new-request',+ headers: { Authorization: 'Bearer fresh-token', 'X-Access-Token': 'fresh-token' },+ oauth_headers: { 'X-Access-Token': 'fresh-token' },+ });+ expect(upstreamTokenProvider).toHaveBeenCalledTimes(1);+ expect(processMCPEnv({ options: reused })).toMatchObject(reused);+ },+ );+ it.each(['yaml', 'config'] as const)('resolves a trusted %s configuration', async (source) => {+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'live-token' });++ const resolved = await resolveDirectOpenIDBearerConfig({+ config: directBearerConfig(source),+ upstreamTokenProvider,+ forceRefresh: true,+ });++ expect('headers' in resolved ? resolved.headers : undefined).toEqual({+ Authorization: 'Bearer live-token',+ });+ expect(upstreamTokenProvider).toHaveBeenCalledWith({ forceRefresh: true });+ });++ it('resolves a bearer placeholder supplied through an operator environment variable', async () => {+ const variableName = 'LIBRECHAT_TEST_DIRECT_BEARER_HEADER';+ process.env[variableName] = 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}';+ const config = {+ ...directBearerConfig('yaml'),+ headers: { Authorization: `\${${variableName}}` },+ };++ try {+ expect(usesDirectOpenIDBearerRecovery(config)).toBe(true);+ await expect(+ resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider: jest.fn().mockResolvedValue({ access_token: 'live-token' }),+ }),+ ).resolves.toMatchObject({ headers: { Authorization: 'Bearer live-token' } });+ } finally {+ delete process.env[variableName];+ }+ });++ it.each(['user', 'plugin'] as const)(+ 'does not resolve an untrusted %s configuration',+ async (source) => {+ const config = directBearerConfig(source);+ const upstreamTokenProvider = jest.fn();++ await expect(+ resolveDirectOpenIDBearerConfig({ config, upstreamTokenProvider }),+ ).resolves.toBe(config);+ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ },+ );++ it('requires explicit trusted provenance even when the placeholder is present', () => {+ const config = { ...directBearerConfig('yaml'), source: undefined };++ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ });++ it('rejects a database-backed config even if its source marker is spoofed', () => {+ const config = { ...directBearerConfig('config'), dbId: 'user-server' };++ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ });++ it('enables recovery from the trusted placeholder without a separate opt-in', () => {+ expect(usesDirectOpenIDBearerRecovery(directBearerConfig('yaml'))).toBe(true);+ });++ it('does not infer direct bearer recovery without the Authorization placeholder', () => {+ const config = {+ ...directBearerConfig('yaml'),+ headers: { Authorization: 'Bearer static-token' },+ };++ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ });++ it('lets audience-bound OBO take precedence when both modes are configured', () => {+ const config = {+ ...directBearerConfig('yaml'),+ obo: { scopes: 'api://mcp/.default' },+ };++ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ });++ it('preserves explicit OAuth and removes its shadowed OpenID template', async () => {+ const config = {+ ...directBearerConfig('yaml'),+ oauth: { client_id: 'explicit-client' },+ };+ const upstreamTokenProvider = jest.fn();+ expect(usesDirectOpenIDBearerRecovery(config)).toBe(false);+ await expect(+ resolveDirectOpenIDBearerConfig({ config, upstreamTokenProvider }),+ ).resolves.toMatchObject({ oauth: config.oauth, headers: {} });+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ });++ it('preserves direct bearer selection when OAuth is explicitly disabled', async () => {+ const config = {+ ...directBearerConfig('yaml'),+ oauth: { client_id: 'disabled-client' },+ requiresOAuth: false,+ };+ expect(usesDirectOpenIDBearerRecovery(config)).toBe(true);+ await expect(+ resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider: jest.fn().mockResolvedValue({ access_token: 'direct-token' }),+ }),+ ).resolves.toMatchObject({ headers: { Authorization: 'Bearer direct-token' } });+ });++ it('removes the shadowed OpenID Authorization template when OBO takes precedence', async () => {+ const config = {+ ...directBearerConfig('yaml'),+ obo: { scopes: 'api://mcp/.default' },+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Service': 'private-mcp',+ },+ };+ const upstreamTokenProvider = jest.fn();++ const resolved = await resolveDirectOpenIDBearerConfig({ config, upstreamTokenProvider });++ expect('headers' in resolved ? resolved.headers : undefined).toEqual({+ 'X-Service': 'private-mcp',+ });+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ });++ it('preserves the verified request bearer fallback when no session is available', async () => {+ const config = directBearerConfig('yaml');++ await expect(+ resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider: jest.fn().mockResolvedValue(null),+ }),+ ).resolves.toBe(config);+ });++ it('preserves the verified request bearer fallback when no provider is plumbed', async () => {+ const config = directBearerConfig('yaml');++ await expect(resolveDirectOpenIDBearerConfig({ config })).resolves.toBe(config);+ });++ it('requires a live provider after the upstream bearer is rejected', async () => {+ await expect(+ resolveDirectOpenIDBearerConfig({+ config: directBearerConfig('yaml'),+ forceRefresh: true,+ }),+ ).rejects.toBeInstanceOf(OpenIDReauthRequiredError);+ });++ it('returns a transport-neutral reauthentication error when forced refresh is unavailable', async () => {+ await expect(+ resolveDirectOpenIDBearerConfig({+ config: directBearerConfig('yaml'),+ upstreamTokenProvider: jest.fn().mockResolvedValue(null),+ forceRefresh: true,+ }),+ ).rejects.toBeInstanceOf(OpenIDReauthRequiredError);+ });++ it('preserves transient provider failures for the calling transport', async () => {+ const transient = Object.assign(new Error('service unavailable'), { status: 503 });++ await expect(+ resolveDirectOpenIDBearerConfig({+ config: directBearerConfig('yaml'),+ upstreamTokenProvider: jest.fn().mockRejectedValue(transient),+ }),+ ).rejects.toMatchObject({+ name: 'MCPAuthenticationRefreshError',+ cause: transient,+ } satisfies Partial<MCPAuthenticationRefreshError>);+ });++ it('substitutes opaque access tokens without interpreting replacement patterns', async () => {+ const resolved = await resolveDirectOpenIDBearerConfig({+ config: directBearerConfig('yaml'),+ upstreamTokenProvider: jest.fn().mockResolvedValue({ access_token: "opaque-$&-$`-$'" }),+ });++ expect('headers' in resolved ? resolved.headers?.Authorization : undefined).toBe(+ "Bearer opaque-$&-$`-$'",+ );+ });+});diff --git a/packages/api/src/mcp/openid.ts b/packages/api/src/mcp/openid.tsnew file mode 100644index 0000000000..60887f43ef--- /dev/null+++ b/packages/api/src/mcp/openid.ts@@ -0,0 +1,213 @@+import { extractEnvVariable } from 'librechat-data-provider';+import type { UpstreamTokenProvider } from './oauth/obo';+import type { MCPOptions } from './types';+import { isRetryableOboExchangeError } from './oauth/obo';+import { MCPAuthenticationRefreshError } from './errors';+import { OpenIDReauthRequiredError } from '~/utils/oidc';+import { isAbortError } from '~/utils/errors';++const OPENID_ACCESS_TOKEN_PATTERN = /\{\{LIBRECHAT_OPENID_(?:ACCESS_TOKEN|TOKEN)\}\}/;+const OPENID_ACCESS_TOKEN_REPLACEMENT_PATTERN = /\{\{LIBRECHAT_OPENID_(?:ACCESS_TOKEN|TOKEN)\}\}/g;+/** Request-local snapshots carry the opaque token without serializing it as new config metadata. */+const resolvedAccessTokens = new WeakMap<MCPOptions, string>();++type DirectBearerConfig = MCPOptions & {+ dbId?: string;+ source?: 'yaml' | 'config' | 'user' | 'plugin';+};++function getAuthorizationHeader(+ config: DirectBearerConfig,+): { name: string; value: string } | null {+ if (!('headers' in config) || !config.headers) {+ return null;+ }++ const entry = Object.entries(config.headers).find(+ ([name]) => name.toLowerCase() === 'authorization',+ );+ return entry ? { name: entry[0], value: entry[1] } : null;+}++/** Expands an operator-owned environment indirection before looking for the OpenID placeholder. */+function getAuthorizationTemplateValue(value: string): string {+ return extractEnvVariable(value);+}++function apiKeyOwnsAuthorization(config: DirectBearerConfig): boolean {+ const apiKey = config.apiKey;+ return !!(+ apiKey?.source === 'admin' &&+ apiKey.key &&+ (apiKey.authorization_type !== 'custom' ||+ apiKey.custom_header?.toLowerCase() === 'authorization')+ );+}++function resolveAccessTokenPlaceholders(+ config: DirectBearerConfig,+ token: string,+): DirectBearerConfig {+ const resolve = (value: string) => {+ const template = extractEnvVariable(value);+ return OPENID_ACCESS_TOKEN_PATTERN.test(template)+ ? template.replace(OPENID_ACCESS_TOKEN_REPLACEMENT_PATTERN, () => token)+ : value;+ };+ const resolveMap = (values: Record<string, string>) =>+ Object.fromEntries(Object.entries(values).map(([key, value]) => [key, resolve(value)]));+ const resolved = { ...config };+ if ('headers' in resolved && resolved.headers) {+ resolved.headers = resolveMap(resolved.headers);+ }+ if ('oauth_headers' in resolved && resolved.oauth_headers) {+ resolved.oauth_headers = resolveMap(resolved.oauth_headers);+ }+ if ('url' in resolved) {+ resolved.url = resolve(resolved.url);+ }+ if ('env' in resolved && resolved.env) {+ resolved.env = resolveMap(resolved.env);+ }+ if ('args' in resolved && resolved.args) {+ resolved.args = resolved.args.map(resolve);+ }+ if (resolved.oauth) {+ resolved.oauth = Object.fromEntries(+ Object.entries(resolved.oauth).map(([key, value]) => [+ key,+ typeof value === 'string' ? resolve(value) : value,+ ]),+ );+ }+ resolvedAccessTokens.set(resolved, token);+ return resolved;+}++/** Explicit OAuth/OBO/API keys own Authorization. Remove only the lower-priority OpenID template+ * before generic runtime expansion can demand or inject the upstream bearer directly. */+function removeShadowedOpenIDAuthorization(config: DirectBearerConfig): DirectBearerConfig {+ const authorization = getAuthorizationHeader(config);+ if (+ authorization == null ||+ !OPENID_ACCESS_TOKEN_PATTERN.test(getAuthorizationTemplateValue(authorization.value)) ||+ !('headers' in config)+ ) {+ return config;+ }++ const headers = { ...config.headers };+ delete headers[authorization.name];+ return { ...config, headers };+}++/** Whether a trusted operator config explicitly routes its OpenID bearer to this server. */+export function isDirectOpenIDBearerRecoveryEnabled(config: DirectBearerConfig): boolean {+ /** Explicit credential modes take precedence over the legacy passthrough placeholder. */+ if (+ config.obo != null ||+ apiKeyOwnsAuthorization(config) ||+ (config.oauth != null && config.requiresOAuth !== false) ||+ config.dbId != null+ ) {+ return false;+ }+ if (config.source !== 'yaml' && config.source !== 'config') {+ return false;+ }+ const authorization = getAuthorizationHeader(config);+ return (+ authorization != null &&+ OPENID_ACCESS_TOKEN_PATTERN.test(getAuthorizationTemplateValue(authorization.value))+ );+}++/** Whether a trusted direct-bearer config still needs its live placeholder resolved. */+export function usesDirectOpenIDBearerRecovery(config: DirectBearerConfig): boolean {+ return isDirectOpenIDBearerRecoveryEnabled(config);+}++/** Resolves the live bearer before a connection or request reaches the MCP transport. */+export async function resolveDirectOpenIDBearerConfig({+ config,+ upstreamTokenProvider,+ forceRefresh = false,+ resolvedConfig,+ signal,+}: {+ config: DirectBearerConfig;+ upstreamTokenProvider?: UpstreamTokenProvider;+ forceRefresh?: boolean;+ resolvedConfig?: MCPOptions;+ signal?: AbortSignal;+}): Promise<DirectBearerConfig> {+ signal?.throwIfAborted();+ if (+ config.obo != null ||+ apiKeyOwnsAuthorization(config) ||+ (config.oauth != null && config.requiresOAuth !== false)+ ) {+ return removeShadowedOpenIDAuthorization(config);+ }+ if (!usesDirectOpenIDBearerRecovery(config)) {+ return config;+ }+ const authorization = getAuthorizationHeader(config);+ const resolvedToken = resolvedConfig && resolvedAccessTokens.get(resolvedConfig);+ if (!forceRefresh && resolvedToken != null) {+ return resolveAccessTokenPlaceholders(config, resolvedToken);+ }+ const resolvedAuthorization = resolvedConfig && getAuthorizationHeader(resolvedConfig);+ if (!forceRefresh && authorization && resolvedAuthorization && 'headers' in config) {+ return {+ ...config,+ headers: { ...config.headers, [authorization.name]: resolvedAuthorization.value },+ };+ }+ if (!upstreamTokenProvider) {+ /** Keep the established `processMCPEnv` path available to API consumers that only+ * provide the verified request user. Recovery still requires a live session: once+ * the upstream rejects that bearer, a forced resolution must fail closed rather+ * than reconnecting with the same stale credential. */+ if (!forceRefresh) {+ return config;+ }+ throw new OpenIDReauthRequiredError(+ 'A live OpenID session is required to recover this MCP bearer credential.',+ );+ }++ let tokens;+ try {+ tokens = await upstreamTokenProvider({ forceRefresh, ...(signal ? { signal } : {}) });+ signal?.throwIfAborted();+ } catch (error) {+ signal?.throwIfAborted();+ if (isAbortError(error)) {+ throw error;+ }+ if (isRetryableOboExchangeError(error)) {+ throw new MCPAuthenticationRefreshError(error);+ }+ const reauthError = new OpenIDReauthRequiredError(+ 'The OpenID session could not refresh the MCP bearer credential. Please sign in again.',+ );+ reauthError.cause = error;+ throw reauthError;+ }+ if (!tokens?.access_token) {+ /** A verified bearer-authenticated request has no Express session to refresh. Its+ * strategy-populated user token remains the authoritative non-forced fallback. */+ if (!forceRefresh) {+ return config;+ }+ throw new OpenIDReauthRequiredError(+ 'The OpenID session has no usable MCP bearer credential. Please sign in again.',+ );+ }++ if (!authorization || !('headers' in config)) {+ return config;+ }+ return resolveAccessTokenPlaceholders(config, tokens.access_token);+}diff --git a/packages/api/src/mcp/registry/MCPServerInspector.ts b/packages/api/src/mcp/registry/MCPServerInspector.tsindex 76b5155a61..4d3af8fac3 100644--- a/packages/api/src/mcp/registry/MCPServerInspector.ts+++ b/packages/api/src/mcp/registry/MCPServerInspector.ts@@ -11,6 +11,7 @@ import {} from '~/mcp/utils';import { isMCPDomainAllowed, extractMCPServerDomain } from '~/auth/domain';import { normalizeJsonSchema, resolveJsonSchemaRefs } from '~/mcp/zod';+import { isDirectOpenIDBearerRecoveryEnabled } from '~/mcp/openid';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';import { MCPDomainNotAllowedError } from '~/mcp/errors';import { detectOAuthRequirement } from '~/mcp/oauth';@@ -123,6 +124,11 @@ export class MCPServerInspector {}private async detectOAuth(): Promise<void> {+ if (isDirectOpenIDBearerRecoveryEnabled(this.config)) {+ this.config.requiresOAuth = false;+ this.config.oauthMetadata = null;+ return;+ }if (this.config.requiresOAuth != null) return;if (hasRuntimeUrlPlaceholders(this.config)) return;if (this.config.url == null || this.config.startup === false) {diff --git a/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.tsindex c77b1b32e7..b311976af6 100644--- a/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts+++ b/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts@@ -81,6 +81,22 @@ describe('MCPServerInspector', () => {});});+ it('should keep trusted direct OpenID bearer configuration out of MCP OAuth detection', async () => {+ const rawConfig = {+ type: 'streamable-http' as const,+ url: 'https://api.example.com/mcp',+ source: 'yaml' as const,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.MCPOptions;++ const result = await MCPServerInspector.inspect('test_server', rawConfig, mockConnection);++ expect(result.requiresOAuth).toBe(false);+ expect(result.oauthMetadata).toBeNull();+ expect(mockDetectOAuthRequirement).not.toHaveBeenCalled();+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();+ });+it('should skip capabilities fetch when startup=false', async () => {const rawConfig: t.MCPOptions = {type: 'stdio',diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex 603dd24319..eb7c21a0ac 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -216,11 +216,22 @@ export type AddServerResult = {config: ParsedServerConfig;};+/** Mutable per-creation budget shared by every direct-bearer recovery layer. */+export interface DirectBearerRecoveryState {+ attempted: boolean;+ /** Request-local credential snapshot shared with checkout joiners and the first tool call. */+ resolvedConfig?: MCPOptions;+}+export interface BasicConnectionOptions {serverName: string;serverConfig: MCPOptions;/** Original unresolved definition retained across asynchronous credential preprocessing. */serverDefinition?: MCPOptions;+ /** Original trusted definition retained when serverConfig already contains request-resolved credentials. */+ directBearerSourceConfig?: ParsedServerConfig;+ /** Internal one-shot fence shared with the connection owner. */+ directBearerRecoveryState?: DirectBearerRecoveryState;useSSRFProtection?: boolean;allowedDomains?: string[] | null;/** Admin exemption list of host:port pairs that bypass the SSRF private-IP block */@@ -240,6 +251,8 @@ export interface UserConnectionContext {requestBody?: RequestBody;requestScopedConnections?: RequestScopedMCPConnectionStore;graphTokenResolver?: GraphTokenResolver;+ /** Live OpenID session credential source for trusted direct bearer and OBO configurations. */+ upstreamTokenProvider?: UpstreamTokenProvider;connectionTimeout?: number;/** Cancels the connection's SDK requests when the caller itself is cancelled; previously only* OAuth connections could carry a signal, leaving non-OAuth discovery uncancellable. */@@ -254,6 +267,8 @@ export interface RequestScopedMCPConnectionStore {connections: Map<string, unknown>;pending: Map<string, Promise<unknown>>;disposeConnection?: (connectionKey: string, connection: unknown) => Promise<void>;+ /** Set before cleanup snapshots pending work; new connection attempts must fail closed. */+ cleanupStarted?: boolean;}export interface OAuthStartOptions {@@ -272,7 +287,6 @@ export interface OAuthConnectionOptions extends UserConnectionContext {returnOnOAuth?: boolean;oboTokenResolver?: OboTokenResolver;oboTrustChecker?: OboTrustChecker;- upstreamTokenProvider?: UpstreamTokenProvider;oboIdentityContext?: AuthIdentityContext;}@@ -282,7 +296,11 @@ export interface UserMCPConnectionOptions extends UserConnectionContext {forceNew?: boolean;ephemeralConnection?: boolean;serverConfig?: ParsedServerConfig;+ /** Internal one-shot fence shared across connection initialization and initial tools/list. */+ directBearerRecoveryState?: DirectBearerRecoveryState;flowManager?: FlowStateManager<o.MCPOAuthTokens | null>;+ /** Request-local resolved credentials; serverConfig remains the authoritative definition. */+ directBearerResolvedConfig?: MCPOptions;tokenMethods?: TokenMethods;signal?: AbortSignal;oauthStart?: OAuthStartHandler;@@ -290,7 +308,6 @@ export interface UserMCPConnectionOptions extends UserConnectionContext {returnOnOAuth?: boolean;oboTokenResolver?: OboTokenResolver;oboTrustChecker?: OboTrustChecker;- upstreamTokenProvider?: UpstreamTokenProvider;oboIdentityContext?: AuthIdentityContext;}diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.tsindex aeb3faed47..aa8b3af0c4 100644--- a/packages/api/src/mcp/utils.ts+++ b/packages/api/src/mcp/utils.ts@@ -10,6 +10,7 @@ import {import type { AgentToolOptions } from 'librechat-data-provider';import type { ParsedServerConfig } from '~/mcp/types';import type { RequestBody } from '~/types';+import { isDirectOpenIDBearerRecoveryEnabled } from '~/mcp/openid';import { ALLOWED_BODY_FIELDS, isPluginSourced } from '~/utils/env';import { isEnabled } from '~/utils/common';@@ -264,9 +265,10 @@ export function isOAuthServer(* which omits the OBO resolver — `usesObo` then evaluates to false in the* factory and the connection sends a bare request that the upstream rejects.*/-export function requiresOAuthMachinery(- config: Pick<ParsedServerConfig, 'requiresOAuth' | 'oauth' | 'obo'>,-): boolean {+export function requiresOAuthMachinery(config: ParsedServerConfig): boolean {+ if (isDirectOpenIDBearerRecoveryEnabled(config)) {+ return false;+ }return isOAuthServer(config) || config.obo != null;}diff --git a/packages/api/src/middleware/error.spec.ts b/packages/api/src/middleware/error.spec.tsindex 99a13771f3..59e63d1009 100644--- a/packages/api/src/middleware/error.spec.ts+++ b/packages/api/src/middleware/error.spec.ts@@ -1,6 +1,7 @@import { logger, tenantStorage } from '@librechat/data-schemas';import type { Request, Response } from 'express';import type { ValidationError, MongoServerError, CustomError } from '~/types';+import { MCPAuthenticationRefreshError, MCPAuthenticationRejectedError } from '~/mcp/errors';import { ErrorController, createCustomError } from './error';import { OpenIDReauthRequiredError } from '~/utils/oidc';@@ -252,6 +253,39 @@ describe('ErrorController', () => {});});+ describe('MCPAuthenticationRejectedError handling', () => {+ it('projects rejection without triggering the app-auth 401 retry interceptor', () => {+ const error = new MCPAuthenticationRejectedError('private-mcp', true);++ ErrorController(error, mockReq, mockRes, mockNext);++ expect(mockRes.status).toHaveBeenCalledWith(403);+ expect(error.statusCode).toBe(403);+ expect(mockRes.send).toHaveBeenCalledWith({+ error: 'invalid_token',+ code: 'MCP_AUTHENTICATION_REJECTED',+ message: error.message,+ retryable: true,+ connectionRefreshed: true,+ });+ });+ });++ describe('MCPAuthenticationRefreshError handling', () => {+ it('returns a retryable service-unavailable response', () => {+ const error = new MCPAuthenticationRefreshError(new Error('identity provider unavailable'));++ ErrorController(error, mockReq, mockRes, mockNext);++ expect(mockRes.status).toHaveBeenCalledWith(503);+ expect(mockRes.send).toHaveBeenCalledWith({+ code: 'MCP_AUTHENTICATION_REFRESH_FAILED',+ message: error.message,+ retryable: true,+ });+ });+ });+describe('Unknown error handling', () => {it('should handle unknown errors', () => {const unknownError = new Error('Some unknown error');diff --git a/packages/api/src/middleware/error.ts b/packages/api/src/middleware/error.tsindex ad8afedf22..a3868bae7d 100644--- a/packages/api/src/middleware/error.ts+++ b/packages/api/src/middleware/error.ts@@ -2,6 +2,7 @@ import { ErrorTypes } from 'librechat-data-provider';import { logger, tenantStorage } from '@librechat/data-schemas';import type { NextFunction, Request, Response } from 'express';import type { MongoServerError, ValidationError, CustomError } from '~/types';+import { MCPAuthenticationRefreshError, MCPAuthenticationRejectedError } from '~/mcp/errors';import { buildTenantIsolationErrorLogContext } from './auth';import { OpenIDReauthRequiredError } from '~/utils/oidc';@@ -89,6 +90,27 @@ export const ErrorController = (return res.status(401).send({ error: 'invalid_token', message: err.message });}+ if (err instanceof MCPAuthenticationRejectedError) {+ logger.warn('MCP bearer authentication rejected: ' + err.message);+ /** A remote credential rejection must not trigger the client's app-JWT retry interceptor. */+ return res.status(err.statusCode).send({+ error: 'invalid_token',+ code: err.code,+ message: err.message,+ retryable: err.retryable,+ connectionRefreshed: err.connectionRefreshed,+ });+ }++ if (err instanceof MCPAuthenticationRefreshError) {+ logger.warn('MCP bearer refresh temporarily unavailable: ' + err.message);+ return res.status(err.statusCode).send({+ code: err.code,+ message: err.message,+ retryable: err.retryable,+ });+ }+if (isCustomError(error) && error.statusCode && error.body) {return res.status(error.statusCode).send(error.body);}diff --git a/packages/data-provider/specs/mcp.spec.ts b/packages/data-provider/specs/mcp.spec.tsindex b0e1210b3d..8f2511429a 100644--- a/packages/data-provider/specs/mcp.spec.ts+++ b/packages/data-provider/specs/mcp.spec.ts@@ -88,6 +88,16 @@ describe('MCPOptionsSchema', () => {expect(result.success).toBe(false);});});++ it('accepts the direct OpenID bearer placeholder for operator configuration', () => {+ const result = MCPOptionsSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ });++ expect(result.success).toBe(true);+ });});describe('MCP schemas', () => {