Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(discover): move the MCP market slice onto @lobechat/replica (#20694)

Arvin Xu2d13ebff4c9d
diff --git a/src/features/MCP/MCPDetail/index.tsx b/src/features/MCP/MCPDetail/index.tsx
index 2d670803a02..817e5cf09ea 100644
--- a/src/features/MCP/MCPDetail/index.tsx
+++ b/src/features/MCP/MCPDetail/index.tsx
@@ -13,6 +13,7 @@ import Overview from '@/features/MCPPluginDetail/Overview';
import Schema from '@/features/MCPPluginDetail/Schema';
import Score from '@/features/MCPPluginDetail/Score';
import { useDiscoverStore } from '@/store/discover';
+import { mcpSelectors } from '@/store/discover/selectors';
import { useToolStore } from '@/store/tool';
import { McpNavKey } from '@/types/discover';
@@ -36,7 +37,8 @@ const Detail = memo<DetailProps>(({ identifier: defaultIdentifier, defaultTab, n
const identifier = defaultIdentifier ?? list?.items?.[0]?.identifier;
const useMcpDetail = useDiscoverStore((s) => s.useFetchMcpDetail);
- const { data, isLoading } = useMcpDetail({ identifier });
+ const { isLoading, queryKey } = useMcpDetail({ identifier });
+ const data = useDiscoverStore(mcpSelectors.mcpDetail(queryKey));
// An explicit identifier never waits on the list; otherwise wait for it to paint.
if ((!defaultIdentifier && !list) || isLoading) return <Loading />;
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
index 53ecc3d5b1a..e71a0a3c643 100644
--- a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
@@ -10,6 +10,7 @@ import DetailLoading from '@/features/MCP/MCPDetail/Loading';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useDiscoverStore } from '@/store/discover';
+import { mcpSelectors } from '@/store/discover/selectors';
import { useToolStore } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';
@@ -39,7 +40,8 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
]);
const togglePlugin = useAgentStore((s) => s.togglePlugin);
- const { data, isLoading } = useMcpDetail({ identifier });
+ const { isLoading, queryKey } = useMcpDetail({ identifier });
+ const data = useDiscoverStore(mcpSelectors.mcpDetail(queryKey));
const handleConfirm = useCallback(async () => {
if (!canCreate || !canEdit || !installRequest || !data) return;
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 161eb285095..c0395d934b8 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -512,22 +512,6 @@ export const discoverKeys = {
locale,
params,
]),
- mcpCategories: def('discover:mcpCategories', (locale: string, params: unknown) => [
- 'discover:mcpCategories',
- locale,
- params,
- ]),
- mcpDetail: def('discover:mcpDetail', (locale: string, identifier: string, version?: string) => [
- 'discover:mcpDetail',
- locale,
- identifier,
- version,
- ]),
- mcpList: def('discover:mcpList', (locale: string, params: unknown) => [
- 'discover:mcpList',
- locale,
- params,
- ]),
modelCategories: def('discover:modelCategories', (params: unknown) => [
'discover:modelCategories',
params,
diff --git a/src/routes/(main)/community/(detail)/mcp/index.tsx b/src/routes/(main)/community/(detail)/mcp/index.tsx
index c7119d5e317..1a3af26a63e 100644
--- a/src/routes/(main)/community/(detail)/mcp/index.tsx
+++ b/src/routes/(main)/community/(detail)/mcp/index.tsx
@@ -11,6 +11,7 @@ import Header from '@/features/MCPPluginDetail/Header';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { mcpSelectors } from '@/store/discover/selectors';
import NotFound from '../components/NotFound';
import { TocProvider } from '../features/Toc/useToc';
@@ -26,7 +27,8 @@ const McpDetailPage = memo<McpDetailPageProps>(({ mobile }) => {
const { version } = useQuery() as { version?: string };
const useMcpDetail = useDiscoverStore((s) => s.useFetchMcpDetail);
- const { data, error, isLoading, mutate } = useMcpDetail({ identifier, version });
+ const { error, isLoading, mutate, queryKey } = useMcpDetail({ identifier, version });
+ const data = useDiscoverStore(mcpSelectors.mcpDetail(queryKey));
useFetchInstalledPlugins();
if (data === undefined) {
diff --git a/src/routes/(main)/community/(list)/(home)/index.tsx b/src/routes/(main)/community/(list)/(home)/index.tsx
index d5161f26d0a..707d539fe18 100644
--- a/src/routes/(main)/community/(list)/(home)/index.tsx
+++ b/src/routes/(main)/community/(list)/(home)/index.tsx
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
import { useDiscoverStore } from '@/store/discover';
+import { mcpSelectors } from '@/store/discover/selectors';
import { AssistantSorts, McpSorts } from '@/types/discover';
import ListLoading from '../../components/ListLoading';
@@ -30,15 +31,17 @@ const HomePage = memo(() => {
});
const {
- data: mcpList,
- isLoading: pluginLoading,
error: mcpError,
+ isLoading: pluginLoading,
mutate: refetchMcp,
+ queryKey: mcpQueryKey,
} = useMcpList({
page: 1,
pageSize: 12,
sort: McpSorts.Recommended,
});
+ // The replica view of this query; the sync hook only reports the fetch flags.
+ const mcpList = useDiscoverStore(mcpSelectors.mcpList(mcpQueryKey));
return (
<>
diff --git a/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx b/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx
index 9fae888e21b..ae499d4c31b 100644
--- a/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/mcp/features/Category/index.tsx
@@ -12,6 +12,7 @@ import { useCategory } from '@/hooks/useMCPCategory';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { useDiscoverStore } from '@/store/discover';
+import { mcpSelectors } from '@/store/discover/selectors';
import { McpCategory, McpSorts } from '@/types/discover';
import CategoryMenu from '../../../../components/CategoryMenu';
@@ -22,7 +23,8 @@ const Category = memo(() => {
category?: McpCategory;
q?: string;
};
- const { data: items = [] } = useMcpCategories({ q });
+ const { queryKey } = useMcpCategories({ q });
+ const items = useDiscoverStore(mcpSelectors.mcpCategories(queryKey));
const navigate = useWorkspaceAwareNavigate();
const cates = useCategory();
diff --git a/src/routes/(main)/community/(list)/mcp/index.tsx b/src/routes/(main)/community/(list)/mcp/index.tsx
index 52da140bd64..cfcf75bfcf2 100644
--- a/src/routes/(main)/community/(list)/mcp/index.tsx
+++ b/src/routes/(main)/community/(list)/mcp/index.tsx
@@ -7,6 +7,7 @@ import AsyncBoundary from '@/components/AsyncBoundary';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { mcpSelectors } from '@/store/discover/selectors';
import { type McpQueryParams } from '@/types/discover';
import { DiscoverTab, McpSorts } from '@/types/discover';
@@ -17,7 +18,7 @@ import List from './features/List';
const McpPage = memo(() => {
const { q, page, category, sort, order } = useQuery() as McpQueryParams;
const useMcpList = useDiscoverStore((s) => s.useFetchMcpList);
- const { data, error, isLoading, mutate } = useMcpList({
+ const { error, isLoading, mutate, queryKey } = useMcpList({
category,
order,
page,
@@ -25,6 +26,8 @@ const McpPage = memo(() => {
q,
sort: sort ?? McpSorts.Recommended,
});
+ // The replica view of this query; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(mcpSelectors.mcpList(queryKey));
const items = data?.items ?? [];
diff --git a/src/store/discover/initialState.ts b/src/store/discover/initialState.ts
index 6236369195a..b008d3a088d 100644
--- a/src/store/discover/initialState.ts
+++ b/src/store/discover/initialState.ts
@@ -1,3 +1,5 @@
+import type { MCPSliceState } from './slices/mcp/initialState';
+import { initialMCPSliceState } from './slices/mcp/initialState';
import type { ProviderSliceState } from './slices/provider/initialState';
import { initialProviderSliceState } from './slices/provider/initialState';
@@ -5,8 +7,9 @@ import { initialProviderSliceState } from './slices/provider/initialState';
* State of the discover (marketplace) store: the replica views of its slices,
* plus each slice's bookkeeping. Slices add their own actions on top.
*/
-export type DiscoverStoreState = ProviderSliceState;
+export type DiscoverStoreState = MCPSliceState & ProviderSliceState;
export const initialState: DiscoverStoreState = {
+ ...initialMCPSliceState,
...initialProviderSliceState,
};
diff --git a/src/store/discover/selectors/index.ts b/src/store/discover/selectors/index.ts
index e932bf68166..c11b0fd5b4e 100644
--- a/src/store/discover/selectors/index.ts
+++ b/src/store/discover/selectors/index.ts
@@ -1 +1,2 @@
+export { mcpSelectors } from './mcpSelectors';
export { providerSelectors } from './providerSelectors';
diff --git a/src/store/discover/selectors/mcpSelectors.ts b/src/store/discover/selectors/mcpSelectors.ts
new file mode 100644
index 00000000000..c4070a8dc71
--- /dev/null
+++ b/src/store/discover/selectors/mcpSelectors.ts
@@ -0,0 +1,33 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import type { DiscoverMcpDetail, McpListResponse } from '@/types/discover';
+
+import type { DiscoverStore } from '../store';
+
+const EMPTY_CATEGORIES: CategoryItem[] = [];
+
+/**
+ * Readers of the MCP market replicas. Every helper takes the `queryKey` the
+ * matching fetch hook returned, so a surface that asks for one query never
+ * reads another's rows.
+ */
+const mcpList =
+ (queryKey?: string) =>
+ (s: DiscoverStore): McpListResponse | undefined =>
+ queryKey ? s.mcpListMap[queryKey] : undefined;
+
+const mcpDetail =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverMcpDetail | undefined =>
+ queryKey ? s.mcpDetailMap[queryKey] : undefined;
+
+const mcpCategories =
+ (queryKey?: string) =>
+ (s: DiscoverStore): CategoryItem[] =>
+ (queryKey && s.mcpCategoriesMap[queryKey]) || EMPTY_CATEGORIES;
+
+export const mcpSelectors = {
+ mcpCategories,
+ mcpDetail,
+ mcpList,
+};
diff --git a/src/store/discover/slices/mcp/action.test.ts b/src/store/discover/slices/mcp/action.test.ts
index 8792225b384..731e4da076f 100644
--- a/src/store/discover/slices/mcp/action.test.ts
+++ b/src/store/discover/slices/mcp/action.test.ts
@@ -1,128 +1,276 @@
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { discoverService } from '@/services/discover';
+import { createReplicaState } from '@/libs/replica';
import { globalHelpers } from '@/store/global/helpers';
+import type { McpListResponse } from '@/types/discover';
+import { mcpSelectors } from '../../selectors';
import { useDiscoverStore as useStore } from '../../store';
+import { mcpCategoriesQueryKey, mcpDetailQueryKey, mcpListQueryKey } from './projection';
+
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getMcpCategories: vi.fn(),
+ getMcpDetail: vi.fn(),
+ getMcpList: vi.fn(),
+ },
+}));
+
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const makeList = (identifier = 'mcp-1'): McpListResponse =>
+ ({
+ currentPage: 1,
+ items: [{ identifier } as any],
+ pageSize: 21,
+ totalCount: 1,
+ totalPages: 1,
+ }) as McpListResponse;
+
+const emptyMcpState = () => ({
+ mcpCategoriesMap: {},
+ mcpCategoriesReplica: createReplicaState(),
+ mcpDetailMap: {},
+ mcpDetailReplica: createReplicaState(),
+ mcpListMap: {},
+ mcpListReplica: createReplicaState(),
+});
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ useStore.setState(emptyMcpState());
});
-describe('MCPAction', () => {
- describe('useFetchMcpDetail', () => {
- it('should fetch MCP detail when identifier is provided', async () => {
- const mockDetail = {
- identifier: 'test-mcp',
- name: 'Test MCP',
- description: 'A test MCP server',
- };
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (name: 'mcpCategories' | 'mcpDetail' | 'mcpList') => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+describe('MCPSlice (replica)', () => {
+ describe('useFetchMcpList', () => {
+ it('requests the list with normalized page / pageSize and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getMcpDetail').mockResolvedValue(mockDetail as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ renderHook(() => useStore.getState().useFetchMcpList({ q: 'github' }));
- const params = { identifier: 'test-mcp', version: '1.0.0' };
- const { result } = renderHook(() => useStore.getState().useFetchMcpDetail(params));
+ const [call] = await syncCalls('mcpList');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockDetail);
+ expect(discoverService.getMcpList).toHaveBeenCalledWith({
+ locale: 'en-US',
+ page: 1,
+ pageSize: 21,
+ q: 'github',
});
+ });
+
+ it('keys each page and filter set as its own replica entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchMcpList({ page: 1 }),
+ useStore.getState().useFetchMcpList({ page: 2 }),
+ useStore.getState().useFetchMcpList({ category: 'developer' }),
+ ]);
- expect(discoverService.getMcpDetail).toHaveBeenCalledWith(params);
+ const [first, second, third] = result.current;
+ expect(new Set([first.queryKey, second.queryKey, third.queryKey]).size).toBe(3);
});
- it('should not fetch when identifier is undefined', () => {
+ it('does not register a sync β€” and reports no loading β€” when disabled', async () => {
const { result } = renderHook(() =>
- useStore.getState().useFetchMcpDetail({ identifier: undefined }),
+ useStore.getState().useFetchMcpList({ page: 1 }, { enabled: false }),
);
- expect(result.current.data).toBeUndefined();
- expect(discoverService.getMcpDetail).not.toHaveBeenCalled();
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('mcpList')).toHaveLength(0);
+ });
+
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() => useStore.getState().useFetchMcpList({ page: 1 }));
+
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('does not report loading when the entry already has a (hydrated) value', () => {
+ const key = mcpListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ useStore.setState({ mcpListMap: { [key]: makeList() } });
+
+ const { result } = renderHook(() => useStore.getState().useFetchMcpList({ page: 1 }));
+
+ expect(result.current.queryKey).toBe(key);
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('folds the response into the replica view the selectors read', async () => {
+ const response = makeList();
+
+ renderHook(() => useStore.getState().useFetchMcpList({ page: 1 }));
+ const [call] = await syncCalls('mcpList');
+ act(() => call.config.onSuccess!(response));
+
+ const key = mcpListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ expect(mcpSelectors.mcpList(key)(useStore.getState())).toEqual(response);
});
});
- describe('useFetchMcpList', () => {
- it('should fetch MCP list with default parameters', async () => {
- const mockList = {
- items: [{ identifier: 'mcp-1' }, { identifier: 'mcp-2' }],
- total: 2,
- };
+ describe('useFetchMcpDetail', () => {
+ it('drops a cached detail once the market reports the server gone', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getMcpList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-1' }),
+ );
+ const key = result.current.queryKey!;
+ const [call] = await syncCalls('mcpDetail');
- const { result } = renderHook(() => useStore.getState().useFetchMcpList({}));
+ vi.mocked(discoverService.getMcpDetail).mockResolvedValueOnce({ identifier: 'mcp-1' } as any);
+ const cached = await call.fetcher();
+ act(() => call.config.onSuccess!(cached));
+ expect(mcpSelectors.mcpDetail(key)(useStore.getState())).toEqual({ identifier: 'mcp-1' });
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ // The market removed the server: the service answers `undefined`.
+ vi.mocked(discoverService.getMcpDetail).mockResolvedValueOnce(undefined as any);
+ const missing = await call.fetcher();
+ act(() => call.config.onSuccess!(missing));
- expect(discoverService.getMcpList).toHaveBeenCalledWith({
- page: 1,
- pageSize: 21,
- });
+ expect(mcpSelectors.mcpDetail(key)(useStore.getState())).toBeUndefined();
+ expect(useStore.getState().mcpDetailMap[key]).toBeUndefined();
});
- it('should fetch MCP list with custom parameters', async () => {
- const mockList = {
- items: [{ identifier: 'mcp-1' }],
- total: 1,
- };
+ it('requests the detail with identifier, version and locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getMcpList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ renderHook(() =>
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-1', version: '1.0.0' }),
+ );
- const params = { page: 2, pageSize: 10, category: 'data-analysis' } as any;
- const { result } = renderHook(() => useStore.getState().useFetchMcpList(params));
+ const [call] = await syncCalls('mcpDetail');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
+ expect(discoverService.getMcpDetail).toHaveBeenCalledWith({
+ identifier: 'mcp-1',
+ locale: 'en-US',
+ version: '1.0.0',
});
+ });
- expect(discoverService.getMcpList).toHaveBeenCalledWith({
- page: 2,
- pageSize: 10,
- category: 'data-analysis',
- });
+ it('keys the detail by identifier, so a different identifier is a different entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-1' }),
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-2' }),
+ ]);
+
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
});
- it('should convert page and pageSize to numbers', async () => {
- vi.spyOn(discoverService, 'getMcpList').mockResolvedValue({ items: [] } as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ it('keys the detail by version, so a pinned version is a different entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-1' }),
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-1', version: '1.0.0' }),
+ ]);
- const params = { page: 3, pageSize: 15 } as any;
- const { result } = renderHook(() => useStore.getState().useFetchMcpList(params));
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
+ });
- await waitFor(() => {
- expect(result.current.data).toBeDefined();
- });
+ it('keys the detail by the locale, so a language switch refetches', () => {
+ const { result, rerender } = renderHook(() =>
+ useStore.getState().useFetchMcpDetail({ identifier: 'mcp-1' }),
+ );
+ const first = result.current.queryKey;
- expect(discoverService.getMcpList).toHaveBeenCalledWith({
- page: 3,
- pageSize: 15,
- });
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ rerender();
+
+ expect(result.current.queryKey).not.toBe(first);
+ });
+
+ it('does not register a sync β€” and reports no loading β€” without an identifier', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchMcpDetail({ identifier: undefined }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('mcpDetail')).toHaveLength(0);
+ });
+
+ it('does not register a sync for an empty identifier', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchMcpDetail({ identifier: '' }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('mcpDetail')).toHaveLength(0);
});
});
describe('useMcpCategories', () => {
- it('should fetch MCP categories with correct parameters', async () => {
- const mockCategories = [
- { id: 'cat-1', name: 'Category 1' },
- { id: 'cat-2', name: 'Category 2' },
- ];
+ it('does not revalidate the categories on window focus', async () => {
+ renderHook(() => useStore.getState().useMcpCategories({ q: 'github' }));
+
+ const [call] = await syncCalls('mcpCategories');
+ expect(call.config.revalidateOnFocus).toBe(false);
+ });
- vi.spyOn(discoverService, 'getMcpCategories').mockResolvedValue(mockCategories as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ it('requests category counts with the search term and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- const params = {} as any;
- const { result } = renderHook(() => useStore.getState().useMcpCategories(params));
+ renderHook(() => useStore.getState().useMcpCategories({ q: 'github' }));
- await waitFor(() => {
- expect(result.current.data).toEqual(mockCategories);
+ const [call] = await syncCalls('mcpCategories');
+ await call.fetcher();
+
+ expect(discoverService.getMcpCategories).toHaveBeenCalledWith({
+ locale: 'en-US',
+ q: 'github',
});
+ });
+
+ it('skips the request when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useMcpCategories({}, { enabled: false }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('mcpCategories')).toHaveLength(0);
+ });
- expect(discoverService.getMcpCategories).toHaveBeenCalledWith(params);
+ it('falls back to an empty list when no category entry is loaded', () => {
+ expect(mcpSelectors.mcpCategories(undefined)(useStore.getState())).toEqual([]);
+ expect(mcpSelectors.mcpList(undefined)(useStore.getState())).toBeUndefined();
+ expect(mcpSelectors.mcpDetail(undefined)(useStore.getState())).toBeUndefined();
+ });
+ });
+
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per query dimension', () => {
+ expect(mcpListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 })).toBe(
+ mcpListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 }),
+ );
+ expect(mcpDetailQueryKey({ identifier: 'a' })).not.toBe(
+ mcpDetailQueryKey({ identifier: 'b' }),
+ );
+ expect(mcpDetailQueryKey({ identifier: 'a' })).not.toBe(
+ mcpDetailQueryKey({ identifier: 'a', version: '2.0.0' }),
+ );
+ expect(mcpCategoriesQueryKey({ q: 'a' })).not.toBe(mcpCategoriesQueryKey({}));
});
});
});
diff --git a/src/store/discover/slices/mcp/action.ts b/src/store/discover/slices/mcp/action.ts
index 7564d237c57..47fb1d91e70 100644
--- a/src/store/discover/slices/mcp/action.ts
+++ b/src/store/discover/slices/mcp/action.ts
@@ -1,64 +1,160 @@
-import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
-import { type SWRResponse } from 'swr';
+import type { CategoryItem, CategoryListQuery } from '@lobehub/market-sdk';
-import { useClientDataSWR } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
-import { type DiscoverStore } from '@/store/discover';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import type { DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
-import { type StoreSetter } from '@/store/types';
+import type { StoreSetter } from '@/store/types';
+import type { DiscoverMcpDetail, McpListResponse, McpQueryParams } from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+
import {
- type DiscoverMcpDetail,
- type McpListResponse,
- type McpQueryParams,
-} from '@/types/discover';
+ type McpCategoriesParams,
+ mcpCategoriesQueryKey,
+ mcpCategoriesResource,
+ type McpDetailParams,
+ mcpDetailQueryKey,
+ mcpDetailResource,
+ type McpListParams,
+ mcpListQueryKey,
+ mcpListResource,
+} from './projection';
+
+const n = setNamespace('discover/mcp');
+
+/**
+ * Sync flags of a market read, plus the aliases the old SWR hooks returned
+ * (`isLoading` / `mutate`) so a call site only has to move its `data` read to
+ * the matching `mcpSelectors` entry.
+ */
+export interface MCPSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `mcpSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
type Setter = StoreSetter<DiscoverStore>;
+
export const createMCPSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new MCPActionImpl(set, get, _api);
export class MCPActionImpl {
+ readonly #categories;
+ readonly #detail;
+ readonly #get: () => DiscoverStore;
+ readonly #list;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#list = createReplicaSlice(mcpListResource, {
+ actionPrefix: n('list'),
+ get,
+ set,
+ stateKey: 'mcpListReplica',
+ view: recordLens<DiscoverStore, McpListResponse>('mcpListMap'),
+ });
+ this.#detail = createReplicaSlice(mcpDetailResource, {
+ actionPrefix: n('detail'),
+ get,
+ // The market no longer has this server: drop the entry and its persisted
+ // row rather than keep serving the cached copy.
+ isMissing: (detail) => detail === null,
+ set,
+ stateKey: 'mcpDetailReplica',
+ view: recordLens<DiscoverStore, DiscoverMcpDetail>('mcpDetailMap'),
+ });
+ this.#categories = createReplicaSlice(mcpCategoriesResource, {
+ actionPrefix: n('categories'),
+ get,
+ set,
+ stateKey: 'mcpCategoriesReplica',
+ view: recordLens<DiscoverStore, CategoryItem[]>('mcpCategoriesMap'),
+ });
}
- useFetchMcpDetail = ({
- identifier,
- version,
- }: {
- identifier?: string;
- version?: string;
- }): SWRResponse<DiscoverMcpDetail> => {
- const locale = globalHelpers.getCurrentLanguage();
+ #toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string | undefined,
+ hasValue: boolean,
+ active: boolean,
+ ): MCPSyncResult => ({
+ ...sync,
+ // A disabled hook never loads; a settled entry with a value never flashes.
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+ });
- return useClientDataSWR(
- !identifier ? null : discoverKeys.mcpDetail(locale, identifier, version),
- async () => discoverService.getMcpDetail({ identifier: identifier!, version }),
- );
+ /**
+ * The MCP market list of one query. Each (filters Β· page) pair is its own
+ * entry, so the URL-driven pager walks entries instead of appending pages.
+ * Read the rows with `mcpSelectors.mcpList(queryKey)`.
+ */
+ useFetchMcpList = (
+ params: McpQueryParams = {},
+ options: { enabled?: boolean } = {},
+ ): MCPSyncResult => {
+ const { enabled = true } = options;
+ const normalized: McpListParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ page: params.page ? Number(params.page) : 1,
+ pageSize: params.pageSize ? Number(params.pageSize) : 21,
+ };
+ const queryKey = mcpListQueryKey(normalized);
+ const sync = this.#list.useSync(normalized, { enabled });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().mcpListMap[queryKey], enabled);
};
- useFetchMcpList = (params: McpQueryParams): SWRResponse<McpListResponse> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useClientDataSWR(discoverKeys.mcpList(locale, params), async () =>
- discoverService.getMcpList({
- ...params,
- page: params.page ? Number(params.page) : 1,
- pageSize: params.pageSize ? Number(params.pageSize) : 21,
- }),
+ /**
+ * One MCP detail by identifier (with an optional pinned `version`). Read it
+ * with `mcpSelectors.mcpDetail(queryKey)`; `undefined` after the sync settles
+ * means the market has no such identifier β€” or no identifier was given, in
+ * which case the read is disabled and the hook reports no loading.
+ */
+ useFetchMcpDetail = (
+ { identifier, version }: { identifier?: string; version?: string } = {},
+ options: { enabled?: boolean } = {},
+ ): MCPSyncResult => {
+ const { enabled = true } = options;
+ // Without an identifier there is nothing to fetch β€” never load a blank key.
+ const active = enabled && !!identifier;
+ const normalized: McpDetailParams = {
+ identifier: identifier ?? '',
+ locale: globalHelpers.getCurrentLanguage(),
+ version,
+ };
+ const queryKey = mcpDetailQueryKey(normalized);
+ const sync = this.#detail.useSync(normalized, { enabled: active });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().mcpDetailMap[queryKey] !== undefined,
+ active,
);
};
- useMcpCategories = (params: CategoryListQuery): SWRResponse<CategoryItem[]> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useClientDataSWR(
- discoverKeys.mcpCategories(locale, params),
- async () => discoverService.getMcpCategories(params),
- {
- revalidateOnFocus: false,
- },
- );
+ /**
+ * Category counts of one query (the search term). The community sidebar reads
+ * `mcpSelectors.mcpCategories(queryKey)`.
+ */
+ useMcpCategories = (
+ params: CategoryListQuery = {},
+ options: { enabled?: boolean } = {},
+ ): MCPSyncResult => {
+ const { enabled = true } = options;
+ const normalized: McpCategoriesParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ };
+ const queryKey = mcpCategoriesQueryKey(normalized);
+ // Static, persisted counts: like the SWR hook it replaces, a window focus
+ // does not refetch them.
+ const sync = this.#categories.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().mcpCategoriesMap[queryKey], enabled);
};
}
diff --git a/src/store/discover/slices/mcp/initialState.ts b/src/store/discover/slices/mcp/initialState.ts
new file mode 100644
index 00000000000..1a4578e91c4
--- /dev/null
+++ b/src/store/discover/slices/mcp/initialState.ts
@@ -0,0 +1,34 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type { DiscoverMcpDetail, McpListResponse } from '@/types/discover';
+
+/**
+ * Replica views of the MCP market reads, each beside its bookkeeping slot.
+ * The views are plain records keyed by the entry key of the matching resource
+ * (`projection.ts`); components read them through `mcpSelectors`, never
+ * through the fetch hook.
+ */
+export interface MCPSliceState {
+ /** Category counts per query (`mcpCategoriesQueryKey`). */
+ mcpCategoriesMap: Record<string, CategoryItem[]>;
+ /** Replica bookkeeping of `mcpCategoriesMap`. */
+ mcpCategoriesReplica: ReplicaState<CategoryItem[]>;
+ /** MCP detail per identifier (`mcpDetailQueryKey`). */
+ mcpDetailMap: Record<string, DiscoverMcpDetail>;
+ /** Replica bookkeeping of `mcpDetailMap`. */
+ mcpDetailReplica: ReplicaState<DiscoverMcpDetail>;
+ /** MCP list per query (`mcpListQueryKey`). */
+ mcpListMap: Record<string, McpListResponse>;
+ /** Replica bookkeeping of `mcpListMap`. */
+ mcpListReplica: ReplicaState<McpListResponse>;
+}
+
+export const initialMCPSliceState: MCPSliceState = {
+ mcpCategoriesMap: {},
+ mcpCategoriesReplica: createReplicaState(),
+ mcpDetailMap: {},
+ mcpDetailReplica: createReplicaState(),
+ mcpListMap: {},
+ mcpListReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/mcp/projection.ts b/src/store/discover/slices/mcp/projection.ts
new file mode 100644
index 00000000000..ed5c3444f94
--- /dev/null
+++ b/src/store/discover/slices/mcp/projection.ts
@@ -0,0 +1,97 @@
+import type { CategoryItem, CategoryListQuery } from '@lobehub/market-sdk';
+
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import type { DiscoverMcpDetail, McpListResponse, McpQueryParams } from '@/types/discover';
+
+/**
+ * The marketplace MCP reads are **read-only**: no optimistic write, no
+ * cross-copy entity link. What the replica buys here is the first frame β€” the
+ * last confirmed page paints before the network answers β€” and one cache
+ * partition per identity (the `cacheScope`), so switching account or workspace
+ * never serves the previous one's rows.
+ *
+ * Each distinct query is its own entry (`key`), exactly like the SWR key it
+ * replaces: the community list paginates by URL (`?page=N`), so a page flip is
+ * a different entry rather than a `loadMore` of the same one.
+ */
+
+/** Normalized `mcpList` params β€” the shape actually sent to the market endpoint. */
+export interface McpListParams extends Omit<McpQueryParams, 'page' | 'pageSize'> {
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale?: string;
+ page: number;
+ pageSize: number;
+}
+
+/**
+ * Entry key of one MCP list query. Includes the page, because the list pages
+ * through the URL instead of appending pages to one entry.
+ */
+export const mcpListQueryKey = (params: McpListParams): string => stableQueryKey(params);
+
+export interface McpDetailParams {
+ identifier: string;
+ /** Current UI language; the market resolves localized copy server-side. */
+ locale?: string;
+ /** Pinned marketplace version; a different version is a different entry. */
+ version?: string;
+}
+
+/** Entry key of one MCP detail (`identifier` Β· `version`, localized). */
+export const mcpDetailQueryKey = (params: McpDetailParams): string => stableQueryKey(params);
+
+/** Category counts query of the community MCP sidebar (the search term). */
+export type McpCategoriesParams = CategoryListQuery & {
+ /** The old SWR key carried the locale, so a language switch refetches. */
+ locale?: string;
+};
+
+/** Entry key of one category-counts query. */
+export const mcpCategoriesQueryKey = (params: McpCategoriesParams): string =>
+ stableQueryKey(params);
+
+/**
+ * MCP market list, one entry per query (`mcpListMap[queryKey]`). The response
+ * already carries everything a row reader needs (`items`, `currentPage`,
+ * `pageSize`, `totalCount`), so it is stored as-is.
+ */
+export const mcpListResource = defineReplica<McpListParams, McpListResponse>({
+ fetcher: (params) => discoverService.getMcpList(params),
+ key: mcpListQueryKey,
+ name: 'mcpList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One MCP detail by identifier (`mcpDetailMap[key]`). The service answers
+ * `undefined` for an identifier the market no longer has; the fetcher turns
+ * that into `null` so the slice's `isMissing` drops the entry (memory and
+ * persisted row) instead of letting the engine skip the write and keep painting
+ * a stale cached copy. The page then reaches "not found" once the sync settles.
+ */
+export const mcpDetailResource = defineReplica<
+ McpDetailParams,
+ DiscoverMcpDetail,
+ DiscoverMcpDetail | null
+>({
+ fetcher: async (params) => (await discoverService.getMcpDetail(params)) ?? null,
+ key: mcpDetailQueryKey,
+ name: 'mcpDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Category counts of one query (`mcpCategoriesMap[queryKey]`). Small and read
+ * on almost every community MCP screen, so localStorage keeps the first frame
+ * populated instead of flashing an empty sidebar.
+ */
+export const mcpCategoriesResource = defineReplica<McpCategoriesParams, CategoryItem[]>({
+ fetcher: (params) => discoverService.getMcpCategories(params),
+ key: mcpCategoriesQueryKey,
+ name: 'mcpCategories',
+ storage: 'localStorage',
+ version: 1,
+});