Skip to content

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

🥖 fix: Refresh MCP Credentials That Arrive Already Expired (#16111)

lia-by-librechat[bot]64f8211fcd19
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index 1b8be2a2dd..b5f3b98616 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -1023,12 +1023,65 @@ export class MCPConnectionFactory {
await this.onOAuthCredentialsAdopted?.(tokens.publication_generation);
}
+ /**
+ * Callback completion means credentials were persisted, not that their access token is still
+ * usable. Both OAuth waiters and token-flow waiters can receive that exact completed result.
+ * Re-read storage once instead of installing it or misclassifying expiry as a binding failure.
+ */
+ private async renewExpiredFlowResult(
+ tokens: MCPOAuthTokens | null,
+ ): Promise<MCPOAuthTokens | null> {
+ const expiry = tokens?.expires_at;
+ // Match storeTokens' whole-second persistence precision, including a rounded-to-zero TTL.
+ if (
+ expiry == null ||
+ !Number.isFinite(expiry) ||
+ Math.floor((expiry - Date.now()) / 1000) > 0
+ ) {
+ return tokens;
+ }
+
+ this.signal?.throwIfAborted();
+ const leaseId = getMCPOAuthLeaseId(this.userId!, this.serverName, this.tenantId);
+ try {
+ const generation = await this.flowManager!.getLeaseGeneration(leaseId);
+ const lease =
+ generation == null
+ ? null
+ : await this.flowManager!.acquireLease(leaseId, {
+ expectedGeneration: generation,
+ waitMs: Math.min(
+ this.serverConfig.oauthPersistenceWaitTimeout ?? Infinity,
+ this.getSilentRefreshTimeoutMs(),
+ ),
+ });
+ if (!lease) {
+ throw new Error('OAuth publication is not settled');
+ }
+ // A callback settles waiters while its rollback journal is still live. Cross its persistence
+ // fence before redeeming, then RELEASE it: refresh persistence acquires this same fence.
+ await lease.release();
+ } catch (error) {
+ throw new MCPTokenStorageUnavailableError(this.serverName, error);
+ }
+ this.signal?.throwIfAborted();
+ await this.invalidateGetTokensFlow();
+ const renewed = await this.loadOAuthTokens();
+ if (renewed?.expires_at != null && Math.floor((renewed.expires_at - Date.now()) / 1000) <= 0) {
+ throw new MCPTokenRefreshUnavailableError(
+ this.serverName,
+ new Error('Refreshed access token has no usable lifetime'),
+ );
+ }
+ return renewed;
+ }
+
/** Retrieves existing OAuth tokens from storage or returns null */
protected async getOAuthTokens(): Promise<MCPOAuthTokens | null> {
if (!this.tokenMethods?.findToken) return null;
try {
- const tokens = await this.loadOAuthTokens();
+ const tokens = await this.renewExpiredFlowResult(await this.loadOAuthTokens());
if (tokens) {
const [isCurrentAccessToken, storedClient] = await this.runWithCapturedTenant(() =>
@@ -1073,6 +1126,9 @@ export class MCPConnectionFactory {
}
return tokens;
} catch (error) {
+ if (this.signal?.aborted) {
+ throw error;
+ }
if (MCPConnectionFactory.isReauthenticationRequired(error)) {
logger.info(`${this.logPrefix} Reauthentication required; triggering OAuth flow`);
return null;
@@ -1927,8 +1983,18 @@ export class MCPConnectionFactory {
const result = await this.handleOAuthRequired(oauthLeaseGeneration);
if (result?.tokens) {
- const { tokens } = result;
try {
+ if (
+ !this.tokenMethods?.findToken ||
+ typeof result.tokens.credential_set_id !== 'string' ||
+ !result.tokens.credential_set_id
+ ) {
+ throw new ReauthenticationRequiredError(this.serverName, 'binding');
+ }
+ const tokens = await this.renewExpiredFlowResult(result.tokens);
+ if (!tokens) {
+ throw new ReauthenticationRequiredError(this.serverName, 'expired');
+ }
if (
!this.tokenMethods?.findToken ||
typeof tokens.credential_set_id !== 'string' ||
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
index 07aff464b5..180d4ae4ae 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
@@ -5,12 +5,15 @@ import type {
OAuthStoredClientMetadata,
MCPOAuthTokens,
} from '~/mcp/oauth';
+import type { MCPOAuthFlowMetadata } from '~/mcp/oauth';
+import type * as t from '~/mcp/types';
import {
MockKeyv,
InMemoryTokenStore,
createOAuthMCPServer,
type OAuthTestServer,
} from './helpers/oauthTestServer';
+import { persistMCPAuthorizationTransaction } from '~/mcp/authorization';
import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';
import { MCPTokenStorage, MCPOAuthHandler } from '~/mcp/oauth';
@@ -53,6 +56,16 @@ jest.mock('~/mcp/mcpConfig', () => ({
},
}));
+class TokenLoadingFactory extends MCPConnectionFactory {
+ public constructor(basic: t.BasicConnectionOptions, options: t.OAuthConnectionOptions) {
+ super(basic, options);
+ }
+
+ public loadTokens() {
+ return this.getOAuthTokens();
+ }
+}
+
const SERVER_NAME = 'sdk-oauth-server';
const USER_ID = 'sdk-user';
const CLIENT_ID = 'librechat-sdk-test-client';
@@ -187,6 +200,119 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
jest.clearAllMocks();
});
+ it('refreshes an expired callback for the active connection and token waiter after publication settles', async () => {
+ server = await createOAuthMCPServer({
+ issueRefreshTokens: true,
+ rotateRefreshTokens: true,
+ requireResourceParameter: true,
+ });
+ const flowManager = new FlowStateManager<MCPOAuthTokens>(
+ new MockKeyv<MCPOAuthTokens>() as unknown as Keyv,
+ { ttl: 30000, ci: true },
+ );
+ const tokenMethods = {
+ findToken: tokenStore.findToken,
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ deleteTokens: tokenStore.deleteTokens,
+ };
+ const basic = {
+ serverName: SERVER_NAME,
+ serverConfig: {
+ type: 'streamable-http' as const,
+ url: server.url,
+ initTimeout: 15000,
+ requiresOAuth: true,
+ oauthRefreshCoordination: true,
+ },
+ };
+ const options = {
+ useOAuth: true as const,
+ user: { id: USER_ID } as IUser,
+ flowManager,
+ tokenMethods,
+ };
+ let waitingTokens: Promise<MCPOAuthTokens | null> | undefined;
+ let published = false;
+ let waiterReachedFence = false;
+ const acquireLease = flowManager.acquireLease.bind(flowManager);
+ jest.spyOn(flowManager, 'acquireLease').mockImplementation((...args) => {
+ if (published) waiterReachedFence = true;
+ return acquireLease(...args);
+ });
+ const oauthStart = jest.fn(async (authorizationUrl: string) => {
+ // Follow the actual authorization URL (including PKCE), then use the same exchange and
+ // persistence transaction as the callback route. Only the elapsed lifetime is injected.
+ const response = await fetch(authorizationUrl, { redirect: 'manual' });
+ const code = new URL(response.headers.get('location')!).searchParams.get('code')!;
+ const flowId = MCPOAuthHandler.generateFlowId(USER_ID, SERVER_NAME);
+ const state = await flowManager.getFlowState(flowId, 'mcp_oauth');
+ const metadata = state!.metadata as MCPOAuthFlowMetadata;
+ const tokenFlowId = MCPOAuthHandler.generateTokenFlowId(USER_ID, SERVER_NAME);
+ await flowManager.initFlow(tokenFlowId, 'mcp_get_tokens');
+ waitingTokens = new TokenLoadingFactory(basic, options).loadTokens();
+ void waitingTokens.catch(() => undefined);
+
+ await MCPOAuthHandler.completeOAuthFlow(
+ flowId,
+ code,
+ flowManager,
+ {},
+ async (exchanged, completeAuthorization) => {
+ server.issuedTokens.delete(exchanged.access_token);
+ return persistMCPAuthorizationTransaction<MCPOAuthTokens>(
+ {
+ scope: { userId: USER_ID, serverName: SERVER_NAME },
+ flowIds: [flowId, MCPOAuthHandler.generateTokenFlowId(USER_ID, SERVER_NAME)],
+ tokens: { ...exchanged, expires_at: Date.now() - 1000 },
+ completeAuthorization: completeAuthorization!,
+ persistTokens: (tokens, onStoreCommitted) =>
+ MCPTokenStorage.storeTokens({
+ ...tokenMethods,
+ flowManager,
+ userId: USER_ID,
+ serverName: SERVER_NAME,
+ tokens,
+ clientInfo: metadata.clientInfo,
+ metadata: MCPOAuthHandler.buildStoredClientMetadata(
+ metadata.metadata,
+ metadata.resourceMetadata,
+ metadata.serverUrl,
+ metadata.clientSource,
+ ),
+ onStoreCommitted: async (stored) => {
+ await onStoreCommitted(stored);
+ published = true;
+ // Completion wakes the token waiter before storeTokens releases its lease.
+ // It must not consume the refresh token while rollback is still possible.
+ await waitFor(() => waiterReachedFence);
+ expect(
+ server.tokenRequests.filter((r) => r.grantType === 'refresh_token'),
+ ).toHaveLength(0);
+ },
+ }),
+ },
+ {
+ ensureServerActive: async () => true,
+ inactiveServerError: () => new Error('Server deleted'),
+ invalidateRecoveryGeneration: async () => 'callback-publication',
+ flowManager,
+ retryDelaysMs: [0],
+ },
+ );
+ },
+ );
+ });
+ connection = await MCPConnectionFactory.create(basic, { ...options, oauthStart });
+ const loaded = await waitingTokens;
+ expect(loaded).not.toBeNull();
+ expect(server.issuedTokens.has(loaded!.access_token)).toBe(true);
+ expect(await connection.isConnected()).toBe(true);
+ expect((await connection.fetchTools()).some((tool) => tool.name === 'echo')).toBe(true);
+ expect(oauthStart).toHaveBeenCalledTimes(1);
+ expect(server.tokenRequests.filter((r) => r.grantType === 'refresh_token')).toHaveLength(1);
+ });
+
it('silently refreshes a server-rejected token and reconnects with the MCP resource parameter', async () => {
server = await createOAuthMCPServer({
issueRefreshTokens: true,
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
index 787270c1dd..652d71b2a5 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -227,6 +227,99 @@ describe('MCPConnectionFactory', () => {
(getTenantId as jest.Mock).mockReturnValue(undefined);
});
+ describe('Expired flow result recovery', () => {
+ const expired = (): MCPOAuthTokens => ({
+ access_token: 'expired-callback',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ expires_at: Date.now() - 1000,
+ credential_set_id: 'persisted-generation',
+ });
+ const factory = (signal?: AbortSignal) =>
+ new InspectableMCPConnectionFactory(
+ {
+ serverName: 'test-server',
+ serverConfig: { type: 'sse', url: 'https://api.example.com' },
+ },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ signal,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+
+ it.each(['getLeaseGeneration', 'acquireLease'] as const)(
+ 'does not turn a %s outage into missing authorization',
+ async (operation) => {
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(expired());
+ mockFlowManager[operation].mockRejectedValue(new Error('Redis unavailable'));
+ await expect(factory().getOAuthTokensForTest()).rejects.toMatchObject({
+ name: 'MCPTokenStorageUnavailableError',
+ });
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ },
+ );
+
+ it('defers when teardown supersedes the publication fence', async () => {
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(expired());
+ mockFlowManager.acquireLease.mockResolvedValue(null);
+ await expect(factory().getOAuthTokensForTest()).rejects.toMatchObject({
+ name: 'MCPTokenStorageUnavailableError',
+ });
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves transient refresh failure instead of prompting again', async () => {
+ const failure = Object.assign(new Error('Provider unavailable'), {
+ name: 'MCPTokenRefreshUnavailableError',
+ });
+ mockFlowManager.createFlowWithHandler
+ .mockResolvedValueOnce(expired())
+ .mockRejectedValueOnce(failure);
+ await expect(factory().getOAuthTokensForTest()).rejects.toBe(failure);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ });
+
+ it('does not loop when the refreshed result is also expired', async () => {
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(expired());
+ await expect(factory().getOAuthTokensForTest()).rejects.toMatchObject({
+ name: 'MCPTokenRefreshUnavailableError',
+ });
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(2);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ });
+
+ it('releases the publication fence without redeeming after caller cancellation', async () => {
+ const controller = new AbortController();
+ const cancelled = new Error('Caller stopped');
+ const release = jest.fn(async () => {
+ controller.abort(cancelled);
+ });
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(expired());
+ mockFlowManager.acquireLease.mockResolvedValue({ generation: 0, release });
+ await expect(factory(controller.signal).getOAuthTokensForTest()).rejects.toBe(cancelled);
+ expect(release).toHaveBeenCalledTimes(1);
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ });
+
+ it('does not add a fence or another read to usable flow results', async () => {
+ const current = { ...expired(), expires_at: Date.now() + 60000 };
+ mockFlowManager.createFlowWithHandler.mockResolvedValue(current);
+ await expect(factory().getOAuthTokensForTest()).resolves.toEqual(current);
+ expect(mockFlowManager.acquireLease).not.toHaveBeenCalled();
+ expect(mockFlowManager.createFlowWithHandler).toHaveBeenCalledTimes(1);
+ });
+ });
+
it('cancels pending retry backoff when the connection deadline expires', async () => {
jest.useFakeTimers();
try {
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
index 6d6920a32e..375cae3fc5 100644
--- a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts
@@ -12,6 +12,7 @@
*/
import { Keyv } from 'keyv';
+import jwt from 'jsonwebtoken';
import { logger } from '@librechat/data-schemas';
import type { IUser } from '@librechat/data-schemas';
import type { OAuthTestServer } from './helpers/oauthTestServer';
@@ -76,6 +77,250 @@ async function seedStoredClient(tokenStore: InMemoryTokenStore, serverUrl: strin
});
}
+describe('Persisted access-token expiry', () => {
+ const ONE_YEAR_SECONDS = 365 * 24 * 60 * 60;
+
+ /** Stores one provider response and reports the lifetime the access record actually carries. */
+ async function persistedLifetimeSeconds(
+ tokens: Record<string, unknown>,
+ updateExisting = false,
+ ): Promise<number> {
+ const tokenStore = new InMemoryTokenStore();
+ if (updateExisting) {
+ await tokenStore.createToken({
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:test-srv',
+ token: 'enc:previous-token',
+ expiresIn: 3600,
+ metadata: tokenMetadata,
+ });
+ }
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'test-srv',
+ tokens: tokens as never,
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ findToken: tokenStore.findToken,
+ clientInfo: { client_id: 'test-client' },
+ metadata: bindingMetadata('https://mcp.example.com/'),
+ });
+ const stored = await tokenStore.findToken({
+ userId: 'u1',
+ type: 'mcp_oauth',
+ identifier: 'mcp:test-srv',
+ });
+ return Math.round((stored!.expiresAt.getTime() - Date.now()) / 1000);
+ }
+
+ it.each([{ expires_in: 0 }, { expires_at: 0 }])(
+ 'preserves an explicitly zero lifetime: %j',
+ async (expiry) => {
+ await expect(
+ persistedLifetimeSeconds({
+ access_token: 'opaque-zero-lifetime',
+ token_type: 'Bearer',
+ ...expiry,
+ }),
+ ).resolves.toBeLessThanOrEqual(0);
+ },
+ );
+
+ it('updates an existing access record to expire immediately for expires_in zero', async () => {
+ await expect(
+ persistedLifetimeSeconds(
+ {
+ access_token: 'replacement',
+ token_type: 'Bearer',
+ expires_in: 0,
+ },
+ true,
+ ),
+ ).resolves.toBeLessThanOrEqual(0);
+ });
+
+ it.each([NaN, Infinity])(
+ 'ignores non-finite expires_at %s in favor of a finite lifetime',
+ async (expires_at) => {
+ await expect(
+ persistedLifetimeSeconds({
+ access_token: 'opaque',
+ token_type: 'Bearer',
+ expires_at,
+ expires_in: 3600,
+ }),
+ ).resolves.toBe(3600);
+ },
+ );
+
+ it('keeps a disclosed lifetime', async () => {
+ await expect(
+ persistedLifetimeSeconds({
+ access_token: 'opaque-access-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ refresh_token: 'r1',
+ obtained_at: Date.now(),
+ }),
+ ).resolves.toBe(3600);
+ });
+
+ /**
+ * A lifetime that has already elapsed must not be recorded as a year of validity: `getTokens`
+ * decides to refresh from this record, so a dead credential stored as valid is only discovered
+ * when the resource server rejects a request.
+ */
+ it('records a credential that arrived expired as expired', async () => {
+ const lifetime = await persistedLifetimeSeconds({
+ access_token: 'expired-access-token',
+ token_type: 'Bearer',
+ expires_at: Date.now() - 60_000,
+ refresh_token: 'r1',
+ obtained_at: Date.now(),
+ });
+ expect(lifetime).toBeLessThanOrEqual(0);
+ expect(lifetime).not.toBe(ONE_YEAR_SECONDS);
+ });
+
+ it('does not round a sub-second remaining lifetime up to a year', async () => {
+ const lifetime = await persistedLifetimeSeconds({
+ access_token: 'nearly-expired-access-token',
+ token_type: 'Bearer',
+ expires_at: Date.now() + 900,
+ refresh_token: 'r1',
+ obtained_at: Date.now(),
+ });
+ expect(lifetime).toBeLessThanOrEqual(1);
+ expect(lifetime).not.toBe(ONE_YEAR_SECONDS);
+ });
+
+ /**
+ * A JWT `exp` comes from the provider's clock, so skew can make a live credential look expired.
+ * That case keeps its existing leniency (`tokens.test.ts`) and is deliberately not changed here.
+ */
+ it('keeps the default for a past JWT exp, which may be clock skew', async () => {
+ const expiredJwt = jwt.sign(
+ { sub: 'u1', exp: Math.floor(Date.now() / 1000) - 60 },
+ 'test-secret',
+ );
+ await expect(
+ persistedLifetimeSeconds({
+ access_token: expiredJwt,
+ token_type: 'Bearer',
+ refresh_token: 'r1',
+ obtained_at: Date.now(),
+ }),
+ ).resolves.toBe(ONE_YEAR_SECONDS);
+ });
+
+ /** RFC 6749 §5.1 makes `expires_in` only RECOMMENDED, so an unknown lifetime keeps its default. */
+ it('keeps the long default when no lifetime is knowable', async () => {
+ await expect(
+ persistedLifetimeSeconds({
+ access_token: 'opaque-access-token-without-expiry',
+ token_type: 'Bearer',
+ refresh_token: 'r1',
+ obtained_at: Date.now(),
+ }),
+ ).resolves.toBe(ONE_YEAR_SECONDS);
+ });
+});
+
+describe('A credential persisted with an elapsed lifetime', () => {
+ let server: OAuthTestServer;
+ let tokenStore: InMemoryTokenStore;
+
+ beforeEach(async () => {
+ server = await createOAuthMCPServer({
+ tokenTTLMs: 60000,
+ issueRefreshTokens: true,
+ rotateRefreshTokens: true,
+ });
+ tokenStore = new InMemoryTokenStore();
+ });
+
+ afterEach(async () => {
+ await server.close();
+ });
+
+ /**
+ * The stored-credential read is the only path that can recover before a request fails, so a
+ * response whose lifetime already elapsed has to refresh here rather than reach a transport,
+ * get rejected, and risk an interactive prompt for a grant that is still renewable.
+ */
+ it('refreshes on the next read instead of requiring re-authentication', async () => {
+ const code = await server.getAuthCode();
+ const tokenRes = await fetch(`${server.url}token`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: `grant_type=authorization_code&code=${code}`,
+ });
+ const initial = (await tokenRes.json()) as { access_token: string; refresh_token: string };
+
+ await MCPTokenStorage.storeTokens({
+ userId: 'u1',
+ serverName: 'test-srv',
+ tokens: { ...initial, token_type: 'Bearer', obtained_at: Date.now(), expires_at: Date.now() },
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ findToken: tokenStore.findToken,
+ clientInfo: { client_id: 'test-client' },
+ metadata: bindingMetadata(server.url),
+ });
+
+ const result = await MCPTokenStorage.getTokens({
+ userId: 'u1',
+ serverName: 'test-srv',
+ findToken: tokenStore.findToken,
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ refreshTokens: async (refreshToken) => {
+ const res = await fetch(`${server.url}token`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: `grant_type=refresh_token&refresh_token=${refreshToken}`,
+ });
+ if (!res.ok) {
+ throw new Error(`Refresh failed: ${res.status}`);
+ }
+ const data = (await res.json()) as MCPOAuthTokens & { expires_in: number };
+ return {
+ ...data,
+ obtained_at: Date.now(),
+ expires_at: Date.now() + data.expires_in * 1000,
+ };
+ },
+ });
+
+ expect(result).not.toBeNull();
+ expect(result!.access_token).not.toBe(initial.access_token);
+ expect(
+ server.tokenRequests.filter(({ grantType }) => grantType === 'refresh_token'),
+ ).toHaveLength(1);
+
+ const mcpRes = await fetch(server.url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ Authorization: `Bearer ${result!.access_token}`,
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ method: 'initialize',
+ id: 1,
+ params: {
+ protocolVersion: '2025-03-26',
+ capabilities: {},
+ clientInfo: { name: 'test', version: '0.0.1' },
+ },
+ }),
+ });
+ expect(mcpRes.status).toBe(200);
+ });
+});
+
describe('MCP OAuth Token Expiry Scenarios', () => {
afterEach(() => {
jest.clearAllMocks();
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.ts
index 2b7aa4d6eb..b2ab3c4364 100644
--- a/packages/api/src/mcp/__tests__/handler.test.ts
+++ b/packages/api/src/mcp/__tests__/handler.test.ts
@@ -1759,6 +1759,41 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
);
});
+ it('normalizes a zero exchange lifetime before persistence', async () => {
+ const flowManager = {
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: 123,
+ metadata: {
+ serverName: 'test-server',
+ codeVerifier: 'verifier',
+ clientInfo: {},
+ metadata: {},
+ },
+ }),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
+ } as unknown as FlowStateManager<MCPOAuthTokens>;
+ mockExchangeAuthorization.mockResolvedValue({
+ access_token: 'expired-token',
+ token_type: 'Bearer',
+ expires_in: 0,
+ });
+ const persist = jest.fn(async (tokens: MCPOAuthTokens) => tokens);
+ const result = await MCPOAuthHandler.completeOAuthFlow(
+ 'flow',
+ 'code',
+ flowManager,
+ {},
+ persist,
+ );
+ expect(result.expires_at).toEqual(expect.any(Number));
+ expect(result.expires_at).toBeLessThanOrEqual(Date.now());
+ expect(persist).toHaveBeenCalledWith(
+ expect.objectContaining({ expires_in: 0, expires_at: result.expires_at }),
+ expect.any(Function),
+ );
+ });
+
it('persists exchanged tokens before completing and waking the OAuth flow', async () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
diff --git a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
index 22f10f4016..422fda3911 100644
--- a/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
+++ b/packages/api/src/mcp/__tests__/helpers/oauthTestServer.ts
@@ -634,7 +634,9 @@ export class InMemoryTokenStore {
token: data.token ?? existing.token,
expiresAt:
data.expiresAt ??
- (data.expiresIn ? new Date(Date.now() + expiresIn * 1000) : existing.expiresAt),
+ (data.expiresIn !== undefined
+ ? new Date(Date.now() + expiresIn * 1000)
+ : existing.expiresAt),
metadata: data.metadata ?? existing.metadata,
};
this.tokens.set(existingKey, updated);
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index 3d8d61de66..6dcf8a5653 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -1353,7 +1353,10 @@ export class MCPOAuthHandler {
...tokens,
credential_set_id: randomBytes(16).toString('hex'),
obtained_at: Date.now(),
- expires_at: tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined,
+ expires_at:
+ typeof tokens.expires_in === 'number' && Number.isFinite(tokens.expires_in)
+ ? Date.now() + tokens.expires_in * 1000
+ : undefined,
};
/**
@@ -1711,7 +1714,9 @@ export class MCPOAuthHandler {
...tokens,
obtained_at: Date.now(),
expires_at:
- typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : undefined,
+ typeof tokens.expires_in === 'number' && Number.isFinite(tokens.expires_in)
+ ? Date.now() + tokens.expires_in * 1000
+ : undefined,
} as MCPOAuthTokens;
}
diff --git a/packages/api/src/mcp/oauth/tokens.ts b/packages/api/src/mcp/oauth/tokens.ts
index 3f246f4ded..be0fbf6357 100644
--- a/packages/api/src/mcp/oauth/tokens.ts
+++ b/packages/api/src/mcp/oauth/tokens.ts
@@ -726,12 +726,18 @@ export class MCPTokenStorage {
let accessTokenExpiry: Date;
let expiresInSeconds: number;
- if ('expires_at' in tokens && tokens.expires_at) {
+ // Zero is a stated lifetime, not an omitted one. Only unknown/invalid lifetimes
+ // use the default; never turn an elapsed known lifetime into a year of validity.
+ if (
+ 'expires_at' in tokens &&
+ typeof tokens.expires_at === 'number' &&
+ Number.isFinite(tokens.expires_at)
+ ) {
/** MCPOAuthTokens format - already has calculated expiry */
logger.debug(`${logPrefix} Using expires_at: ${tokens.expires_at}`);
accessTokenExpiry = new Date(tokens.expires_at);
expiresInSeconds = Math.floor((accessTokenExpiry.getTime() - Date.now()) / 1000);
- } else if (tokens.expires_in) {
+ } else if (typeof tokens.expires_in === 'number' && Number.isFinite(tokens.expires_in)) {
/** Standard OAuthTokens format - use expires_in directly to avoid lossy Date round-trip */
logger.debug(`${logPrefix} Using expires_in: ${tokens.expires_in}`);
expiresInSeconds = tokens.expires_in;
@@ -756,20 +762,26 @@ export class MCPTokenStorage {
}
}
- logger.debug(`${logPrefix} Calculated expiry date: ${accessTokenExpiry.toISOString()}`);
-
if (isNaN(accessTokenExpiry.getTime())) {
logger.error(`${logPrefix} Invalid expiry date calculated, using default`);
accessTokenExpiry = new Date(Date.now() + defaultTTL * 1000);
expiresInSeconds = defaultTTL;
}
+ logger.debug(`${logPrefix} Calculated expiry date: ${accessTokenExpiry.toISOString()}`);
+
+ if (expiresInSeconds <= 0) {
+ logger.info(
+ `${logPrefix} Stored access token is already expired (expires_at: ${accessTokenExpiry.toISOString()}); the next read refreshes it`,
+ );
+ }
+
const accessTokenData = {
userId,
type: 'mcp_oauth',
identifier,
token: encryptedAccessToken,
- expiresIn: expiresInSeconds > 0 ? expiresInSeconds : defaultTTL,
+ expiresIn: expiresInSeconds,
metadata: tokenMetadata,
};