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: Ask for MCP Sign-In When a Server Rejects Refreshed Tokens (#16075)

Danny Avila03f182f9d4a5
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index 07fa1b4114..1b8be2a2dd 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -1553,6 +1553,34 @@ export class MCPConnectionFactory {
return true;
}
+ /**
+ * Whether the server rejected the tokens a silent refresh issued during this connection attempt,
+ * and they are still the stored credential. A provider can keep refreshing a grant its resource
+ * server no longer accepts, so refreshing again would repeat the rejection on every connect
+ * attempt and never ask the user to authorize. Tokens another request stored since then are not
+ * a rejected renewal; the refresh path adopts them.
+ */
+ private async isRejectedRenewal(
+ renewed: MCPOAuthTokens,
+ rejectedCredentialSetId: string | null,
+ ): Promise<boolean> {
+ if (!this.tokenMethods?.findToken) {
+ return false;
+ }
+ if ((renewed.credential_set_id ?? null) !== rejectedCredentialSetId) {
+ return false;
+ }
+ return this.runWithCapturedTenant(() =>
+ MCPTokenStorage.isCurrentAccessToken({
+ userId: this.userId!,
+ serverName: this.serverName,
+ accessToken: renewed.access_token,
+ credentialSetId: renewed.credential_set_id,
+ findToken: this.tokenMethods!.findToken!,
+ }),
+ );
+ }
+
private getOAuthReplayExpiresAt(createdAt?: number): number | undefined {
if (!createdAt) {
return undefined;
@@ -1662,6 +1690,8 @@ export class MCPConnectionFactory {
const isRequestRecovery = eventName === 'oauthReauthenticationRequired';
let recoveryPhase: OAuthRecoveryPhase = 'silent-refresh';
let eventHandling: Promise<void> | null = null;
+ /** Tokens a silent refresh issued while this connection was being established. */
+ let renewedTokens: MCPOAuthTokens | null = null;
const handleOAuthEvent = async (data: OAuthRequiredEvent) => {
logger.info(`${this.logPrefix} oauthRequired event received`);
@@ -1704,7 +1734,15 @@ export class MCPConnectionFactory {
if (!isRequestRecovery || recoveryPhase === 'silent-refresh') {
recoveryPhase = 'interactive';
- if (!data.skipSilentRefresh && this.shouldAttemptSilentTokenRefresh(data)) {
+ if (
+ !isRequestRecovery &&
+ renewedTokens != null &&
+ (await this.isRejectedRenewal(renewedTokens, rejectedCredentialSetId))
+ ) {
+ logger.info(
+ `${this.logPrefix} Server rejected the tokens a silent refresh just issued; starting interactive OAuth`,
+ );
+ } else if (!data.skipSilentRefresh && this.shouldAttemptSilentTokenRefresh(data)) {
let refreshedTokens: MCPOAuthTokens | null;
try {
refreshedTokens = await this.attemptSilentTokenRefresh(rejectedCredentialSetId);
@@ -1727,6 +1765,9 @@ export class MCPConnectionFactory {
return;
}
if (refreshedTokens) {
+ if (!isRequestRecovery) {
+ renewedTokens = refreshedTokens;
+ }
connection.setOAuthTokens(refreshedTokens);
connection.emit('oauthHandled', 'silent-refresh' satisfies t.OAuthHandledSource);
return;
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 95e17af213..07aff464b5 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
@@ -495,6 +495,53 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
}
});
+ it('starts OAuth once the resource rejects the tokens a refresh issued while connecting', async () => {
+ server = await createOAuthMCPServer({
+ issueRefreshTokens: true,
+ requireResourceParameter: true,
+ tokenScopes: ['read'],
+ scopesSupported: ['read'],
+ rejectRefreshTokens: 10,
+ });
+ const initialTokens = await issueTokens(server);
+ await storeTokens(tokenStore, server, initialTokens);
+ server.issuedTokens.delete(initialTokens.access_token);
+
+ const oauthStart = jest.fn(async (_authorizationUrl: string): Promise<void> => undefined);
+ await expect(
+ MCPConnectionFactory.create(
+ {
+ serverName: SERVER_NAME,
+ serverConfig: {
+ type: 'streamable-http',
+ url: server.url,
+ initTimeout: 15000,
+ },
+ },
+ {
+ useOAuth: true,
+ user: { id: USER_ID } as IUser,
+ flowManager: createFlowManager(),
+ tokenMethods: {
+ findToken: tokenStore.findToken,
+ createToken: tokenStore.createToken,
+ updateToken: tokenStore.updateToken,
+ deleteTokens: tokenStore.deleteTokens,
+ },
+ returnOnOAuth: true,
+ oauthStart,
+ },
+ ),
+ ).rejects.toThrow();
+
+ expect(
+ server.tokenRequests.filter((request) => request.grantType === 'refresh_token'),
+ ).toHaveLength(1);
+ expect(oauthStart).toHaveBeenCalledTimes(1);
+ const authorizationUrl = new URL(oauthStart.mock.calls[0][0]);
+ expect(authorizationUrl.searchParams.get('resource')).toBe(server.resourceUrl);
+ });
+
it('does not silently refresh an SDK insufficient_scope challenge before starting OAuth', 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 674ac4f616..787270c1dd 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -2156,6 +2156,117 @@ describe('MCPConnectionFactory', () => {
expect(oauthOptions.oauthStart).not.toHaveBeenCalled();
});
+ describe('when the server rejects the tokens a silent refresh issued', () => {
+ const renewedTokens: MCPOAuthTokens = {
+ access_token: 'renewed-access',
+ refresh_token: 'refresh123',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ credential_set_id: 'grant-1',
+ };
+ const challenge = {
+ serverUrl: 'https://api.example.com',
+ rejectedCredentialSetId: 'grant-1',
+ };
+
+ async function captureEstablishmentHandler(oauthStart: jest.Mock) {
+ let oauthRequiredHandler: ((data: Record<string, unknown>) => Promise<void>) | undefined;
+ mockConnectionInstance.on.mockImplementation((event, handler) => {
+ if (event === 'oauthRequired') {
+ oauthRequiredHandler = handler as (data: Record<string, unknown>) => Promise<void>;
+ }
+ return mockConnectionInstance;
+ });
+ mockConnectionInstance.isConnected.mockResolvedValue(false);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPTokenStorage.forceRefreshTokens.mockResolvedValue(renewedTokens);
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com',
+ flowId: 'flow123',
+ flowMetadata: {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://api.example.com',
+ state: 'random-state',
+ },
+ });
+ mockFlowManager.getFlowState.mockResolvedValue(null);
+ mockFlowManager.createFlow.mockReturnValue(new Promise(() => {}));
+
+ try {
+ await MCPConnectionFactory.create(
+ {
+ serverName: 'test-server',
+ serverConfig: {
+ ...mockServerConfig,
+ url: 'https://api.example.com',
+ type: 'sse' as const,
+ } as t.SSEOptions,
+ },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ returnOnOAuth: true,
+ oauthStart,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+ } catch {
+ // Expected: the mocked connection never reports connected
+ }
+ return oauthRequiredHandler!;
+ }
+
+ it('starts interactive OAuth instead of refreshing the rejected renewal again', async () => {
+ const oauthStart = jest.fn();
+ const handler = await captureEstablishmentHandler(oauthStart);
+
+ await handler(challenge);
+ await handler(challenge);
+
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(1);
+ expect(mockMCPTokenStorage.isCurrentAccessToken).toHaveBeenCalledWith(
+ expect.objectContaining({ accessToken: 'renewed-access', credentialSetId: 'grant-1' }),
+ );
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith('oauthHandled', 'silent-refresh');
+ expect(oauthStart).toHaveBeenCalledWith('https://auth.example.com');
+ expect(mockConnectionInstance.emit).toHaveBeenCalledWith(
+ 'oauthFailed',
+ expect.objectContaining({ message: 'OAuth flow initiated - return early' }),
+ );
+ });
+
+ it('refreshes again when another request replaced the renewal', async () => {
+ const oauthStart = jest.fn();
+ const handler = await captureEstablishmentHandler(oauthStart);
+ mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValue(false);
+
+ await handler(challenge);
+ await handler(challenge);
+
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ expect(oauthStart).not.toHaveBeenCalled();
+ });
+
+ it('refreshes a credential set the renewal did not issue', async () => {
+ const oauthStart = jest.fn();
+ const handler = await captureEstablishmentHandler(oauthStart);
+
+ await handler(challenge);
+ await handler({ ...challenge, rejectedCredentialSetId: 'grant-2' });
+
+ expect(mockMCPTokenStorage.forceRefreshTokens).toHaveBeenCalledTimes(2);
+ expect(oauthStart).not.toHaveBeenCalled();
+ });
+ });
+
it('should fall back to interactive OAuth when silent refresh throws unexpectedly', async () => {
const sseConfig = {
...mockServerConfig,