: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): bound each posthog api request with a deadline (#115549)
posthog[bot]0534c71a3728
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 91becc527c9e..32615f43f716 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -5,6 +5,8 @@ import { MCP_CLIENT_IP_HEADERS, signedClientIpHeaders } from '@/lib/client-ip-siimport { getUserAgent } from '@/lib/constants'import {ErrorCode,+ hasTimeoutCause,+ isTimeoutError,parseRetryAfterSeconds,PostHogApiError,PostHogPermissionError,@@ -57,7 +59,22 @@ const SAFE_HTTP_METHODS = new Set(['GET', 'HEAD'])* 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'+ return (error instanceof Error && error.name === 'AbortError') || isTimeoutError(error)+}++// Per-attempt deadline for a JSON API request. Without it, an upstream request that+// never answers holds the tool call open until the MCP client gives up, and a batch+// waits on its slowest call. A timeout returns an error that says whether a retry is+// safe, so the agent does not have to guess if a write applied.+const API_REQUEST_TIMEOUT_MS = 2 * 60 * 1000++// Endpoints that run analytics queries can legitimately take minutes, so they keep a+// wide bound. It still ends a request that never answers.+const LONG_RUNNING_API_REQUEST_TIMEOUT_MS = 10 * 60 * 1000+const LONG_RUNNING_API_PATH = /\/(query|run_insights|mcp_tools\/execute_sql)\/$|\/(max_tools|autoresearch)\//++function apiRequestTimeoutMs(url: string): number {+ return LONG_RUNNING_API_PATH.test(url.split('?')[0]!) ? LONG_RUNNING_API_REQUEST_TIMEOUT_MS : API_REQUEST_TIMEOUT_MS}// Default overall timeout for an SSE stream (wall-clock cap from connect to close).@@ -624,17 +641,32 @@ export class ApiClient {let waitBudgetMs = RATE_LIMIT_TOTAL_WAIT_BUDGET_MSlet rateLimitRetries = 0let transportRetries = 0+ const timeoutMs = apiRequestTimeoutMs(url)for (;;) {let response: Responselet bodyText: string+ const deadline = new AbortController()+ const timer = setTimeout(+ () =>+ deadline.abort(+ new DOMException(`No response within ${Math.round(timeoutMs / 1000)} seconds`, 'TimeoutError')+ ),+ timeoutMs+ )+ const signal = options?.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signaltry {- response = await this.fetch(url, options)+ response = await this.fetch(url, { ...options, signal })// 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 canRetry = !isAbortError(error) && isSafeMethod && transportRetries < TRANSPORT_MAX_RETRIES+ const canRetry =+ !signal.aborted &&+ !isAbortError(error) &&+ !hasTimeoutCause(error) &&+ isSafeMethod &&+ transportRetries < TRANSPORT_MAX_RETRIESif (!canRetry) {console.error(`[API] Transport failure on ${method} ${url}: ${String(error)}`)return {@@ -657,6 +689,8 @@ export class ApiClient {)await new Promise((resolve) => setTimeout(resolve, delayMs))continue+ } finally {+ clearTimeout(timer)}if (response.status === 429) {@@ -907,44 +941,29 @@ export class ApiClient {hidden?: boolean}}): Promise<Result<ApiEventDefinition>> => {- try {- // Fetching the event definition by name to get its ID- const searchParams = new URLSearchParams({ name: eventName })- const findUrl = `${this.baseUrl}/api/projects/${projectId}/event_definitions/by_name/?${searchParams}`+ // Fetching the event definition by name to get its ID+ const searchParams = new URLSearchParams({ name: eventName })+ const findUrl = `${this.baseUrl}/api/projects/${projectId}/event_definitions/by_name/?${searchParams}`- const findResponse = await this.fetch(findUrl)+ const findResult = await this.fetchJson<ApiEventDefinition>(findUrl)- if (findResponse.status === 404) {+ if (!findResult.success) {+ if (findResult.error instanceof PostHogApiError && findResult.error.status === 404) {return {success: false,error: new Error(`Event definition not found: ${eventName}`),}}+ return findResult+ }- if (!findResponse.ok) {- throw this.buildApiError(findResponse, await findResponse.text(), findUrl, 'GET')- }-- const eventDef = (await findResponse.json()) as ApiEventDefinition-- // Updating the event definition by ID- const updateUrl = `${this.baseUrl}/api/projects/${projectId}/event_definitions/${eventDef.id}/`-- const updateResponse = await this.fetch(updateUrl, {- method: 'PATCH',- body: JSON.stringify(data),- })-- if (!updateResponse.ok) {- throw this.buildApiError(updateResponse, await updateResponse.text(), updateUrl, 'PATCH')- }-- const responseData = (await updateResponse.json()) as ApiEventDefinition+ // Updating the event definition by ID+ const updateUrl = `${this.baseUrl}/api/projects/${projectId}/event_definitions/${findResult.data.id}/`- return { success: true, data: responseData }- } catch (error) {- return { success: false, error: error as Error }- }+ return this.fetchJson<ApiEventDefinition>(updateUrl, {+ method: 'PATCH',+ body: JSON.stringify(data),+ })},updatePropertyDefinition: async ({@@ -966,52 +985,37 @@ export class ApiClient {hidden?: boolean}}): Promise<Result<ApiPropertyDefinition>> => {- try {- // Property definitions have no by-name lookup endpoint, so resolve the id via the- // list endpoint: `properties` does an exact-name match, and `type` disambiguates a- // name that exists across taxonomies (e.g. an event property and a person property).- const findParams = getSearchParamsFromRecord({- properties: propertyName,- type: type ?? 'event',- group_type_index: groupTypeIndex,- })- const findUrl = `${this.baseUrl}/api/projects/${projectId}/property_definitions/?${findParams}`-- const findResponse = await this.fetch(findUrl)-- if (!findResponse.ok) {- throw this.buildApiError(findResponse, await findResponse.text(), findUrl, 'GET')- }+ // Property definitions have no by-name lookup endpoint, so resolve the id via the+ // list endpoint: `properties` does an exact-name match, and `type` disambiguates a+ // name that exists across taxonomies (e.g. an event property and a person property).+ const findParams = getSearchParamsFromRecord({+ properties: propertyName,+ type: type ?? 'event',+ group_type_index: groupTypeIndex,+ })+ const findUrl = `${this.baseUrl}/api/projects/${projectId}/property_definitions/?${findParams}`- const findData = (await findResponse.json()) as { results: ApiPropertyDefinition[] }- const propertyDef = findData.results.find((def) => def.name === propertyName)+ const findResult = await this.fetchJson<{ results: ApiPropertyDefinition[] }>(findUrl)- if (!propertyDef) {- return {- success: false,- error: new Error(- `Property definition not found: ${propertyName} (type: ${type ?? 'event'})`- ),- }- }+ if (!findResult.success) {+ return findResult+ }- const updateUrl = `${this.baseUrl}/api/projects/${projectId}/property_definitions/${propertyDef.id}/`+ const propertyDef = findResult.data.results.find((def) => def.name === propertyName)- const updateResponse = await this.fetch(updateUrl, {- method: 'PATCH',- body: JSON.stringify(data),- })-- if (!updateResponse.ok) {- throw this.buildApiError(updateResponse, await updateResponse.text(), updateUrl, 'PATCH')+ if (!propertyDef) {+ return {+ success: false,+ error: new Error(`Property definition not found: ${propertyName} (type: ${type ?? 'event'})`),}+ }- const responseData = (await updateResponse.json()) as ApiPropertyDefinition+ const updateUrl = `${this.baseUrl}/api/projects/${projectId}/property_definitions/${propertyDef.id}/`- return { success: true, data: responseData }- } catch (error) {- return { success: false, error: error as Error }- }+ return this.fetchJson<ApiPropertyDefinition>(updateUrl, {+ method: 'PATCH',+ body: JSON.stringify(data),+ })},updatePathCleaningFilters: async ({diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex a3de124b6337..28696103ab59 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -21,6 +21,8 @@ import {MCPToolResultError,findPostHogPermissionError,findRecoverableApiError,+ hasTimeoutCause,+ isTimeoutError,} from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { resolveGatewayTools } from '@/lib/gateway-tools'@@ -978,7 +980,7 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassificationif (findPostHogPermissionError(error)) {return { errorType: 'permission' }}- if (error instanceof Error && error.name === 'TimeoutError') {+ if (hasTimeoutCause(error)) {return { errorType: 'timeout' }}@@ -1079,7 +1081,7 @@ function resolveSafeErrorMessage(error: unknown): string | undefined {if (error instanceof ExecCommandError) {return `Exec command rejected: ${error.reason}`}- if (error instanceof Error && error.name === 'TimeoutError') {+ if (isTimeoutError(error)) {return 'Tool call timed out'}const apiError = findRecoverableApiError(error)diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 66081803613d..d3cd094975e3 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -315,6 +315,11 @@ export class PostHogRateLimitError extends PostHogApiError {}}+/** True for an error raised by a request deadline, as opposed to a cancellation or a network fault. */+export function isTimeoutError(error: unknown): boolean {+ return error instanceof Error && error.name === 'TimeoutError'+}+export interface PostHogTransportErrorOptions {url: stringmethod: string@@ -339,6 +344,8 @@ export class PostHogTransportError extends Error {public readonly url: stringpublic readonly method: stringpublic readonly attempts: number+ /** True when the request hit the client's deadline instead of failing to connect. */+ public readonly timedOut: booleanconstructor(options: PostHogTransportErrorOptions) {const reason = options.cause instanceof Error ? options.cause.message : String(options.cause)@@ -353,6 +360,8 @@ export class PostHogTransportError extends Error {this.url = options.urlthis.method = options.methodthis.attempts = options.attempts+ // A forwarded request nests the local transport error, so look through the cause chain.+ this.timedOut = hasTimeoutCause(options.cause);(this as Error & { cause?: unknown }).cause = options.cause}}@@ -527,6 +536,21 @@ export function findRecoverableApiError(error: unknown): PostHogApiError | PostHreturn undefined}+/** True when the error or any error in its `cause` chain came from a request deadline. Tools that+ * rethrow through `wrapError` keep the timeout in `cause`. */+export function hasTimeoutCause(error: unknown): boolean {+ let current: unknown = error+ const seen = new Set<unknown>()+ while (current && !seen.has(current)) {+ if (isTimeoutError(current) || (current instanceof PostHogTransportError && current.timedOut)) {+ return true+ }+ seen.add(current)+ current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined+ }+ return false+}+/*** Handles tool errors and returns a structured error message.* Any errors that originate from the tool SHOULD be reported inside the resultdiff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 589277b87326..9dcbd22bba57 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -47,6 +47,7 @@ import {MCPToolResultError,PostHogApiError,PostHogRateLimitError,+ PostHogTransportError,PostHogValidationError,ToolInputValidationError,wrapError,@@ -528,6 +529,35 @@ describe('ToolExecutor metrics', () => {expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })})+ it.each([+ ['a transport error', (error: Error): Error => error],+ [+ 'a transport error wrapped in a cause chain',+ (error: Error): Error => wrapError('Failed to get insight', error),+ ],+ ])('classifies a request deadline on %s as timeout', async (_label, wrap) => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('insight-query', async () => {+ throw wrap(+ new PostHogTransportError({+ url: 'https://us.posthog.com/api/environments/2/insights/1/',+ method: 'GET',+ attempts: 1,+ retryable: true,+ cause: new DOMException('No response within 120 seconds', 'TimeoutError'),+ })+ )+ }) as any+ )++ await executor.handleToolCall(+ { name: 'insight-query', arguments: {} },+ makeToolExecutorState([{ name: 'insight-query' }])+ )++ expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'insight-query', error_type: 'timeout' })+ })+it('records validation_error without starting a timer', async () => {vi.spyOn(catalog, 'getToolByName').mockReturnValue({name: 'strict-tool',diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.tsindex 5670b648ca74..1f86bc829c3f 100644--- a/services/mcp/tests/unit/api-client.test.ts+++ b/services/mcp/tests/unit/api-client.test.ts@@ -673,5 +673,87 @@ describe('ApiClient', () => {expect((error as PostHogTransportError).message).toContain('may have been applied upstream')expect(mockFetch).toHaveBeenCalledTimes(1)})++ const stubStalledFetch = (): ReturnType<typeof vi.fn> => {+ const mockFetch = vi.fn(+ (_url: string, init?: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener('abort', () => reject(init.signal!.reason))+ })+ )+ vi.stubGlobal('fetch', mockFetch)+ return mockFetch+ }++ it.each([+ { method: 'GET' as const, retryable: true, advice: 'safe to retry' },+ { method: 'POST' as const, retryable: false, advice: 'may have been applied upstream' },+ ])('ends a $method request that never answers', async ({ method, retryable, advice }) => {+ const mockFetch = stubStalledFetch()+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })++ const error = await settle(client.request({ method, path: '/api/projects/17/signals/scout/notes/' }))++ expect(error).toBeInstanceOf(PostHogTransportError)+ expect(error).toMatchObject({ retryable, timedOut: true, attempts: 1 })+ expect((error as PostHogTransportError).message).toContain(advice)+ expect(mockFetch).toHaveBeenCalledTimes(1)+ })++ it.each([+ {+ name: 'event definition',+ lookup: { id: 'event-id', name: 'test_event' },+ update: (client: ApiClient) =>+ client.projects().updateEventDefinition({+ projectId: '17',+ eventName: 'test_event',+ data: { description: 'Test' },+ }),+ },+ {+ name: 'property definition',+ lookup: { results: [{ id: 'property-id', name: 'test_property' }] },+ update: (client: ApiClient) =>+ client.projects().updatePropertyDefinition({+ projectId: '17',+ propertyName: 'test_property',+ data: { description: 'Test' },+ }),+ },+ ])('ends a $name update that never answers', async ({ lookup, update }) => {+ const mockFetch = stubStalledFetch()+ mockFetch.mockResolvedValueOnce(new Response(JSON.stringify(lookup), { status: 200 }))+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })++ const result = await settle(update(client))++ expect(result).toMatchObject({ success: false })+ const error = (result as { error: unknown }).error+ expect(error).toBeInstanceOf(PostHogTransportError)+ expect(error).toMatchObject({ method: 'PATCH', retryable: false, timedOut: true })+ expect(mockFetch).toHaveBeenCalledTimes(2)+ })++ it.each(['/api/environments/17/query/', '/api/environments/17/mcp_tools/execute_sql/'])(+ 'gives a query request to %s more time than the default deadline',+ async (path) => {+ stubStalledFetch()+ const client = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })+ let settled = false+ const pending = client+ .request({ method: 'POST', path })+ .finally(() => {+ settled = true+ })+ .catch((error) => error)++ await vi.advanceTimersByTimeAsync(5 * 60 * 1000)+ expect(settled).toBe(false)++ await vi.runAllTimersAsync()+ expect(await pending).toMatchObject({ timedOut: true })+ }+ )})})diff --git a/services/mcp/tests/unit/connection-forwarding.test.ts b/services/mcp/tests/unit/connection-forwarding.test.tsindex 6bac4d85c034..7095a9937642 100644--- a/services/mcp/tests/unit/connection-forwarding.test.ts+++ b/services/mcp/tests/unit/connection-forwarding.test.ts@@ -3,7 +3,7 @@ import { z } from 'zod'import { ApiClient } from '@/api/client'import { ForwardingApiClient } from '@/lib/connection-forwarding'-import { ExecCommandError, PostHogApiError } from '@/lib/errors'+import { ExecCommandError, PostHogApiError, PostHogTransportError } from '@/lib/errors'import { StateManager } from '@/lib/StateManager'import executeSqlTool from '@/tools/posthogAiTools/executeSql'import { createConnectionCallTool } from '@/tools/posthogConnections/call'@@ -105,6 +105,36 @@ describe('posthog connection forwarding', () => {expect(shared.config.onPrivateResponse).toBeUndefined()})+ it('does not retry a forwarded read after its deadline', async () => {+ vi.useFakeTimers()+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const mockFetch = vi.fn(+ (_url: string, init?: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener('abort', () => reject(init.signal!.reason))+ })+ )+ vi.stubGlobal('fetch', mockFetch)+ const forwarding = new ForwardingApiClient(+ new ApiClient({ apiToken: 'test-token', baseUrl: 'https://example.com' }),+ { connectionId: '99', localProjectId: '7', target: TARGET }+ )++ try {+ const outcome = forwarding+ .request({ method: 'GET', path: '/api/projects/4242/insights/' })+ .catch((error) => error)+ await vi.runAllTimersAsync()+ const error = await outcome++ expect(error).toBeInstanceOf(PostHogTransportError)+ expect(error).toMatchObject({ timedOut: true, attempts: 1 })+ expect(mockFetch).toHaveBeenCalledTimes(1)+ } finally {+ vi.useRealTimers()+ }+ })+it('rewrites a request into the forward endpoint and unwraps the target response', async () => {const request = createRequestMock({ status: 200, data: { results: [[1]] } })const forwarding = new ForwardingApiClient(createLocalApi(request), {