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): preserve retry-after hints on 503 responses (#109753)

Vasco de Krijger9265009f5bbb
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 9fa58810b259..db193889809a 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -68,6 +68,11 @@ For lookup tools, return an explicit normal result when absence is an expected a
checking whether an event's session has a recording). Keep invalid inputs, permission failures, and
server failures as tool errors so MCP Analytics measures genuine failures rather than routine misses.
+Preserve API errors with `throw result.error` or `wrapError(message, result.error)` from `@/lib/errors`.
+Copying only the message loses the HTTP status and retry guidance.
+For HTTP 503 responses, the shared client passes a numeric `Retry-After` value to the agent as a minimum wait.
+It does not retry these requests automatically.
+
## SQL-first data retrieval
The MCP server instructs the agent to read data through a unified HogQL interface
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 540cd25edc07..b9e0f7ea9758 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -361,6 +361,8 @@ export class ApiClient {
body: errorText,
url,
method: opts.method,
+ retryAfterSeconds:
+ response.status === 503 ? parseRetryAfterSeconds(response.headers.get('Retry-After')) : null,
})
}
return (await response.text()) as T
@@ -605,6 +607,8 @@ export class ApiClient {
body: errorText,
url,
method,
+ retryAfterSeconds:
+ response.status === 503 ? parseRetryAfterSeconds(response.headers.get('Retry-After')) : null,
})
}
@@ -809,7 +813,7 @@ export class ApiClient {
const response = await this.fetch(url)
if (!response.ok) {
- throw new Error(`Failed to fetch property definitions: ${response.statusText}`)
+ throw this.buildApiError(response, await response.text(), url, 'GET')
}
const data = (await response.json()) as { results: ApiPropertyDefinition[] }
@@ -845,7 +849,7 @@ export class ApiClient {
const response = await this.fetch(requestUrl)
if (!response.ok) {
- throw new Error(`Failed to fetch event definitions: ${response.statusText}`)
+ throw this.buildApiError(response, await response.text(), requestUrl, 'GET')
}
const data = (await response.json()) as { results: ApiEventDefinition[] }
@@ -907,7 +911,7 @@ export class ApiClient {
}
if (!findResponse.ok) {
- throw new Error(`Failed to find event definition: ${findResponse.statusText}`)
+ throw this.buildApiError(findResponse, await findResponse.text(), findUrl, 'GET')
}
const eventDef = (await findResponse.json()) as ApiEventDefinition
@@ -921,7 +925,7 @@ export class ApiClient {
})
if (!updateResponse.ok) {
- throw new Error(`Failed to update event definition: ${updateResponse.statusText}`)
+ throw this.buildApiError(updateResponse, await updateResponse.text(), updateUrl, 'PATCH')
}
const responseData = (await updateResponse.json()) as ApiEventDefinition
@@ -965,7 +969,7 @@ export class ApiClient {
const findResponse = await this.fetch(findUrl)
if (!findResponse.ok) {
- throw new Error(`Failed to find property definition: ${findResponse.statusText}`)
+ throw this.buildApiError(findResponse, await findResponse.text(), findUrl, 'GET')
}
const findData = (await findResponse.json()) as { results: ApiPropertyDefinition[] }
@@ -988,7 +992,7 @@ export class ApiClient {
})
if (!updateResponse.ok) {
- throw new Error(`Failed to update property definition: ${updateResponse.statusText}`)
+ throw this.buildApiError(updateResponse, await updateResponse.text(), updateUrl, 'PATCH')
}
const responseData = (await updateResponse.json()) as ApiPropertyDefinition
@@ -1317,16 +1321,14 @@ export class ApiClient {
insightId: number
}): Promise<Result<{ success: boolean; message: string }>> => {
try {
- const response = await this.fetch(
- `${this.baseUrl}/api/projects/${projectId}/insights/${insightId}/`,
- {
- method: 'PATCH',
- body: JSON.stringify({ deleted: true }),
- }
- )
+ const url = `${this.baseUrl}/api/projects/${projectId}/insights/${insightId}/`
+ const response = await this.fetch(url, {
+ method: 'PATCH',
+ body: JSON.stringify({ deleted: true }),
+ })
if (!response.ok) {
- throw new Error(`Failed to delete insight: ${response.statusText}`)
+ throw this.buildApiError(response, await response.text(), url, 'PATCH')
}
return {
@@ -1683,7 +1685,7 @@ export class ApiClient {
async getGroupTypes(projectId: string): Promise<GroupType[]> {
const result = await this.fetchJson<GroupType[]>(`${this.baseUrl}/api/projects/${projectId}/groups_types/`)
if (!result.success) {
- throw new Error(result.error.message)
+ throw result.error
}
return result.data
}
@@ -1694,7 +1696,7 @@ export class ApiClient {
`${this.baseUrl}/api/projects/${projectId}/mcp_server_installations/available_tools/`
)
if (!result.success) {
- throw new Error(result.error.message)
+ throw result.error
}
return result.data
}
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index cbf345632801..246b0aea8908 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -191,6 +191,7 @@ export interface PostHogApiErrorOptions {
url: string
method: string
message?: string
+ retryAfterSeconds?: number | null
}
/**
@@ -211,6 +212,7 @@ export class PostHogApiError extends Error {
public readonly body: string
public readonly url: string
public readonly method: string
+ public readonly retryAfterSeconds: number | null
constructor(options: PostHogApiErrorOptions) {
super(options.message ?? buildDefaultApiErrorMessage(options))
@@ -220,6 +222,7 @@ export class PostHogApiError extends Error {
this.body = options.body
this.url = options.url
this.method = options.method
+ this.retryAfterSeconds = options.retryAfterSeconds ?? null
}
}
@@ -247,14 +250,10 @@ export interface PostHogRateLimitErrorOptions {
}
/**
- * Thrown when the PostHog API responds with HTTP 429. Never retried inside the
- * MCP server: sleeping here keeps the client's request open and lets pending
- * work pile up behind it, so the rate limit is surfaced immediately with the
- * server's Retry-After hint and the client decides when to retry.
+ * Thrown when an HTTP 429 reaches the caller, including after the JSON client's
+ * bounded retries. Preserves the server's Retry-After hint for the next attempt.
*/
export class PostHogRateLimitError extends PostHogApiError {
- public readonly retryAfterSeconds: number | null
-
constructor(options: PostHogRateLimitErrorOptions) {
const retryHint = options.retryAfterSeconds !== null ? ` Retry after ${options.retryAfterSeconds} seconds.` : ''
super({
@@ -263,10 +262,10 @@ export class PostHogRateLimitError extends PostHogApiError {
body: options.body,
url: options.url,
method: options.method,
+ retryAfterSeconds: options.retryAfterSeconds,
message: `PostHog API rate limit exceeded (429) on ${options.method} ${options.url}.${retryHint}`,
})
this.name = 'PostHogRateLimitError'
- this.retryAfterSeconds = options.retryAfterSeconds
}
}
@@ -314,14 +313,14 @@ export class PostHogTransportError extends Error {
/**
* Parses a Retry-After header into whole seconds. Returns null for missing
- * headers, HTTP-date values, and bogus negatives.
+ * headers, HTTP-date values, and invalid delay values.
*/
export function parseRetryAfterSeconds(header: string | null): number | null {
- if (!header) {
+ if (!header || !/^\d+$/.test(header.trim())) {
return null
}
- const seconds = Number.parseInt(header, 10)
- return Number.isNaN(seconds) || seconds < 0 ? null : seconds
+ const seconds = Number(header)
+ return Number.isSafeInteger(seconds) ? seconds : null
}
export interface PostHogPermissionErrorOptions {
@@ -615,7 +614,11 @@ export function handleToolError(
// reach here (4xx short-circuited earlier).
const recoveryHint =
recoverableApiError instanceof PostHogApiError
- ? getToolRecoveryHint({ url: recoverableApiError.url, status: recoverableApiError.status })
+ ? getToolRecoveryHint({
+ url: recoverableApiError.url,
+ status: recoverableApiError.status,
+ retryAfterSeconds: recoverableApiError.retryAfterSeconds,
+ })
: undefined
return {
diff --git a/services/mcp/src/lib/tool-error-hints.ts b/services/mcp/src/lib/tool-error-hints.ts
index 8195e544f476..e5c79e18b741 100644
--- a/services/mcp/src/lib/tool-error-hints.ts
+++ b/services/mcp/src/lib/tool-error-hints.ts
@@ -69,6 +69,7 @@ interface RecoveryHintInput {
url?: string | undefined
/** The HTTP status code, if known. */
status?: number | undefined
+ retryAfterSeconds?: number | null
}
/**
@@ -79,7 +80,11 @@ interface RecoveryHintInput {
* 4xx responses already carry an actionable validation detail and must not be
* buried under a generic hint.
*/
-export function getToolRecoveryHint({ url, status }: RecoveryHintInput): string | undefined {
+export function getToolRecoveryHint({ url, status, retryAfterSeconds }: RecoveryHintInput): string | undefined {
+ if (status === 503 && retryAfterSeconds != null) {
+ return `The PostHog API is temporarily unavailable. Wait at least ${retryAfterSeconds} seconds before retrying this request.`
+ }
+
// 4xx is recoverable agent input, already surfaced verbatim upstream.
if (status !== undefined && status < 500) {
return undefined
diff --git a/services/mcp/src/tools/aiObservability/getLLMCosts.ts b/services/mcp/src/tools/aiObservability/getLLMCosts.ts
index b81646d45a7e..eed160a2e035 100644
--- a/services/mcp/src/tools/aiObservability/getLLMCosts.ts
+++ b/services/mcp/src/tools/aiObservability/getLLMCosts.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import { wrapError } from '@/lib/errors'
import { withUiApp } from '@/resources/ui-apps'
import { AIObservabilityGetCostsSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
@@ -41,7 +42,7 @@ export const getLLMCostsHandler: ToolBase<typeof schema, Result>['handler'] = as
const costsResult = await context.api.query({ projectId }).execute({ queryBody: trendsQuery })
if (!costsResult.success) {
- throw new Error(`Failed to get LLM costs: ${costsResult.error.message}`)
+ throw wrapError(`Failed to get LLM costs: ${costsResult.error.message}`, costsResult.error)
}
return withPostHogUrl(context, { results: costsResult.data.results }, '/ai-observability')
}
diff --git a/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts b/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts
index f919ef283e69..2b904ecc1f5d 100644
--- a/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts
+++ b/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts
@@ -2,7 +2,9 @@ import { z } from 'zod'
import { mergeRecipes, RecipeNormalizer, type StoredRecipe, validateRecipeAgainstSample } from '@posthog/llm-normalizer'
+import { PostHogApiError, wrapError } from '@/lib/errors'
import { getPostHogClient } from '@/lib/posthog'
+import { getToolRecoveryHint } from '@/lib/tool-error-hints'
import type { Context, ToolBase } from '@/tools/types'
// Mirrors MAX_SOURCE_LENGTH on the ParserRecipe model.
@@ -88,7 +90,7 @@ export const parserRecipeCreateHandler: ToolBase<typeof schema, ParserRecipeCrea
.execute({ queryBody: { kind: 'TraceQuery', traceId: params.trace_id, dateRange: { date_from: dateFrom } } })
if (!traceResult.success) {
// Infra failures are exceptions; validation failures are results.
- throw new Error(`Failed to load trace ${params.trace_id}: ${traceResult.error.message}`)
+ throw wrapError(`Failed to load trace ${params.trace_id}: ${traceResult.error.message}`, traceResult.error)
}
const traces = (traceResult.data.results ?? []) as Trace[]
@@ -183,7 +185,9 @@ export const parserRecipeCreateHandler: ToolBase<typeof schema, ParserRecipeCrea
// Observability must never break the request.
}
// Only persistence failed — never make the agent rewrite a correct recipe.
- return { valid: true, saved: false, error: error instanceof Error ? error.message : String(error) }
+ const message = error instanceof Error ? error.message : String(error)
+ const recoveryHint = error instanceof PostHogApiError ? getToolRecoveryHint(error) : undefined
+ return { valid: true, saved: false, error: [message, recoveryHint].filter(Boolean).join(' ') }
}
}
diff --git a/services/mcp/src/tools/insights/query.ts b/services/mcp/src/tools/insights/query.ts
index b1e3a73d5fba..13c0fb779866 100644
--- a/services/mcp/src/tools/insights/query.ts
+++ b/services/mcp/src/tools/insights/query.ts
@@ -1,6 +1,7 @@
import type { z } from 'zod'
import type { AccessControlFilterWarning, DataWarehouseSyncWarning } from '@/api/client'
+import { wrapError } from '@/lib/errors'
import { withUiApp } from '@/resources/ui-apps'
import type { Insight } from '@/schema/insights'
import { InsightQueryInputSchema } from '@/schema/tool-inputs'
@@ -59,7 +60,7 @@ export const queryHandler: ToolBase<typeof schema, Result>['handler'] = async (c
})
if (!insightResult.success) {
- throw new Error(`Failed to get insight: ${insightResult.error.message}`)
+ throw wrapError(`Failed to get insight: ${insightResult.error.message}`, insightResult.error)
}
const queryResult = await context.api.insights({ projectId }).query({
@@ -67,7 +68,7 @@ export const queryHandler: ToolBase<typeof schema, Result>['handler'] = async (c
})
if (!queryResult.success) {
- throw new Error(`Failed to query insight: ${queryResult.error.message}`)
+ throw wrapError(`Failed to query insight: ${queryResult.error.message}`, queryResult.error)
}
// Carry the overrides into the link as query params so opening the insight in
diff --git a/services/mcp/src/tools/projects/getProjects.ts b/services/mcp/src/tools/projects/getProjects.ts
index e225faad3ce6..569393154d44 100644
--- a/services/mcp/src/tools/projects/getProjects.ts
+++ b/services/mcp/src/tools/projects/getProjects.ts
@@ -1,4 +1,5 @@
import type { Schemas } from '@/api/generated'
+import { wrapError } from '@/lib/errors'
import { ProjectGetAllSchema } from '@/schema/tool-inputs'
import { omitResponseFields } from '@/tools/tool-utils'
import type { Context, ToolBase } from '@/tools/types'
@@ -24,7 +25,7 @@ export const getProjectsHandler: ToolBase<typeof schema, PublicProject[]>['handl
const projectsResult = await context.api.organizations().projects({ orgId }).list()
if (!projectsResult.success) {
- throw new Error(`Failed to get projects: ${projectsResult.error.message}`)
+ throw wrapError(`Failed to get projects: ${projectsResult.error.message}`, projectsResult.error)
}
return projectsResult.data.map(
diff --git a/services/mcp/src/tools/projects/updateEventDefinition.ts b/services/mcp/src/tools/projects/updateEventDefinition.ts
index 9129a7487917..71ef26205578 100644
--- a/services/mcp/src/tools/projects/updateEventDefinition.ts
+++ b/services/mcp/src/tools/projects/updateEventDefinition.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import { wrapError } from '@/lib/errors'
import type { ApiEventDefinition } from '@/schema/api'
import { EventDefinitionUpdateSchema } from '@/schema/tool-inputs'
import type { Context, ToolBase } from '@/tools/types'
@@ -23,7 +24,7 @@ export const updateEventDefinitionHandler: ToolBase<typeof schema, Result>['hand
})
if (!result.success) {
- throw new Error(`Failed to update event definition: ${result.error.message}`)
+ throw wrapError(`Failed to update event definition: ${result.error.message}`, result.error)
}
return {
diff --git a/services/mcp/src/tools/projects/updatePathCleaning.ts b/services/mcp/src/tools/projects/updatePathCleaning.ts
index e1f081f0b740..019b42d4da48 100644
--- a/services/mcp/src/tools/projects/updatePathCleaning.ts
+++ b/services/mcp/src/tools/projects/updatePathCleaning.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import { wrapError } from '@/lib/errors'
import { PathCleaningRulesUpdateSchema } from '@/schema/tool-inputs'
import type { Context, ToolBase } from '@/tools/types'
@@ -276,7 +277,10 @@ export const updatePathCleaningHandler: ToolBase<typeof schema, Result>['handler
const projectResult = await context.api.projects().get({ projectId })
if (!projectResult.success) {
- throw new Error(`Failed to read current path cleaning rules: ${projectResult.error.message}`)
+ throw wrapError(
+ `Failed to read current path cleaning rules: ${projectResult.error.message}`,
+ projectResult.error
+ )
}
const currentStored = normalizePathCleaningFilters(
@@ -309,7 +313,7 @@ export const updatePathCleaningHandler: ToolBase<typeof schema, Result>['handler
filters: resultingRules,
})
if (!updateResult.success) {
- throw new Error(`Failed to save path cleaning rules: ${updateResult.error.message}`)
+ throw wrapError(`Failed to save path cleaning rules: ${updateResult.error.message}`, updateResult.error)
}
const saved = normalizePathCleaningFilters(
diff --git a/services/mcp/src/tools/projects/updatePropertyDefinition.ts b/services/mcp/src/tools/projects/updatePropertyDefinition.ts
index 56d3e624e901..5cc31292f420 100644
--- a/services/mcp/src/tools/projects/updatePropertyDefinition.ts
+++ b/services/mcp/src/tools/projects/updatePropertyDefinition.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import { wrapError } from '@/lib/errors'
import type { ApiPropertyDefinition } from '@/schema/api'
import { PropertyDefinitionUpdateSchema } from '@/schema/tool-inputs'
import type { Context, ToolBase } from '@/tools/types'
@@ -25,7 +26,7 @@ export const updatePropertyDefinitionHandler: ToolBase<typeof schema, Result>['h
})
if (!result.success) {
- throw new Error(`Failed to update property definition: ${result.error.message}`)
+ throw wrapError(`Failed to update property definition: ${result.error.message}`, result.error)
}
return {
diff --git a/services/mcp/tests/unit/parser-recipe-create.test.ts b/services/mcp/tests/unit/parser-recipe-create.test.ts
index fa1f5e32776b..b5530e805b6b 100644
--- a/services/mcp/tests/unit/parser-recipe-create.test.ts
+++ b/services/mcp/tests/unit/parser-recipe-create.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
+import { PostHogApiError } from '@/lib/errors'
import parserRecipeCreate from '@/tools/aiObservability/parserRecipeCreate'
import type { Context } from '@/tools/types'
@@ -195,12 +196,27 @@ describe('llma-parser-recipe-create handler', () => {
expect(request).toHaveBeenCalledTimes(1)
})
- it('reports a persistence failure as valid-but-unsaved so the agent does not rewrite', async () => {
- const request = vi.fn().mockResolvedValueOnce({ results: [] }).mockRejectedValueOnce(new Error('500 from API'))
+ it.each([
+ { error: new Error('500 from API'), expected: '500 from API' },
+ {
+ error: new PostHogApiError({
+ status: 503,
+ statusText: 'Service Unavailable',
+ body: 'Cluster busy',
+ url: 'https://us.posthog.com/api/projects/42/llm_analytics/parser_recipes/',
+ method: 'POST',
+ message: 'Cluster busy',
+ retryAfterSeconds: 45,
+ }),
+ expected:
+ 'Cluster busy The PostHog API is temporarily unavailable. Wait at least 45 seconds before retrying this request.',
+ },
+ ])('reports a persistence failure with recovery guidance: $expected', async ({ error, expected }) => {
+ const request = vi.fn().mockResolvedValueOnce({ results: [] }).mockRejectedValueOnce(error)
const { context } = createContext({ events: [generationEvent()], request })
const result = await parserRecipeCreate().handler(context, baseParams)
- expect(result).toEqual({ valid: true, saved: false, error: '500 from API' })
+ expect(result).toEqual({ valid: true, saved: false, error: expected })
})
})
diff --git a/services/mcp/tests/unit/rate-limit-errors.test.ts b/services/mcp/tests/unit/rate-limit-errors.test.ts
index e5a2e4c3bb83..1550c96bc4b2 100644
--- a/services/mcp/tests/unit/rate-limit-errors.test.ts
+++ b/services/mcp/tests/unit/rate-limit-errors.test.ts
@@ -1,7 +1,22 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiClient, type Result } from '@/api/client'
-import { handleToolError, parseRetryAfterSeconds, PostHogApiError, PostHogRateLimitError } from '@/lib/errors'
+import {
+ findRecoverableApiError,
+ handleToolError,
+ parseRetryAfterSeconds,
+ PostHogApiError,
+ PostHogRateLimitError,
+ wrapError,
+} from '@/lib/errors'
+import { getLLMCostsHandler } from '@/tools/aiObservability/getLLMCosts'
+import { parserRecipeCreateHandler } from '@/tools/aiObservability/parserRecipeCreate'
+import { queryHandler } from '@/tools/insights/query'
+import { getProjectsHandler } from '@/tools/projects/getProjects'
+import { updateEventDefinitionHandler } from '@/tools/projects/updateEventDefinition'
+import { updatePathCleaningHandler } from '@/tools/projects/updatePathCleaning'
+import { updatePropertyDefinitionHandler } from '@/tools/projects/updatePropertyDefinition'
+import type { Context } from '@/tools/types'
const captureException = vi.fn()
vi.mock('@/lib/posthog', () => ({
@@ -30,6 +45,10 @@ describe('outbound 429 handling', () => {
{ header: '5', expected: 5 },
{ header: '0', expected: 0 },
{ header: '-5', expected: null },
+ { header: ' 45 ', expected: 45 },
+ { header: '1.5', expected: null },
+ { header: '45seconds', expected: null },
+ { header: '9'.repeat(400), expected: null },
{ header: 'Wed, 21 Oct 2026 07:28:00 GMT', expected: null },
{ header: null, expected: null },
])('parses $header as $expected', ({ header, expected }) => {
@@ -185,3 +204,195 @@ describe('outbound 429 handling', () => {
})
})
})
+
+describe('outbound 503 retry hints', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ async function unwrapResult(resultPromise: Promise<Result<unknown>>): Promise<unknown> {
+ const result = await resultPromise
+ if (!result.success) {
+ throw result.error
+ }
+ return result.data
+ }
+
+ it.each<{
+ name: string
+ request: (context: Context) => Promise<unknown>
+ precedingResponses?: unknown[]
+ }>([
+ {
+ name: 'property definitions list',
+ request: ({ api }) => unwrapResult(api.projects().propertyDefinitions({ projectId: '123' })),
+ },
+ {
+ name: 'event definitions list',
+ request: ({ api }) => unwrapResult(api.projects().eventDefinitions({ projectId: '123' })),
+ },
+ {
+ name: 'insight delete',
+ request: ({ api }) => unwrapResult(api.insights({ projectId: '123' }).delete({ insightId: 456 })),
+ },
+ ...[false, true].flatMap((duringUpdate) => [
+ {
+ name: `event definition ${duringUpdate ? 'update' : 'lookup'}`,
+ request: (context: Context) =>
+ updateEventDefinitionHandler(context, { eventName: 'test_event', data: { description: 'Test' } }),
+ precedingResponses: duringUpdate ? [{ id: 'event-id', name: 'test_event' }] : [],
+ },
+ {
+ name: `property definition ${duringUpdate ? 'update' : 'lookup'}`,
+ request: (context: Context) =>
+ updatePropertyDefinitionHandler(context, {
+ propertyName: 'test_property',
+ type: 'event',
+ data: { description: 'Test' },
+ }),
+ precedingResponses: duringUpdate ? [{ results: [{ id: 'property-id', name: 'test_property' }] }] : [],
+ },
+ {
+ name: `insight ${duringUpdate ? 'query' : 'lookup'}`,
+ request: (context: Context) => queryHandler(context, { insightId: '456', output_format: 'json' }),
+ precedingResponses: duringUpdate ? [{ id: 456, query: { kind: 'HogQLQuery', query: 'SELECT 1' } }] : [],
+ },
+ {
+ name: `path cleaning ${duringUpdate ? 'update' : 'lookup'}`,
+ request: (context: Context) =>
+ updatePathCleaningHandler(context, {
+ operations: [{ action: 'append', alias: '/items/id', regex: '^/items/[0-9]+$' }],
+ confirm: true,
+ }),
+ precedingResponses: duringUpdate ? [{ path_cleaning_filters: [] }] : [],
+ },
+ ]),
+ { name: 'group types', request: ({ api }) => api.getGroupTypes('123') },
+ { name: 'gateway tools', request: ({ api }) => api.getGatewayTools('123') },
+ { name: 'project discovery', request: (context) => getProjectsHandler(context, {}) },
+ { name: 'LLM costs', request: (context) => getLLMCostsHandler(context, {}) },
+ {
+ name: 'parser recipe trace',
+ request: (context) =>
+ parserRecipeCreateHandler(context, {
+ name: 'Test recipe',
+ yaml_source: 'test: true',
+ trace_id: 'test-trace',
+ event_uuid: 'test-event',
+ }),
+ },
+ ])('preserves the cooldown through the $name path', async ({ request, precedingResponses = [] }) => {
+ const mockFetch = vi.fn()
+ for (const response of precedingResponses) {
+ mockFetch.mockResolvedValueOnce(new Response(JSON.stringify(response), { status: 200 }))
+ }
+ mockFetch.mockResolvedValueOnce(
+ new Response('Temporarily unavailable', { status: 503, headers: { 'Retry-After': '45' } })
+ )
+ vi.stubGlobal('fetch', mockFetch)
+ const context = {
+ api: new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://example.com' }),
+ stateManager: { getProjectId: async () => '123', getOrgID: async () => 'test-org' },
+ } as unknown as Context
+
+ const error = await request(context).catch((error: unknown) => error)
+
+ expect(findRecoverableApiError(error)).toMatchObject({ status: 503, retryAfterSeconds: 45 })
+ const result = handleToolError(error, 'test-tool')
+ expect(result.isError).toBe(true)
+ expect(result.content[0]).toMatchObject({
+ type: 'text',
+ text: expect.stringContaining('Wait at least 45 seconds'),
+ })
+ expect(mockFetch).toHaveBeenCalledTimes(precedingResponses.length + 1)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it.each([
+ { transport: 'json', wrapped: false },
+ { transport: 'json', wrapped: true },
+ { transport: 'text', wrapped: false },
+ { transport: 'text', wrapped: true },
+ { transport: 'sse', wrapped: false },
+ { transport: 'sse', wrapped: true },
+ ])(
+ 'passes the server cooldown to the agent without retrying ($transport, wrapped=$wrapped)',
+ async ({ transport, wrapped }) => {
+ const body = JSON.stringify({
+ type: 'server_error',
+ code: 'service_unavailable',
+ detail: 'Please try later.',
+ })
+ const mockFetch = vi.fn().mockResolvedValue(
+ new Response(body, {
+ status: 503,
+ statusText: 'Service Unavailable',
+ headers: { 'Retry-After': '45' },
+ })
+ )
+ vi.stubGlobal('fetch', mockFetch)
+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://example.com' })
+ const options = { method: 'POST' as const, path: '/api/projects/123/logs/query/', body: {} }
+ const request =
+ transport === 'sse'
+ ? client.requestSSE({ ...options, onEvent: vi.fn() })
+ : client.request({ ...options, responseType: transport === 'text' ? 'text' : 'json' })
+ const error = await request.catch((error: unknown) => error)
+
+ expect(error).toBeInstanceOf(PostHogApiError)
+ expect(error).toMatchObject({ status: 503, body, retryAfterSeconds: 45 })
+ const result = handleToolError(wrapped ? wrapError('Failed to query logs', error) : error, 'query-logs')
+ expect(result.isError).toBe(true)
+ expect(result.content[0]).toMatchObject({
+ type: 'text',
+ text: expect.stringContaining('Wait at least 45 seconds'),
+ })
+ expect((result.content[0] as { text: string }).text).not.toContain('Narrow the query and retry')
+ expect(captureException).toHaveBeenCalledTimes(1)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ expect(vi.getTimerCount()).toBe(0)
+ }
+ )
+
+ it.each([
+ { status: 503, header: '0', expected: 0 },
+ { status: 503, header: '45', expected: 45 },
+ { status: 503, header: null, expected: null },
+ { status: 503, header: 'unknown', expected: null },
+ { status: 503, header: '-1', expected: null },
+ { status: 503, header: '45seconds', expected: null },
+ { status: 503, header: 'Wed, 21 Oct 2026 07:28:00 GMT', expected: null },
+ { status: 500, header: '45', expected: null },
+ ])('only returns valid 503 cooldowns (status=$status, header=$header)', async ({ status, header, expected }) => {
+ const mockFetch = vi.fn().mockResolvedValue(
+ new Response('Upstream failure', {
+ status,
+ headers: header === null ? {} : { 'Retry-After': header },
+ })
+ )
+ vi.stubGlobal('fetch', mockFetch)
+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://example.com' })
+ const error = await client
+ .request({ method: 'GET', path: '/api/projects/123/logs/query/' })
+ .catch((error: unknown) => error)
+
+ expect(error).toMatchObject({ status, retryAfterSeconds: expected })
+ const result = handleToolError(error, 'query-logs')
+ const text = (result.content[0] as { text: string }).text
+ if (expected === null) {
+ expect(text).not.toContain('Wait at least')
+ expect(text).toContain('Narrow the query and retry')
+ } else {
+ expect(text).toContain(`Wait at least ${expected} seconds`)
+ }
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+})