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(mcp): retry idempotent api reads that lose the connection (#105663)

posthog[bot]c83c61e13e11
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 09f59cd16c53..f321011038ba 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -8,6 +8,7 @@ import {
PostHogApiError,
PostHogPermissionError,
PostHogRateLimitError,
+ PostHogTransportError,
PostHogValidationError,
} from '@/lib/errors'
import { getSearchParamsFromRecord, sanitizeHeaders, sanitizeHeaderValue } from '@/lib/utils.js'
@@ -38,6 +39,26 @@ const RATE_LIMIT_MAX_RETRIES = 3
const RATE_LIMIT_BASE_BACKOFF_MS = 2000
const RATE_LIMIT_TOTAL_WAIT_BUDGET_MS = 30_000
+// Transport retry policy. A connection that fails or drops before a response
+// arrives is transient, and a safe method applied nothing upstream, so the
+// client repeats it instead of handing the agent a failure it can only fix by
+// sending the same call again. The budget stays small: a tool call holds the
+// MCP client's request open while it waits, and a host that is truly down
+// must surface fast.
+const TRANSPORT_MAX_RETRIES = 2
+const TRANSPORT_BASE_BACKOFF_MS = 250
+
+/** Methods that carry no upstream effect, so a repeat after a failed
+ * connection cannot apply the same work twice. */
+const SAFE_HTTP_METHODS = new Set(['GET', 'HEAD'])
+
+/** An aborted request is the caller's own timeout or cancellation, so a retry
+ * would only wait for a deadline that has already passed. Everything else
+ * thrown out of `fetch` or a body read is a transport fault. */
+function isAbortError(error: unknown): boolean {
+ return error instanceof Error && error.name === 'AbortError'
+}
+
// Default overall timeout for an SSE stream (wall-clock cap from connect to close).
// Sized to comfortably cover the slowest known caller (session summarization, ~5 min
// average) with headroom for cold-cache LLM calls.
@@ -566,77 +587,101 @@ export class ApiClient {
private async fetchJson<T>(url: string, options?: RequestInit): Promise<Result<T>> {
const method = options?.method ?? 'GET'
let waitBudgetMs = RATE_LIMIT_TOTAL_WAIT_BUDGET_MS
+ let rateLimitRetries = 0
+ let transportRetries = 0
- for (let attempt = 0; attempt <= RATE_LIMIT_MAX_RETRIES; attempt++) {
+ for (;;) {
+ let response: Response
+ let bodyText: string
try {
- const response = await this.fetch(url, options)
-
- if (response.status === 429) {
- const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get('Retry-After'))
- const rateLimitFailure = async (): Promise<Result<T>> => ({
+ response = await this.fetch(url, options)
+ // Read the body inside the same guard as the connection: a stream cut
+ // short throws here, and that failure is transport, not a bad response.
+ bodyText = await response.text()
+ } catch (error) {
+ const isSafeMethod = SAFE_HTTP_METHODS.has(method.toUpperCase())
+ const canRetry = !isAbortError(error) && isSafeMethod && transportRetries < TRANSPORT_MAX_RETRIES
+ if (!canRetry) {
+ console.error(`[API] Transport failure on ${method} ${url}: ${String(error)}`)
+ return {
success: false,
- error: new PostHogRateLimitError({
- body: await response.text(),
+ error: new PostHogTransportError({
url,
method,
- retryAfterSeconds,
+ attempts: transportRetries + 1,
+ retryable: isSafeMethod,
+ cause: error,
}),
- })
-
- if (attempt === RATE_LIMIT_MAX_RETRIES) {
- console.error(`[API] Rate limit (429) retries exhausted on ${method} ${url}`)
- return rateLimitFailure()
}
+ }
+ // Equal jitter so concurrent failures do not retry in lockstep.
+ const backoffMs = TRANSPORT_BASE_BACKOFF_MS * 2 ** transportRetries
+ const delayMs = backoffMs / 2 + Math.random() * (backoffMs / 2)
+ transportRetries++
+ console.warn(
+ `[API] Transport failure on ${method} ${url}: ${String(error)}. Retrying in ${Math.round(delayMs)}ms (attempt ${transportRetries}/${TRANSPORT_MAX_RETRIES})`
+ )
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ continue
+ }
- // DRF rejects throttled requests before the view executes,
- // so retrying is safe for mutations too.
- const backoffMs = RATE_LIMIT_BASE_BACKOFF_MS * 2 ** attempt
- const delayMs =
- retryAfterSeconds !== null
- ? retryAfterSeconds * 1000
- : // Equal jitter so concurrent 429s don't retry in lockstep.
- backoffMs / 2 + Math.random() * (backoffMs / 2)
-
- if (delayMs > waitBudgetMs) {
- console.warn(
- `[API] Rate limited (429) on ${method} ${url}. Requested wait of ${Math.round(delayMs / 1000)}s exceeds the remaining ${Math.round(waitBudgetMs / 1000)}s retry budget; not retrying.`
- )
- return rateLimitFailure()
- }
+ if (response.status === 429) {
+ const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get('Retry-After'))
+ const rateLimitFailure = (): Result<T> => ({
+ success: false,
+ error: new PostHogRateLimitError({
+ body: bodyText,
+ url,
+ method,
+ retryAfterSeconds,
+ }),
+ })
+
+ if (rateLimitRetries === RATE_LIMIT_MAX_RETRIES) {
+ console.error(`[API] Rate limit (429) retries exhausted on ${method} ${url}`)
+ return rateLimitFailure()
+ }
- waitBudgetMs -= delayMs
+ // DRF rejects throttled requests before the view executes,
+ // so retrying is safe for mutations too.
+ const backoffMs = RATE_LIMIT_BASE_BACKOFF_MS * 2 ** rateLimitRetries
+ const delayMs =
+ retryAfterSeconds !== null
+ ? retryAfterSeconds * 1000
+ : // Equal jitter so concurrent 429s don't retry in lockstep.
+ backoffMs / 2 + Math.random() * (backoffMs / 2)
+
+ if (delayMs > waitBudgetMs) {
console.warn(
- `[API] Rate limited (429) on ${method} ${url}. Retrying in ${Math.round(delayMs)}ms (attempt ${attempt + 1}/${RATE_LIMIT_MAX_RETRIES})`
+ `[API] Rate limited (429) on ${method} ${url}. Requested wait of ${Math.round(delayMs / 1000)}s exceeds the remaining ${Math.round(waitBudgetMs / 1000)}s retry budget; not retrying.`
)
- await new Promise((resolve) => setTimeout(resolve, delayMs))
- continue
+ return rateLimitFailure()
}
- if (!response.ok) {
- const errorText = await response.text()
+ waitBudgetMs -= delayMs
+ rateLimitRetries++
+ console.warn(
+ `[API] Rate limited (429) on ${method} ${url}. Retrying in ${Math.round(delayMs)}ms (attempt ${rateLimitRetries}/${RATE_LIMIT_MAX_RETRIES})`
+ )
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ continue
+ }
- throw this.buildApiError(response, errorText, url, method)
- }
+ if (!response.ok) {
+ return { success: false, error: this.buildApiError(response, bodyText, url, method) }
+ }
- const rawText = await response.text()
- if (!rawText) {
- return { success: true, data: {} as T }
- }
+ if (!bodyText) {
+ return { success: true, data: {} as T }
+ }
- try {
- const rawData = JSON.parse(rawText)
- return { success: true, data: rawData as T }
- } catch {
- return { success: true, data: rawText as T }
- }
- } catch (error) {
- return { success: false, error: error as Error }
+ try {
+ const rawData = JSON.parse(bodyText)
+ return { success: true, data: rawData as T }
+ } catch {
+ return { success: true, data: bodyText as T }
}
}
-
- // Unreachable: the final attempt always returns above, but TypeScript
- // can't prove the loop is exhaustive.
- return { success: false, error: new Error('Unexpected rate limit retry state') }
}
organizations(): Endpoint {
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index a049732fbda8..a7731d92c529 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -262,6 +262,48 @@ export class PostHogRateLimitError extends PostHogApiError {
}
}
+export interface PostHogTransportErrorOptions {
+ url: string
+ method: string
+ attempts: number
+ /**
+ * Whether another attempt is safe. True only for a method that applies
+ * nothing upstream. A failed write can still have reached the handler, so
+ * a repeat of one could apply the same work twice.
+ */
+ retryable: boolean
+ cause: unknown
+}
+
+/**
+ * Thrown when a request to the PostHog API produced no usable response: the
+ * connection failed, dropped, or the body read was cut short. On a retryable
+ * method the client already repeated the call, so this error means the retry
+ * budget is spent.
+ */
+export class PostHogTransportError extends Error {
+ public readonly retryable: boolean
+ public readonly url: string
+ public readonly method: string
+ public readonly attempts: number
+
+ constructor(options: PostHogTransportErrorOptions) {
+ const reason = options.cause instanceof Error ? options.cause.message : String(options.cause)
+ const advice = options.retryable
+ ? 'The request applies nothing upstream, so it is safe to retry.'
+ : 'The request may have been applied upstream, so check the state before you send it again.'
+ super(
+ `Could not reach the PostHog API on ${options.method} ${requestPath(options.url)} after ${options.attempts} attempt${options.attempts === 1 ? '' : 's'}: ${reason}. ${advice}`
+ )
+ this.name = 'PostHogTransportError'
+ this.retryable = options.retryable
+ this.url = options.url
+ this.method = options.method
+ this.attempts = options.attempts
+ ;(this as Error & { cause?: unknown }).cause = options.cause
+ }
+}
+
/**
* Parses a Retry-After header into whole seconds. Returns null for missing
* headers, HTTP-date values, and bogus negatives.
diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.ts
index 89e1705558fc..e507b8157359 100644
--- a/services/mcp/tests/unit/api-client.test.ts
+++ b/services/mcp/tests/unit/api-client.test.ts
@@ -1,7 +1,11 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiClient } from '@/api/client'
import { USER_AGENT, getUserAgent } from '@/lib/constants'
+import { PostHogTransportError } from '@/lib/errors'
+import { getToolByName } from '@/shared/test-utils'
+import { GENERATED_TOOLS } from '@/tools/generated/skills'
+import type { Context } from '@/tools/types'
describe('ApiClient', () => {
it('should create ApiClient with required config', () => {
@@ -428,4 +432,124 @@ describe('ApiClient', () => {
expect(query).not.toHaveProperty('orderBy')
})
})
+
+ // A scout reads its required skill pages before it can start, so a dropped
+ // connection on one of those reads costs the whole run a manual repeat.
+ // Safe methods apply nothing upstream, so the client repeats them itself.
+ describe('transient transport failures', () => {
+ const networkError = (): Error => new TypeError('fetch failed')
+
+ const stubFetch = (...outcomes: (Response | Error)[]): ReturnType<typeof vi.fn> => {
+ const mockFetch = vi.fn()
+ for (const outcome of outcomes) {
+ if (outcome instanceof Error) {
+ mockFetch.mockRejectedValueOnce(outcome)
+ } else {
+ mockFetch.mockResolvedValueOnce(outcome)
+ }
+ }
+ mockFetch.mockImplementation(() => Promise.reject(networkError()))
+ vi.stubGlobal('fetch', mockFetch)
+ return mockFetch
+ }
+
+ const skillContext = (): Context =>
+ ({
+ api: new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' }),
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },
+ }) as unknown as Context
+
+ /** Drains the backoff sleeps, then returns the value or the thrown error. */
+ const settle = async (promise: Promise<unknown>): Promise<unknown> => {
+ const outcome = promise.then(
+ (value) => value,
+ (error) => error
+ )
+ await vi.runAllTimersAsync()
+ return outcome
+ }
+
+ const runTool = (name: string, params: Record<string, unknown>): Promise<unknown> =>
+ settle(getToolByName(GENERATED_TOOLS, name).handler(skillContext(), params))
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ it('retries a paginated skill-get page that fails to connect', async () => {
+ const mockFetch = stubFetch(
+ networkError(),
+ new Response(JSON.stringify({ name: 'skills-store', body: 'page two' }), { status: 200 })
+ )
+
+ const result = await runTool('skill-get', {
+ skill_name: 'skills-store',
+ body_offset: 20000,
+ body_length: 20000,
+ })
+
+ expect(result).toEqual({ name: 'skills-store', body: 'page two' })
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ const [retriedUrl] = mockFetch.mock.calls[1]!
+ expect(retriedUrl).toContain('/llm_skills/name/skills-store/')
+ expect(retriedUrl).toContain('body_offset=20000')
+ })
+
+ it('retries a skill-file-get read whose body stream is cut short', async () => {
+ const truncated = new Response('{}', { status: 200 })
+ vi.spyOn(truncated, 'text').mockRejectedValue(new TypeError('Network connection lost'))
+ const mockFetch = stubFetch(
+ truncated,
+ new Response(JSON.stringify({ path: 'references/limits.md' }), { status: 200 })
+ )
+
+ const result = await runTool('skill-file-get', {
+ skill_name: 'skills-store',
+ file_path: 'references/limits.md',
+ })
+
+ expect(result).toEqual({ path: 'references/limits.md' })
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it('reports a retryable failure once the retry budget is spent', async () => {
+ const mockFetch = stubFetch()
+
+ const error = await settle(
+ getToolByName(GENERATED_TOOLS, 'skill-file-get').handler(skillContext(), {
+ skill_name: 'skills-store',
+ file_path: 'SKILL.md',
+ })
+ )
+
+ expect(error).toBeInstanceOf(PostHogTransportError)
+ const transportError = error as PostHogTransportError
+ expect(transportError.retryable).toBe(true)
+ expect(transportError.attempts).toBe(3)
+ expect(transportError.message).toContain('safe to retry')
+ expect(mockFetch).toHaveBeenCalledTimes(3)
+ })
+
+ it('does not repeat a write whose outcome is unknown', async () => {
+ const mockFetch = stubFetch()
+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })
+
+ const error = await settle(client.request({ method: 'POST', path: '/api/projects/17/llm_skills/' }))
+
+ expect(error).toBeInstanceOf(PostHogTransportError)
+ // The write may have reached the handler before the connection died,
+ // so telling the agent to send it again invites a double apply.
+ expect((error as PostHogTransportError).retryable).toBe(false)
+ expect((error as PostHogTransportError).message).toContain('may have been applied upstream')
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+ })
})