Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): retry MCP tool listing with backoff instead of looping (#86790)

Chris Volzer467d494ffb9d
diff --git a/products/desktop/packages/core/src/mcp-servers/toolRefresh.test.ts b/products/desktop/packages/core/src/mcp-servers/toolRefresh.test.ts
index 54f1214d376c..a71e9136d5b8 100644
--- a/products/desktop/packages/core/src/mcp-servers/toolRefresh.test.ts
+++ b/products/desktop/packages/core/src/mcp-servers/toolRefresh.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
-import { type AutoRefreshState, shouldAutoRefreshTools } from "./toolRefresh";
+import {
+ type AutoRefreshState,
+ shouldAutoRefreshTools,
+ shouldRetryAutoRefresh,
+} from "./toolRefresh";
function state(overrides: Partial<AutoRefreshState> = {}): AutoRefreshState {
return {
@@ -46,3 +50,14 @@ describe("shouldAutoRefreshTools", () => {
expect(shouldAutoRefreshTools(state({ refreshPending: true }))).toBe(false);
});
});
+
+describe("shouldRetryAutoRefresh", () => {
+ it.each([
+ ["a silent refresh after its first failure", 0, true, true],
+ ["a silent refresh after its second failure", 1, true, true],
+ ["a silent refresh once the retry budget is spent", 2, true, false],
+ ["a manual refresh, which reports its first failure", 0, false, false],
+ ])("%s retries: %s", (_label, failureCount, silent, expected) => {
+ expect(shouldRetryAutoRefresh(failureCount, silent)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/core/src/mcp-servers/toolRefresh.ts b/products/desktop/packages/core/src/mcp-servers/toolRefresh.ts
index ae5a7ed6642c..66edc676a3e1 100644
--- a/products/desktop/packages/core/src/mcp-servers/toolRefresh.ts
+++ b/products/desktop/packages/core/src/mcp-servers/toolRefresh.ts
@@ -16,3 +16,26 @@ export function shouldAutoRefreshTools(state: AutoRefreshState): boolean {
if (state.refreshPending) return false;
return true;
}
+
+/**
+ * A silent auto-refresh retries a failed listing this many times before giving
+ * up for the mount, so a flaky or rate-limited upstream gets a few spaced
+ * attempts and a broken one gets a bounded number of requests.
+ */
+export const AUTO_REFRESH_MAX_RETRIES = 2;
+
+/** Exponential backoff between silent auto-refresh retries: 1s, then 2s. */
+export function autoRefreshRetryDelayMs(failureCount: number): number {
+ return 1000 * 2 ** failureCount;
+}
+
+/**
+ * Only the silent auto-refresh retries. A manual refresh reports its first
+ * failure so the user is not left waiting behind a backoff.
+ */
+export function shouldRetryAutoRefresh(
+ failureCount: number,
+ silent: boolean,
+): boolean {
+ return silent && failureCount < AUTO_REFRESH_MAX_RETRIES;
+}
diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.test.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.test.tsx
index 4df5ad8aa03a..94813940cc9b 100644
--- a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.test.tsx
+++ b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.test.tsx
@@ -27,6 +27,14 @@ vi.mock("@posthog/ui/primitives/toast", () => ({
toast: { error: vi.fn() },
}));
+// Keep the real retry budget but collapse the backoff so the tests stay fast.
+vi.mock("@posthog/core/mcp-servers/toolRefresh", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@posthog/core/mcp-servers/toolRefresh")
+ >()),
+ autoRefreshRetryDelayMs: () => 5,
+}));
+
import { toast } from "@posthog/ui/primitives/toast";
import {
@@ -149,9 +157,17 @@ describe("useGatewayToolPolicies", () => {
expect(mocks.refreshTools).not.toHaveBeenCalled();
});
- it("retries on a later mount when the listing fails", async () => {
+ it("retries a failed listing a bounded number of times, then stops until a later mount", async () => {
mocks.getPolicies.mockResolvedValue([]);
- mocks.refreshTools.mockRejectedValue(new Error("upstream down"));
+ // Reject on a later tick so the pending state renders first, as a real
+ // request does. An immediate rejection collapses the pending and error
+ // renders into one and hides the re-fire this guards against.
+ mocks.refreshTools.mockImplementation(
+ () =>
+ new Promise((_resolve, reject) =>
+ setTimeout(() => reject(new Error("upstream down")), 5),
+ ),
+ );
const first = renderHook(
() =>
@@ -160,10 +176,16 @@ describe("useGatewayToolPolicies", () => {
}),
{ wrapper },
);
- await waitFor(() => expect(mocks.refreshTools).toHaveBeenCalledTimes(1));
- await waitFor(() =>
- expect(first.result.current.refreshPending).toBe(false),
- );
+ // One attempt plus AUTO_REFRESH_MAX_RETRIES retries.
+ await waitFor(() => expect(mocks.refreshTools).toHaveBeenCalledTimes(3));
+ // Long enough for the last failure to settle and re-run the discovery
+ // effect; a fourth listing here is the retry storm this guards against.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ });
+ expect(first.result.current.refreshPending).toBe(false);
+ expect(mocks.refreshTools).toHaveBeenCalledTimes(3);
+ expect(toast.error).not.toHaveBeenCalled();
first.unmount();
renderHook(
@@ -174,8 +196,33 @@ describe("useGatewayToolPolicies", () => {
{ wrapper },
);
- await waitFor(() => expect(mocks.refreshTools).toHaveBeenCalledTimes(2));
- expect(toast.error).not.toHaveBeenCalled();
+ // A later mount gets one more bounded batch, not an open-ended one.
+ await waitFor(() => expect(mocks.refreshTools).toHaveBeenCalledTimes(6));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ });
+ expect(mocks.refreshTools).toHaveBeenCalledTimes(6);
+ });
+
+ it("reports a failed manual refresh at once instead of retrying", async () => {
+ mocks.getPolicies.mockResolvedValue([policy("approved")]);
+ mocks.refreshTools.mockRejectedValue(new Error("upstream down"));
+
+ const { result } = renderHook(
+ () =>
+ useGatewayToolPolicies(serverId, YOU_SCOPE, {
+ autoDiscoverWith: "inst-1",
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.policiesLoading).toBe(false));
+
+ act(() => result.current.refresh("inst-1"));
+
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith("upstream down"),
+ );
+ expect(mocks.refreshTools).toHaveBeenCalledTimes(1);
});
});
});
diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.ts b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.ts
index 220206e52c3f..4f91ae755c2f 100644
--- a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.ts
+++ b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useGatewayToolPolicies.ts
@@ -6,7 +6,11 @@ import {
isAgentPolicyState,
isPolicyStateAllowedByCeiling,
} from "@posthog/core/mcp-gateway/gatewayServers";
-import { shouldAutoRefreshTools } from "@posthog/core/mcp-servers/toolRefresh";
+import {
+ autoRefreshRetryDelayMs,
+ shouldAutoRefreshTools,
+ shouldRetryAutoRefresh,
+} from "@posthog/core/mcp-servers/toolRefresh";
import {
type GatewayPolicyScope,
gatewayKeys,
@@ -127,10 +131,16 @@ export function useGatewayToolPolicies(
// Re-lists tools from the upstream server via the caller's installation.
const silentRefreshRef = useRef(false);
+ const attemptedThisMount = useRef(new Set<string>());
const refreshMutation = useAuthenticatedMutation(
(client, installationId: string) =>
client.refreshMcpInstallationTools(installationId),
{
+ // A silent listing retries a few times with backoff before it gives up;
+ // a manual refresh reports its first failure.
+ retry: (failureCount) =>
+ shouldRetryAutoRefresh(failureCount, silentRefreshRef.current),
+ retryDelay: autoRefreshRetryDelayMs,
onSuccess: () => {
silentRefreshRef.current = false;
queryClient.invalidateQueries({
@@ -166,11 +176,18 @@ export function useGatewayToolPolicies(
installationId: autoDiscoverWith,
isLoading,
toolsLength: policyCount,
- alreadyRefreshed: autoDiscovered.has(autoDiscoverWith),
+ // The module-level marker is dropped when a listing fails so a later
+ // mount retries; the per-mount one is not, because this effect re-runs
+ // when the failed mutation settles and would otherwise fire again at
+ // once, looping against the upstream server until it rate-limits.
+ alreadyRefreshed:
+ autoDiscovered.has(autoDiscoverWith) ||
+ attemptedThisMount.current.has(autoDiscoverWith),
refreshPending: refreshIsPending,
});
if (!fire) return;
autoDiscovered.add(autoDiscoverWith);
+ attemptedThisMount.current.add(autoDiscoverWith);
silentRefreshRef.current = true;
refreshMutate(autoDiscoverWith);
}, [
diff --git a/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.test.tsx b/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.test.tsx
index dcdcf07eb40a..8c0830d56f7e 100644
--- a/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.test.tsx
+++ b/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.test.tsx
@@ -37,6 +37,16 @@ vi.mock("@posthog/ui/primitives/toast", () => ({
},
}));
+// Keep the real retry budget but collapse the backoff so the tests stay fast.
+vi.mock("@posthog/core/mcp-servers/toolRefresh", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@posthog/core/mcp-servers/toolRefresh")
+ >()),
+ autoRefreshRetryDelayMs: () => 5,
+}));
+
+import { toast } from "@posthog/ui/primitives/toast";
+
import { useMcpInstallationTools } from "./useMcpInstallationTools";
function wrapper({ children }: { children: ReactNode }) {
@@ -144,3 +154,73 @@ describe("useMcpInstallationTools setBulkApproval", () => {
);
});
});
+
+describe("useMcpInstallationTools auto-refresh", () => {
+ let queryClient: QueryClient;
+
+ function stableWrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ it("retries a failed silent refresh a bounded number of times, then stops until a later mount", async () => {
+ mockClient.getMcpInstallationTools.mockResolvedValue([]);
+ // Reject on a later tick so the pending state renders first, as a real
+ // request does. An immediate rejection collapses the pending and error
+ // renders into one and hides the re-fire this guards against.
+ mockClient.refreshMcpInstallationTools.mockImplementation(
+ () =>
+ new Promise((_resolve, reject) =>
+ setTimeout(() => reject(new Error("upstream down")), 5),
+ ),
+ );
+
+ const first = renderHook(
+ () =>
+ useMcpInstallationTools("inst-auto-refresh", {
+ autoRefreshIfEmpty: true,
+ }),
+ { wrapper: stableWrapper },
+ );
+ // One attempt plus AUTO_REFRESH_MAX_RETRIES retries.
+ await waitFor(() =>
+ expect(mockClient.refreshMcpInstallationTools).toHaveBeenCalledTimes(3),
+ );
+ // Long enough for the last failure to settle and re-run the auto-refresh
+ // effect; a fourth listing here is the retry storm this guards against.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ });
+ expect(first.result.current.refreshPending).toBe(false);
+ expect(mockClient.refreshMcpInstallationTools).toHaveBeenCalledTimes(3);
+ expect(toast.error).not.toHaveBeenCalled();
+ first.unmount();
+
+ renderHook(
+ () =>
+ useMcpInstallationTools("inst-auto-refresh", {
+ autoRefreshIfEmpty: true,
+ }),
+ { wrapper: stableWrapper },
+ );
+ // A later mount gets one more bounded batch, not an open-ended one.
+ await waitFor(() =>
+ expect(mockClient.refreshMcpInstallationTools).toHaveBeenCalledTimes(6),
+ );
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ });
+ expect(mockClient.refreshMcpInstallationTools).toHaveBeenCalledTimes(6);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.ts b/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.ts
index 6f6824950e74..e6d8393a750e 100644
--- a/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.ts
+++ b/products/desktop/packages/ui/src/features/mcp-servers/hooks/useMcpInstallationTools.ts
@@ -4,7 +4,11 @@ import type {
} from "@posthog/api-client/posthog-client";
import { isPolicyStateAllowedByCeiling } from "@posthog/core/mcp-gateway/gatewayServers";
import { dispatchBulkApproval } from "@posthog/core/mcp-servers/toolBulk";
-import { shouldAutoRefreshTools } from "@posthog/core/mcp-servers/toolRefresh";
+import {
+ autoRefreshRetryDelayMs,
+ shouldAutoRefreshTools,
+ shouldRetryAutoRefresh,
+} from "@posthog/core/mcp-servers/toolRefresh";
import { useHostTRPC } from "@posthog/host-router/react";
import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";
import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
@@ -119,6 +123,7 @@ export function useMcpInstallationTools(
);
const silentRefreshRef = useRef(false);
+ const attemptedThisMount = useRef(new Set<string>());
const refreshMutation = useAuthenticatedMutation(
(client) => {
@@ -128,6 +133,11 @@ export function useMcpInstallationTools(
return client.refreshMcpInstallationTools(installationId);
},
{
+ // A silent listing retries a few times with backoff before it gives up;
+ // a manual refresh reports its first failure.
+ retry: (failureCount) =>
+ shouldRetryAutoRefresh(failureCount, silentRefreshRef.current),
+ retryDelay: autoRefreshRetryDelayMs,
onSuccess: () => {
const silent = silentRefreshRef.current;
silentRefreshRef.current = false;
@@ -160,11 +170,18 @@ export function useMcpInstallationTools(
installationId,
isLoading,
toolsLength,
- alreadyRefreshed: autoRefreshedInstallations.has(installationId),
+ // The module-level marker is dropped when a listing fails so a later
+ // mount retries; the per-mount one is not, because this effect re-runs
+ // when the failed mutation settles and would otherwise fire again at
+ // once, looping against the upstream server until it rate-limits.
+ alreadyRefreshed:
+ autoRefreshedInstallations.has(installationId) ||
+ attemptedThisMount.current.has(installationId),
refreshPending: refreshIsPending,
});
if (!fire) return;
autoRefreshedInstallations.add(installationId);
+ attemptedThisMount.current.add(installationId);
silentRefreshRef.current = true;
refreshMutate(undefined);
}, [