Skip to content

Commit d3ccb4a

Browse files
committed
Fix useSyncExternalStore by returning a stable store from ManagedToolsState.getStore() and resolving the store once in useManagedTools for subscribe and getSnapshot.
1 parent 3f8ee1c commit d3ccb4a

2 files changed

Lines changed: 8 additions & 6 deletions

File tree

core/mcp/state/managedToolsState.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ export class ManagedToolsState {
2424
private readonly store = createStore<{ tools: Tool[] }>()((_set) => ({
2525
tools: [],
2626
}));
27+
private readonly readOnlyStore: ManagedToolsReadOnlyStore = {
28+
getState: () => this.store.getState(),
29+
subscribe: (listener) => this.store.subscribe(listener),
30+
};
2731
private client: InspectorClient | null = null;
2832
private unsubscribe: (() => void) | null = null;
2933
private _metadata: Record<string, string> | undefined = undefined;
@@ -56,10 +60,7 @@ export class ManagedToolsState {
5660

5761
/** Read-only store for subscription (e.g. useStore(manager.getStore(), s => s.tools)). */
5862
getStore(): ManagedToolsReadOnlyStore {
59-
return {
60-
getState: () => this.store.getState(),
61-
subscribe: (listener) => this.store.subscribe(listener),
62-
};
63+
return this.readOnlyStore;
6364
}
6465

6566
getTools(): Tool[] {

core/react/useManagedTools.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ const NOOP_SUBSCRIBE = () => () => {};
1717
export function useManagedTools(
1818
managedToolsState: ManagedToolsState | null | undefined,
1919
): UseManagedToolsResult {
20+
const store = managedToolsState?.getStore() ?? null;
2021
const tools = useSyncExternalStore(
21-
managedToolsState?.getStore()?.subscribe ?? NOOP_SUBSCRIBE,
22-
() => managedToolsState?.getStore()?.getState()?.tools ?? EMPTY_TOOLS,
22+
store?.subscribe ?? NOOP_SUBSCRIBE,
23+
store ? () => store.getState().tools : () => EMPTY_TOOLS,
2324
);
2425

2526
const refresh = useCallback(

0 commit comments

Comments
 (0)