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: Keep the MCP OAuth Prompt Open While a Stale Status Says Connected (#16569)
Danny Avila89e15674b040
diff --git a/client/src/hooks/MCP/__tests__/polling.spec.ts b/client/src/hooks/MCP/__tests__/polling.spec.tsindex f4e6a931c7..9a82863d7e 100644--- a/client/src/hooks/MCP/__tests__/polling.spec.ts+++ b/client/src/hooks/MCP/__tests__/polling.spec.ts@@ -1,4 +1,5 @@import {+ applyPendingOAuthState,applyMCPDiscoveryAuthorizationState,getMCPOAuthTimeout,getMCPOAuthPollingOutcome,@@ -124,6 +125,64 @@ describe('applyMCPDiscoveryAuthorizationState', () => {});});+describe('applyPendingOAuthState', () => {+ const durableStatus = {+ oauth: {+ requiresOAuth: true,+ connectionState: 'connected' as const,+ authorizationState: 'authorized' as const,+ authorizationGeneration: 'generation-1',+ },+ };++ it('reports a server this browser is authorizing as connecting over a cached connection', () => {+ const result = applyPendingOAuthState(durableStatus, {+ oauth: { oauthUrl: 'https://auth.example.test/authorize' },+ });++ expect(result?.oauth).toEqual({+ requiresOAuth: true,+ connectionState: 'connecting',+ authorizationState: 'authorizing',+ authorizationGeneration: 'generation-1',+ });+ expect(durableStatus.oauth.connectionState).toBe('connected');+ });++ it('adds a connecting entry before the status query has loaded', () => {+ const result = applyPendingOAuthState(undefined, {+ oauth: { oauthUrl: 'https://auth.example.test/authorize' },+ });++ expect(result).toEqual({+ oauth: {+ requiresOAuth: true,+ connectionState: 'connecting',+ authorizationState: 'authorizing',+ },+ });+ });++ it('leaves status untouched once the flow ends or when it already reports the flow', () => {+ const connecting = {+ oauth: {+ requiresOAuth: true,+ connectionState: 'connecting' as const,+ authorizationState: 'authorizing' as const,+ },+ };++ expect(applyPendingOAuthState(durableStatus, { oauth: { oauthUrl: null } })).toBe(+ durableStatus,+ );+ expect(+ applyPendingOAuthState(connecting, {+ oauth: { oauthUrl: 'https://auth.example.test/authorize' },+ }),+ ).toBe(connecting);+ });+});+describe('getMCPOAuthTimeout', () => {it('preserves the remaining timeout of a reused flow over the global server window', () => {expect(getMCPOAuthTimeout(45_000, 600_000)).toBe(45_000);diff --git a/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx b/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsxindex 34a3b2b47c..5310c24d15 100644--- a/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx+++ b/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.tsx@@ -3,7 +3,7 @@ import { Provider } from 'jotai';import { QueryKeys } from 'librechat-data-provider';import { act, renderHook, waitFor } from '@testing-library/react';import { QueryClient, QueryClientProvider, QueryObserver } from '@tanstack/react-query';-import type { MCPReinitializeResponse } from 'librechat-data-provider';+import type { MCPServersResponse, MCPReinitializeResponse } from 'librechat-data-provider';import { useMCPServerManager } from '../useMCPServerManager';const mockOpenInNewTab = jest.fn();@@ -12,7 +12,9 @@ jest.mock('~/utils', () => ({ openInNewTab: (...args: unknown[]) => mockOpenInNeconst mockShowToast = jest.fn();const mockSetMCPValues = jest.fn();const mockReinitialize = jest.fn();-const mockUseMCPToolsQuery = jest.fn((_options?: unknown) => ({ data: undefined }));+const mockUseMCPToolsQuery = jest.fn((_options?: unknown): { data?: MCPServersResponse } => ({+ data: undefined,+}));const mockUseMCPConnectionStatus = jest.fn((_options?: unknown) => ({ connectionStatus: {} }));jest.mock('@librechat/client', () => ({@@ -204,4 +206,77 @@ describe('useMCPServerManager initialization', () => {}},);++ it('keeps a server this browser is authorizing connecting when rediscovery outdates a cached connection', async () => {+ jest.useFakeTimers();+ const serverName = 'clickhouse';+ /** Stored tokens the server rejects: status reports a durable connection, discovery a reauth. */+ const connectionStatus = {+ [serverName]: {+ requiresOAuth: true,+ connectionState: 'connected',+ authorizationState: 'authorized',+ authorizationGeneration: 'generation-1',+ },+ };+ const catalog = (authorizationGeneration: string) => ({+ data: {+ servers: {+ [serverName]: {+ name: serverName,+ icon: '',+ authenticated: false,+ authorizationState: 'reauth_required' as const,+ authorizationGeneration,+ authConfig: [],+ tools: [],+ },+ },+ },+ });+ mockUseMCPConnectionStatus.mockImplementation(() => ({ connectionStatus }));+ mockUseMCPToolsQuery.mockImplementation(() => catalog('generation-1'));+ mockReinitialize.mockReset();+ mockReinitialize.mockResolvedValueOnce({+ success: true,+ serverName,+ oauthRequired: true,+ oauthUrl: 'https://auth.example.test/authorize',+ flowId: `user:${serverName}`,+ });+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <Provider>+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ </Provider>+ );+ const { result, rerender, unmount } = renderHook(() => useMCPServerManager(), { wrapper });++ try {+ expect(result.current.connectionStatus?.[serverName]?.connectionState).toBe('disconnected');++ await act(async () => {+ await result.current.initializeServer(serverName, false);+ });+ /** Reinitialize refetches the catalog, which reports a newer generation than cached status. */+ mockUseMCPToolsQuery.mockImplementation(() => catalog('generation-2'));+ rerender();++ expect(result.current.connectionStatus?.[serverName]).toMatchObject({+ connectionState: 'connecting',+ authorizationState: 'authorizing',+ });+ expect(result.current.getServerStatusIconProps(serverName)).toMatchObject({+ isInitializing: true,+ canCancel: true,+ });+ } finally {+ unmount();+ queryClient.clear();+ jest.clearAllTimers();+ jest.useRealTimers();+ mockUseMCPConnectionStatus.mockImplementation(() => ({ connectionStatus: {} }));+ mockUseMCPToolsQuery.mockImplementation(() => ({ data: undefined }));+ }+ });});diff --git a/client/src/hooks/MCP/polling.ts b/client/src/hooks/MCP/polling.tsindex 1014ac731c..d9fd08a67d 100644--- a/client/src/hooks/MCP/polling.ts+++ b/client/src/hooks/MCP/polling.ts@@ -50,6 +50,35 @@ export function applyMCPDiscoveryAuthorizationState(return changed ? nextStatus : connectionStatus;}+/**+ * A server this browser is authorizing is `connecting`, whatever the cached status says. Starting+ * a flow does not refetch connection status, so the cache can still hold the durable `connected`+ * that stored-but-rejected tokens report, and that would read as ready in the middle of OAuth.+ */+export function applyPendingOAuthState(+ connectionStatus: Record<string, MCPServerStatus> | undefined,+ initStates: Record<string, { oauthUrl: string | null }>,+): Record<string, MCPServerStatus> | undefined {+ let nextStatus: Record<string, MCPServerStatus> | undefined;+ for (const [serverName, initState] of Object.entries(initStates)) {+ const current = connectionStatus?.[serverName];+ if (+ initState.oauthUrl == null ||+ (current?.connectionState === 'connecting' && current.authorizationState === 'authorizing')+ ) {+ continue;+ }+ nextStatus ??= { ...(connectionStatus ?? {}) };+ nextStatus[serverName] = {+ ...current,+ requiresOAuth: true,+ connectionState: 'connecting',+ authorizationState: 'authorizing',+ };+ }+ return nextStatus ?? connectionStatus;+}+export type MCPOAuthPollingOutcome = 'pending' | 'completed' | 'failed';export function getMCPOAuthTimeout(diff --git a/client/src/hooks/MCP/useMCPServerManager.ts b/client/src/hooks/MCP/useMCPServerManager.tsindex 160ea9ec1e..820dac1ef0 100644--- a/client/src/hooks/MCP/useMCPServerManager.ts+++ b/client/src/hooks/MCP/useMCPServerManager.ts@@ -33,6 +33,7 @@ import {shouldFailMCPOAuthFallback,isTerminalMCPOAuthPollingError,shouldUseMCPConnectionStatus,+ applyPendingOAuthState,applyMCPDiscoveryAuthorizationState,} from './polling';import {@@ -214,7 +215,10 @@ export function useMCPServerManager({});const connectionStatus = useMemo(() => {if (!polledConnectionStatus) {- return applyMCPDiscoveryAuthorizationState(polledConnectionStatus, discoveredMCPTools);+ return applyPendingOAuthState(+ applyMCPDiscoveryAuthorizationState(polledConnectionStatus, discoveredMCPTools),+ serverInitStates,+ );}let changed = false;@@ -228,8 +232,11 @@ export function useMCPServerManager({nextStatus[serverName] = { ...status, requestScoped: true };}const normalizedStatus = changed ? nextStatus : polledConnectionStatus;- return applyMCPDiscoveryAuthorizationState(normalizedStatus, discoveredMCPTools);- }, [polledConnectionStatus, loadedServers, discoveredMCPTools]);+ return applyPendingOAuthState(+ applyMCPDiscoveryAuthorizationState(normalizedStatus, discoveredMCPTools),+ serverInitStates,+ );+ }, [polledConnectionStatus, loadedServers, discoveredMCPTools, serverInitStates]);const updateServerInitState = useCallback((serverName: string, updates: Partial<MCPServerInitState>) => {