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: Keep MCP Caches Fresh on Demand (#15765)

Danny Avilaaf6e97f0ae2a
diff --git a/client/src/Providers/AgentPanelContext.tsx b/client/src/Providers/AgentPanelContext.tsx
index c561dd81b1..62f0a396d8 100644
--- a/client/src/Providers/AgentPanelContext.tsx
+++ b/client/src/Providers/AgentPanelContext.tsx
@@ -19,6 +19,7 @@ import {
useMCPToolsQuery,
} from '~/data-provider';
import { isMCPServerReadyForAgent } from '~/components/MCP/mcpServerUtils';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
import { Panel, isEphemeralAgent } from '~/common';
import store from '~/store';
@@ -63,6 +64,15 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })
/** The tools query keeps its own warmup gate: the servers list resolving
* alone must not pull the heavier tools request ahead of its stagger. */
const mcpToolsReady = useCatalogReady('mcpTools');
+ useMCPRefresh({
+ enabled:
+ panelVisible &&
+ mcpToolsReady &&
+ !isEphemeralAgent(agent_id) &&
+ !isLoading &&
+ availableMCPServers.length > 0,
+ tools: true,
+ });
const { data: mcpData, isFetching: mcpToolsFetching } = useMCPToolsQuery({
enabled:
mcpToolsReady &&
diff --git a/client/src/components/Chat/Input/MCPSelect.tsx b/client/src/components/Chat/Input/MCPSelect.tsx
index 9fe57c1a1c..38d6914019 100644
--- a/client/src/components/Chat/Input/MCPSelect.tsx
+++ b/client/src/components/Chat/Input/MCPSelect.tsx
@@ -6,6 +6,7 @@ import { TooltipAnchor, composerControlClasses } from '@librechat/client';
import MCPServerMenuItem from '~/components/MCP/MCPServerMenuItem';
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
import StackedMCPIcons from '~/components/MCP/StackedMCPIcons';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
import { useHasAccess, useLocalize } from '~/hooks';
import { useBadgeRowContext } from '~/Providers';
import { cn } from '~/utils';
@@ -18,6 +19,9 @@ function MCPSelectContent() {
const menuStore = Ariakit.useMenuStore({ focusLoop: true });
const isOpen = menuStore.useState('open');
const configDialogOpen = manager?.getConfigDialogProps()?.isOpen === true;
+ useMCPRefresh({
+ enabled: (isOpen || configDialogOpen) && (manager?.availableMCPServers.length ?? 0) > 0,
+ });
/**
* The menu closes with the dialog it launched. Ariakit only takes Escape for
diff --git a/client/src/components/Chat/Input/MCPSubMenu.tsx b/client/src/components/Chat/Input/MCPSubMenu.tsx
index 9a53386567..bd94b9f000 100644
--- a/client/src/components/Chat/Input/MCPSubMenu.tsx
+++ b/client/src/components/Chat/Input/MCPSubMenu.tsx
@@ -4,6 +4,7 @@ import { ChevronRight } from 'lucide-react';
import { MCPIcon, PinIcon } from '@librechat/client';
import MCPServerMenuItem from '~/components/MCP/MCPServerMenuItem';
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
import { useBadgeRowContext } from '~/Providers';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -24,6 +25,13 @@ const MCPSubMenu = React.forwardRef<HTMLButtonElement, MCPSubMenuProps>(
placement: 'right',
});
+ const isOpen = menuStore.useState('open');
+ const configDialogOpen = mcpServerManager?.getConfigDialogProps()?.isOpen === true;
+ useMCPRefresh({
+ enabled:
+ (isOpen || configDialogOpen) && (mcpServerManager?.selectableServers.length ?? 0) > 0,
+ });
+
if (!mcpServerManager) {
return null;
}
diff --git a/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx b/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx
index 2378bcc581..115aad71cc 100644
--- a/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx
@@ -14,6 +14,7 @@ const defaultMcpServerManager = {
{ serverName: 'server-a', config: { title: 'Server A' } },
{ serverName: 'server-b', config: { title: 'Server B' } },
],
+ availableMCPServers: [{ serverName: 'server-a' }, { serverName: 'server-b' }],
connectionStatus: {},
isInitializing: () => false,
getConfigDialogProps: () => null,
@@ -24,6 +25,12 @@ const defaultMcpServerManager = {
let mockCanUseMcp = true;
let mockMcpServerManager = { ...defaultMcpServerManager };
+const mockMCPRefresh = jest.fn();
+
+jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
+ useMCPRefresh: (options: { enabled: boolean; tools?: boolean }) => mockMCPRefresh(options),
+}));
+
jest.mock('~/Providers', () => ({
useBadgeRowContext: () => ({
conversationId: 'test-conv',
@@ -69,6 +76,7 @@ describe('MCPSelect', () => {
it('renders the menu button', () => {
render(<MCPSelect />);
+ expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: false });
expect(screen.getByRole('button', { name: /MCP Servers/i })).toHaveClass(
'h-theme-control',
'min-w-theme-control',
@@ -83,6 +91,7 @@ describe('MCPSelect', () => {
await user.click(screen.getByRole('button', { name: /MCP Servers/i }));
+ expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: true });
const menu = screen.getByRole('menu', { name: /com_ui_mcp_servers/i });
expect(menu).toBeVisible();
expect(within(menu).getByRole('menuitemcheckbox', { name: /Server A/i })).toBeInTheDocument();
diff --git a/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx
index be8fb5d9c2..6a2c1bb10d 100644
--- a/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx
@@ -1,11 +1,16 @@
import React from 'react';
import * as Ariakit from '@ariakit/react';
import userEvent from '@testing-library/user-event';
-import { render, screen, within } from '@testing-library/react';
+import { render, screen, within, waitFor } from '@testing-library/react';
import MCPSubMenu from '../MCPSubMenu';
const mockToggleServerSelection = jest.fn();
const mockSetIsPinned = jest.fn();
+const mockMCPRefresh = jest.fn();
+
+jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
+ useMCPRefresh: (options: { enabled: boolean }) => mockMCPRefresh(options),
+}));
const defaultMcpServerManager = {
isPinned: true,
@@ -85,6 +90,7 @@ describe('MCPSubMenu', () => {
it('renders the submenu trigger with default placeholder', () => {
renderSubMenu();
+ expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: false });
expect(screen.getByText('MCP Servers')).toBeInTheDocument();
});
@@ -94,16 +100,20 @@ describe('MCPSubMenu', () => {
expect(screen.queryByText('MCP Servers')).not.toBeInTheDocument();
});
- it('opens submenu and shows real server items', async () => {
+ it('refreshes the unpinned submenu while open and stops on close', async () => {
const user = userEvent.setup();
+ mockMcpServerManager = { ...defaultMcpServerManager, isPinned: false };
renderSubMenu();
await user.click(screen.getByText('MCP Servers'));
+ expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: true });
const menu = screen.getByRole('menu', { name: /com_ui_mcp_servers/i });
expect(menu).toBeVisible();
expect(within(menu).getByRole('menuitemcheckbox', { name: /Server A/i })).toBeInTheDocument();
expect(within(menu).getByRole('menuitemcheckbox', { name: /Server B/i })).toBeInTheDocument();
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: false }));
});
it('keeps menu open after toggling a server item', async () => {
diff --git a/client/src/components/MCP/ServerInitializationSection.spec.tsx b/client/src/components/MCP/ServerInitializationSection.spec.tsx
index d2281f442b..24404dca63 100644
--- a/client/src/components/MCP/ServerInitializationSection.spec.tsx
+++ b/client/src/components/MCP/ServerInitializationSection.spec.tsx
@@ -7,6 +7,12 @@ import ServerInitializationSection from './ServerInitializationSection';
const mockInitializeServer = jest.fn();
const mockConnectionStatus = jest.fn((): MCPServerStatus | undefined => undefined);
+const mockMCPRefresh = jest.fn();
+
+jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
+ useMCPRefresh: (options: { enabled: boolean; tools?: boolean }) => mockMCPRefresh(options),
+}));
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
useMCPConnectionStatus: () => ({
diff --git a/client/src/components/MCP/ServerInitializationSection.tsx b/client/src/components/MCP/ServerInitializationSection.tsx
index f42aa15a24..6786af1f65 100644
--- a/client/src/components/MCP/ServerInitializationSection.tsx
+++ b/client/src/components/MCP/ServerInitializationSection.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import { RefreshCw, Trash2 } from 'lucide-react';
import { Button, Spinner } from '@librechat/client';
import { useLocalize, useMCPServerManager, useMCPConnectionStatus } from '~/hooks';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
interface ServerInitializationSectionProps {
sidePanel?: boolean;
@@ -37,6 +38,8 @@ export default function ServerInitializationSection({
enabled: !!availableMCPServers && availableMCPServers.length > 0,
});
+ useMCPRefresh({ enabled: availableMCPServers.length > 0 });
+
const serverStatus = connectionStatus?.[serverName];
const isConnected = serverStatus?.connectionState === 'connected';
const hasPendingOAuth =
diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx
index 8901ca4718..cff2b26c96 100644
--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx
+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx
@@ -27,6 +27,12 @@ const mockLocalize = jest.fn((key: string, values?: Record<number, string>) =>
key === 'com_nav_mcp_status_connecting' ? `${values?.[0]} - Connecting` : key,
);
+const mockMCPRefresh = jest.fn();
+
+jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
+ useMCPRefresh: (options: { enabled: boolean; tools?: boolean }) => mockMCPRefresh(options),
+}));
+
jest.mock('react-hook-form', () => ({
useFormContext: () => ({ control: {}, setValue: mockSetValue, getValues: mockGetValues }),
useWatch: ({ name }: { name: string }) => {
diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx
index e52b62a286..4b1cb8cdf0 100644
--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx
+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx
@@ -26,6 +26,7 @@ import { getStatusColor, getStatusTextKey } from '~/components/MCP/mcpServerUtil
import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
import McpOAuthDialog from '~/components/MCP/McpOAuthDialog';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
import { useAgentPanelContext } from '~/Providers';
import { getIconForItem } from '../../items/icons';
import OptionToggle from '../../../OptionToggle';
@@ -79,6 +80,7 @@ export default function McpSection({ item }: Props) {
const [prevReadyForAgent, setPrevReadyForAgent] = useState(false);
const [autoSelectPending, setAutoSelectPending] = useState(false);
const { mcpServersMap, mcpToolsLoading } = useAgentPanelContext();
+ useMCPRefresh({ enabled: true, tools: true });
const { agentsConfig } = useGetAgentsConfig();
const {
codeEnabled,
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx b/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
index cd84fde546..85f641118b 100644
--- a/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
+++ b/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
@@ -14,6 +14,7 @@ import {
import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
import { PanelFooter, PanelContent } from '~/components/ui';
import MCPServerCardSkeleton from './MCPServerCardSkeleton';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
import MCPAdminSettings from './MCPAdminSettings';
import MCPServerDialog from './MCPServerDialog';
import MCPServerList from './MCPServerList';
@@ -35,6 +36,7 @@ export default function MCPBuilderPanel() {
const { user } = useAuthContext();
const { availableMCPServers, isLoading, getServerStatusIconProps, getConfigDialogProps } =
useMCPServerManager();
+ useMCPRefresh({ enabled: panelVisible && !isLoading && availableMCPServers.length > 0 });
const hasCreateAccess = useHasAccess({
permissionType: PermissionTypes.MCP_SERVERS,
diff --git a/client/src/data-provider/MCP/__tests__/freshness.spec.tsx b/client/src/data-provider/MCP/__tests__/freshness.spec.tsx
new file mode 100644
index 0000000000..1e5704d4a5
--- /dev/null
+++ b/client/src/data-provider/MCP/__tests__/freshness.spec.tsx
@@ -0,0 +1,245 @@
+import React from 'react';
+import { act, renderHook } from '@testing-library/react';
+import { QueryKeys, dataService } from 'librechat-data-provider';
+import {
+ QueryClient,
+ QueryClientProvider,
+ focusManager,
+ onlineManager,
+} from '@tanstack/react-query';
+import type { MCPServersResponse, MCPConnectionStatusResponse } from 'librechat-data-provider';
+import { useMCPConnectionStatusQuery } from '../../Tools/queries';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
+import { useMCPToolsQuery } from '../queries';
+
+jest.mock('librechat-data-provider', () => {
+ const actual =
+ jest.requireActual<typeof import('librechat-data-provider')>('librechat-data-provider');
+ return { ...actual, dataService: { ...actual.dataService } };
+});
+
+const mockRefreshConfig = { statusRefreshInterval: 30_000, toolsRefreshInterval: 300_000 };
+
+jest.mock('~/data-provider/Endpoints/queries', () => ({
+ useGetStartupConfig: () => ({ data: { interface: { mcpServers: mockRefreshConfig } } }),
+}));
+
+const catalog: MCPServersResponse = { servers: {} };
+const connected: MCPConnectionStatusResponse = {
+ success: true,
+ connectionStatus: { test: { requiresOAuth: false, connectionState: 'connected' } },
+};
+const disconnected: MCPConnectionStatusResponse = {
+ success: true,
+ connectionStatus: { test: { requiresOAuth: false, connectionState: 'disconnected' } },
+};
+const changedCatalog: MCPServersResponse = {
+ servers: {
+ test: { name: 'test', icon: '', authenticated: true, authConfig: [], tools: [] },
+ },
+};
+
+function useCatalogQueries(enabled = true) {
+ useMCPRefresh({ enabled, tools: true });
+}
+
+describe('MCP cache freshness', () => {
+ let client: QueryClient;
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ mockRefreshConfig.statusRefreshInterval = 30_000;
+ mockRefreshConfig.toolsRefreshInterval = 300_000;
+ focusManager.setFocused(true);
+ onlineManager.setOnline(true);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client.setQueryData([QueryKeys.mcpTools], catalog);
+ client.setQueryData([QueryKeys.mcpConnectionStatus], connected);
+ jest.spyOn(dataService, 'getMCPTools').mockResolvedValue(changedCatalog);
+ jest.spyOn(dataService, 'getMCPConnectionStatus').mockResolvedValue(disconnected);
+ });
+
+ afterEach(() => {
+ client.clear();
+ focusManager.setFocused(undefined);
+ onlineManager.setOnline(true);
+ jest.useRealTimers();
+ });
+
+ it('keeps always-mounted cache observers free of polling', async () => {
+ const { unmount } = renderHook(
+ () => {
+ useMCPToolsQuery();
+ useMCPConnectionStatusQuery();
+ },
+ { wrapper },
+ );
+ await act(async () => {
+ jest.advanceTimersByTime(600_000);
+ });
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+ expect(dataService.getMCPConnectionStatus).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it('starts polling when a surface opens and stops when it closes', async () => {
+ const { rerender, unmount } = renderHook(
+ ({ visible }) => {
+ useMCPToolsQuery();
+ useMCPConnectionStatusQuery();
+ useMCPRefresh({ enabled: visible, tools: true });
+ },
+ { wrapper, initialProps: { visible: false } },
+ );
+ await act(async () => {
+ jest.advanceTimersByTime(600_000);
+ });
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+ expect(dataService.getMCPConnectionStatus).not.toHaveBeenCalled();
+ await act(async () => {
+ rerender({ visible: true });
+ });
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ jest.advanceTimersByTime(30_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(2);
+ rerender({ visible: false });
+ await act(async () => {
+ jest.advanceTimersByTime(600_000);
+ });
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(2);
+ unmount();
+ });
+
+ it('shares the polling cadence across staggered surfaces and keeps polling after one closes', async () => {
+ mockRefreshConfig.toolsRefreshInterval = 60_000;
+ const { rerender, unmount } = renderHook(
+ ({ panel, dialog }) => {
+ useMCPRefresh({ enabled: panel, tools: true });
+ useMCPRefresh({ enabled: dialog, tools: true });
+ },
+ { wrapper, initialProps: { panel: true, dialog: false } },
+ );
+ await act(async () => {
+ jest.advanceTimersByTime(5_000);
+ });
+ rerender({ panel: true, dialog: true });
+ await act(async () => {
+ jest.advanceTimersByTime(25_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ jest.advanceTimersByTime(5_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ jest.advanceTimersByTime(25_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(2);
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ jest.advanceTimersByTime(5_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(2);
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ rerender({ panel: false, dialog: true });
+ await act(async () => {
+ jest.advanceTimersByTime(25_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(3);
+ unmount();
+ });
+
+ it('honors configured polling intervals and zero to disable', async () => {
+ mockRefreshConfig.statusRefreshInterval = 60_000;
+ mockRefreshConfig.toolsRefreshInterval = 0;
+ const { unmount } = renderHook(() => useCatalogQueries(), { wrapper });
+ await act(async () => {
+ jest.advanceTimersByTime(30_000);
+ });
+ expect(dataService.getMCPConnectionStatus).not.toHaveBeenCalled();
+ await act(async () => {
+ jest.advanceTimersByTime(30_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ jest.advanceTimersByTime(300_000);
+ });
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it('reconciles server-side changes at bounded intervals without sending messages', async () => {
+ const { rerender, unmount } = renderHook(() => useCatalogQueries(), { wrapper });
+ rerender();
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+ expect(dataService.getMCPConnectionStatus).not.toHaveBeenCalled();
+
+ await act(async () => {
+ jest.advanceTimersByTime(30_000);
+ });
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ expect(client.getQueryData([QueryKeys.mcpConnectionStatus])).toEqual(disconnected);
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+
+ await act(async () => {
+ jest.advanceTimersByTime(270_000);
+ });
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ expect(client.getQueryData([QueryKeys.mcpTools])).toEqual(changedCatalog);
+ unmount();
+ });
+
+ it('does not poll while the browser is hidden and refreshes stale data on focus', async () => {
+ focusManager.setFocused(false);
+ const { unmount } = renderHook(() => useCatalogQueries(), { wrapper });
+ await act(async () => {
+ jest.advanceTimersByTime(300_001);
+ });
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+ expect(dataService.getMCPConnectionStatus).not.toHaveBeenCalled();
+
+ await act(async () => {
+ focusManager.setFocused(true);
+ });
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ it.each(['mount', 'reconnect'] as const)('refreshes stale data on %s', async (event) => {
+ jest.advanceTimersByTime(300_001);
+ if (event === 'reconnect') {
+ onlineManager.setOnline(false);
+ }
+ const { unmount } = renderHook(() => useCatalogQueries(), { wrapper });
+ await act(async () => {
+ onlineManager.setOnline(true);
+ });
+ expect(dataService.getMCPTools).toHaveBeenCalledTimes(1);
+ expect(dataService.getMCPConnectionStatus).toHaveBeenCalledTimes(1);
+ expect(client.getQueryData([QueryKeys.mcpTools])).toEqual(changedCatalog);
+ expect(client.getQueryData([QueryKeys.mcpConnectionStatus])).toEqual(disconnected);
+ unmount();
+ });
+
+ it('keeps disabled queries idle across polling, focus, and reconnect', async () => {
+ const { unmount } = renderHook(() => useCatalogQueries(false), { wrapper });
+ await act(async () => {
+ jest.advanceTimersByTime(600_000);
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ onlineManager.setOnline(false);
+ onlineManager.setOnline(true);
+ });
+ expect(dataService.getMCPTools).not.toHaveBeenCalled();
+ expect(dataService.getMCPConnectionStatus).not.toHaveBeenCalled();
+ unmount();
+ });
+});
diff --git a/client/src/data-provider/MCP/queries.ts b/client/src/data-provider/MCP/queries.ts
index 8590e43735..29314683b1 100644
--- a/client/src/data-provider/MCP/queries.ts
+++ b/client/src/data-provider/MCP/queries.ts
@@ -1,5 +1,5 @@
-import { useQuery, UseQueryOptions, QueryObserverResult } from '@tanstack/react-query';
import { QueryKeys, dataService } from 'librechat-data-provider';
+import { useQuery, UseQueryOptions, QueryObserverResult } from '@tanstack/react-query';
import type * as t from 'librechat-data-provider';
/**
@@ -34,10 +34,12 @@ export const useMCPToolsQuery = <TData = t.MCPServersResponse>(
[QueryKeys.mcpTools],
() => dataService.getMCPTools(),
{
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- refetchOnMount: false,
- staleTime: 5 * 60 * 1000, // 5 minutes
+ refetchOnWindowFocus: true,
+ refetchOnReconnect: true,
+ refetchOnMount: true,
+ staleTime: 5 * 60 * 1000,
+ refetchInterval: false,
+ refetchIntervalInBackground: false,
...config,
},
);
diff --git a/client/src/data-provider/Tools/queries.ts b/client/src/data-provider/Tools/queries.ts
index 6b06f25c9f..2271753c87 100644
--- a/client/src/data-provider/Tools/queries.ts
+++ b/client/src/data-provider/Tools/queries.ts
@@ -48,10 +48,12 @@ export const useMCPConnectionStatusQuery = (
[QueryKeys.mcpConnectionStatus],
() => dataService.getMCPConnectionStatus(),
{
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- refetchOnMount: false,
+ refetchOnWindowFocus: true,
+ refetchOnReconnect: true,
+ refetchOnMount: true,
staleTime: 10000, // 10 seconds
+ refetchInterval: false,
+ refetchIntervalInBackground: false,
...config,
},
);
diff --git a/client/src/hooks/MCP/useMCPRefresh.ts b/client/src/hooks/MCP/useMCPRefresh.ts
new file mode 100644
index 0000000000..7414b194b3
--- /dev/null
+++ b/client/src/hooks/MCP/useMCPRefresh.ts
@@ -0,0 +1,21 @@
+import { mcpRefreshDefaults } from 'librechat-data-provider';
+import { useMCPConnectionStatusQuery } from '~/data-provider/Tools/queries';
+import { useGetStartupConfig } from '~/data-provider/Endpoints/queries';
+import { useMCPToolsQuery } from '~/data-provider/MCP/queries';
+
+/** Reconcile server-side MCP changes only while a consuming UI is visible. */
+export function useMCPRefresh({ enabled, tools = false }: { enabled: boolean; tools?: boolean }) {
+ const { data: startupConfig } = useGetStartupConfig();
+ const config = startupConfig?.interface?.mcpServers;
+ const statusInterval = config?.statusRefreshInterval ?? mcpRefreshDefaults.statusRefreshInterval;
+ const toolsInterval = config?.toolsRefreshInterval ?? mcpRefreshDefaults.toolsRefreshInterval;
+
+ useMCPConnectionStatusQuery({
+ enabled,
+ refetchInterval: enabled && statusInterval > 0 ? statusInterval : false,
+ });
+ useMCPToolsQuery({
+ enabled: enabled && tools,
+ refetchInterval: enabled && tools && toolsInterval > 0 ? toolsInterval : false,
+ });
+}
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 239c6927dd..fcef419cf7 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -601,8 +601,6 @@ export default function useEventHandlers({
const createdHandler = useCallback(
(data: TResData, submission: EventSubmission) => {
- queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);
- queryClient.invalidateQueries([QueryKeys.mcpTools]);
const { messages, userMessage, isRegenerate = false, isTemporary = false } = submission;
/**
* The spread carries `manualSkills` through from
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 48492895e9..940e52ef41 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -266,6 +266,9 @@ interface:
# public: true # Allows users to toggle "share with everyone" for their links. Whether anonymous access is permitted is controlled by ALLOW_SHARED_LINKS_PUBLIC.
# snapshotFiles: true # Snapshot files referenced by a shared chat so viewers can preview/download them via the link. Enabled by default; the SHARED_LINKS_SNAPSHOT_FILES env var overrides this.
# mcpServers:
+ # # Poll only while MCP controls are visible, in milliseconds (0 disables polling).
+ # toolsRefreshInterval: 300000
+ # statusRefreshInterval: 30000
# Controls user permissions for MCP (Model Context Protocol) server management
# - use: Allow users to use configured MCP servers
# - create: Allow users to create and manage new MCP servers
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index 320d1442c3..727526692e 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -1154,3 +1154,25 @@ describe('bedrockModels defaults', () => {
expect(bedrockModels).not.toContain('anthropic.claude-opus-5');
});
});
+
+describe('MCP UI refresh configuration', () => {
+ it('preserves configured intervals, including zero to disable polling', () => {
+ const result = configSchema.parse({
+ version: '1.3.5',
+ interface: { mcpServers: { toolsRefreshInterval: 0, statusRefreshInterval: 60_000 } },
+ });
+ expect(result.interface?.mcpServers).toMatchObject({
+ toolsRefreshInterval: 0,
+ statusRefreshInterval: 60_000,
+ });
+ });
+
+ it.each([-1, 1.5, 2_147_483_648])('rejects invalid timer intervals: %s', (interval) => {
+ expect(
+ configSchema.safeParse({
+ version: '1.3.5',
+ interface: { mcpServers: { statusRefreshInterval: interval } },
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 142fc633ed..1ce166acd6 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1789,8 +1789,16 @@ export type TTermsOfService = z.infer<typeof termsOfServiceSchema>;
const localizedStringSchema = z.union([z.string(), z.record(z.string())]);
export type LocalizedString = z.infer<typeof localizedStringSchema>;
+export const mcpRefreshDefaults = {
+ toolsRefreshInterval: 5 * 60 * 1000,
+ statusRefreshInterval: 30 * 1000,
+};
+
const mcpServersSchema = z
.object({
+ /** Foreground polling intervals in milliseconds; 0 disables polling. */
+ toolsRefreshInterval: z.number().int().nonnegative().max(2_147_483_647).optional(),
+ statusRefreshInterval: z.number().int().nonnegative().max(2_147_483_647).optional(),
placeholder: z.string().optional(),
use: z.boolean().optional(),
create: z.boolean().optional(),