: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(llma): stop capturing 4xx MCP API errors as exceptions (#59231)
posthog[bot]070fe8c38d22
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex e248cb6a906d..70df594b5151 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -2,7 +2,7 @@ import { createParser } from 'eventsource-parser'import { z } from 'zod'import { getUserAgent } from '@/lib/constants'-import { ErrorCode, PostHogPermissionError, PostHogValidationError } from '@/lib/errors'+import { ErrorCode, PostHogApiError, PostHogPermissionError, PostHogValidationError } from '@/lib/errors'import { getSearchParamsFromRecord } from '@/lib/utils.js'import type {ApiEventDefinition,@@ -182,9 +182,13 @@ export class ApiClient {const response = await this.fetch(url, fetchOptions)if (!response.ok) {const errorText = await response.text()- throw new Error(- `Request failed:\nURL: ${opts.method} ${url}\nStatus Code: ${response.status} (${response.statusText})\nError Message: ${errorText}`- )+ throw new PostHogApiError({+ status: response.status,+ statusText: response.statusText,+ body: errorText,+ url,+ method: opts.method,+ })}return (await response.text()) as T}@@ -381,9 +385,13 @@ export class ApiClient {}console.error(`[API] Request failed on ${method} ${url}: ${response.status} ${response.statusText}`)- throw new Error(- `Request failed:\nURL: ${method} ${url}\nStatus Code: ${response.status} (${response.statusText})\nError Message: ${errorText}`- )+ throw new PostHogApiError({+ status: response.status,+ statusText: response.statusText,+ body: errorText,+ url,+ method,+ })}const rawText = await response.text()diff --git a/services/mcp/src/api/fetcher.ts b/services/mcp/src/api/fetcher.tsindex 15faa2825cdd..bf466f110325 100644--- a/services/mcp/src/api/fetcher.ts+++ b/services/mcp/src/api/fetcher.ts@@ -1,4 +1,5 @@import { getUserAgent } from '@/lib/constants'+import { PostHogApiError } from '@/lib/errors'import type { ApiConfig } from './client'import { globalRateLimiter } from './rate-limiter'@@ -95,7 +96,15 @@ export const buildApiFetcher: (config: ApiConfig) => Fetcher = (config) => {if (!response.ok) {const errorResponse = await response.json()- throw new Error(`Failed request: [${response.status}] ${JSON.stringify(errorResponse)}`)+ const errorBody = JSON.stringify(errorResponse)+ throw new PostHogApiError({+ status: response.status,+ statusText: response.statusText,+ body: errorBody,+ url: input.url.toString(),+ method: input.method.toUpperCase(),+ message: `Failed request: [${response.status}] ${errorBody}`,+ })}return responsediff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex fbe4a9fb8288..41c4202c8e6e 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -119,6 +119,49 @@ export class PostHogValidationError extends Error {}}+export interface PostHogApiErrorOptions {+ status: number+ statusText: string+ body: string+ url: string+ method: string+ message?: string+}++/**+ * Thrown when the PostHog API rejects a request with a non-success status that+ * isn't already handled by a more specific subclass (PostHogPermissionError,+ * PostHogValidationError). Carries the status code so callers can distinguish+ * recoverable agent-input errors (4xx) from genuine service failures (5xx).+ *+ * Background: an LLM agent passing a placeholder UUID to an MCP tool produced+ * a 404, and `handleToolError` captured it as a PostHog exception fingerprinted+ * by tool name — creating a brand-new error tracking issue per tool every time+ * an agent fumbled a parameter. Keying off `status` here lets `handleToolError`+ * short-circuit 4xx without losing visibility into real 5xx failures.+ */+export class PostHogApiError extends Error {+ public readonly status: number+ public readonly statusText: string+ public readonly body: string+ public readonly url: string+ public readonly method: string++ constructor(options: PostHogApiErrorOptions) {+ super(options.message ?? buildDefaultApiErrorMessage(options))+ this.name = 'PostHogApiError'+ this.status = options.status+ this.statusText = options.statusText+ this.body = options.body+ this.url = options.url+ this.method = options.method+ }+}++function buildDefaultApiErrorMessage(options: PostHogApiErrorOptions): string {+ return `Request failed:\nURL: ${options.method} ${options.url}\nStatus Code: ${options.status} (${options.statusText})\nError Message: ${options.body}`+}+export interface PostHogPermissionErrorOptions {detail: stringmissingScope?: string | undefined@@ -258,6 +301,25 @@ export function findPostHogPermissionError(error: unknown): PostHogPermissionErrreturn undefined}+/**+ * Walks `Error.cause` chains to find a wrapped PostHogApiError or+ * PostHogValidationError. Tool-level wrappers (e.g. `throw new Error("Failed+ * to X: ...", { cause })`) hide the underlying typed error, so callers must+ * unwrap before classifying the failure.+ */+export function findRecoverableApiError(error: unknown): PostHogApiError | PostHogValidationError | undefined {+ let current: unknown = error+ const seen = new Set<unknown>()+ while (current && !seen.has(current)) {+ if (current instanceof PostHogApiError || current instanceof PostHogValidationError) {+ return current+ }+ seen.add(current)+ current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined+ }+ return undefined+}+/*** Handles tool errors and returns a structured error message.* Any errors that originate from the tool SHOULD be reported inside the result@@ -290,6 +352,31 @@ export function handleToolError(error: any, tool?: string, distinctId?: string,}}+ // Recoverable: 4xx responses from the PostHog API (and validation errors)+ // are agent-input failures — the LLM passed a bad id, a stale UUID, or a+ // value the serializer rejected. Returning the typed error message to the+ // LLM lets it self-correct on the next turn. Capturing these as exceptions+ // — fingerprinted by tool name — would create a fresh error tracking issue+ // for every agent slip-up. Reserve `captureException` for 5xx and+ // unexpected non-HTTP errors, which are genuinely actionable for engineers.+ const recoverableApiError = findRecoverableApiError(error)+ if (recoverableApiError) {+ const isFourXx =+ recoverableApiError instanceof PostHogValidationError ||+ (recoverableApiError.status >= 400 && recoverableApiError.status < 500)+ if (isFourXx) {+ return {+ content: [+ {+ type: 'text',+ text: `Error: [${toolName}]: ${recoverableApiError.message}`,+ },+ ],+ isError: true,+ }+ }+ }+const permissionError = findPostHogPermissionError(error)if (permissionError) {const properties: Record<string, any> = {diff --git a/services/mcp/tests/unit/fetcher.test.ts b/services/mcp/tests/unit/fetcher.test.tsindex 95579944948c..6651707292ba 100644--- a/services/mcp/tests/unit/fetcher.test.ts+++ b/services/mcp/tests/unit/fetcher.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { buildApiFetcher, type Fetcher } from '@/api/fetcher'import { globalRateLimiter } from '@/api/rate-limiter'+import { PostHogApiError } from '@/lib/errors'// Mock the global rate limitervi.mock('@/api/rate-limiter', () => ({@@ -230,31 +231,42 @@ describe('buildApiFetcher', () => {})describe('error handling', () => {- it('should throw error on non-429 error responses', async () => {- const mockErrorResponse = new Response(JSON.stringify({ error: 'Not found' }), {- status: 404,- })-- vi.mocked(global.fetch).mockResolvedValueOnce(mockErrorResponse)+ it('should throw a typed PostHogApiError on non-429 4xx responses', async () => {+ vi.mocked(global.fetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'Not found' }), {+ status: 404,+ statusText: 'Not Found',+ })+ )const fetcher = buildApiFetcher(mockConfig)- await expect(fetcher.fetch(baseFetchInput)).rejects.toThrow('Failed request: [404]')+ const thrown = await fetcher.fetch(baseFetchInput).catch((err) => err)+ expect(thrown).toBeInstanceOf(PostHogApiError)+ expect(thrown).toMatchObject({+ status: 404,+ statusText: 'Not Found',+ })+ expect(thrown.message).toContain('Failed request: [404]')// Should not retry on non-429 errorsexpect(global.fetch).toHaveBeenCalledTimes(1)})- it('should throw error on 500 server errors without retry', async () => {- const mockErrorResponse = new Response(JSON.stringify({ error: 'Internal error' }), {- status: 500,- })-- vi.mocked(global.fetch).mockResolvedValueOnce(mockErrorResponse)+ it('should throw a typed PostHogApiError on 5xx responses without retry', async () => {+ vi.mocked(global.fetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'Internal error' }), {+ status: 500,+ statusText: 'Internal Server Error',+ })+ )const fetcher = buildApiFetcher(mockConfig)- await expect(fetcher.fetch(baseFetchInput)).rejects.toThrow('Failed request: [500]')+ const thrown = await fetcher.fetch(baseFetchInput).catch((err) => err)+ expect(thrown).toBeInstanceOf(PostHogApiError)+ expect(thrown.status).toBe(500)+ expect(thrown.message).toContain('Failed request: [500]')expect(global.fetch).toHaveBeenCalledTimes(1)})diff --git a/services/mcp/tests/unit/permission-errors.test.ts b/services/mcp/tests/unit/permission-errors.test.tsindex 0d6effcb0a59..842d50c8697c 100644--- a/services/mcp/tests/unit/permission-errors.test.ts+++ b/services/mcp/tests/unit/permission-errors.test.ts@@ -6,7 +6,9 @@ import {findPostHogPermissionError,formatPermissionErrorMessage,handleToolError,+ PostHogApiError,PostHogPermissionError,+ PostHogValidationError,wrapError,} from '@/lib/errors'@@ -370,3 +372,109 @@ describe('ApiClient fetchJson on 403 permission_denied', () => {vi.unstubAllGlobals()})})++// Regression: an LLM agent passing a placeholder UUID to an MCP tool produced+// a 404, and `handleToolError` captured it as a PostHog exception fingerprinted+// by tool name — creating a brand-new error tracking issue per tool every time+// an agent fumbled a parameter. `handleToolError` must treat 4xx (and+// validation errors) as recoverable agent input and reserve `captureException`+// for 5xx and unexpected non-HTTP errors.+describe('handleToolError with API errors', () => {+ beforeEach(() => {+ captureException.mockClear()+ })++ // Boundary coverage: include 499 and 500 in the tables so an off-by-one+ // in the `status < 500` guard (e.g. `<=` instead of `<`) gets caught.+ it.each([+ { status: 400, statusText: 'Bad Request' },+ { status: 404, statusText: 'Not Found' },+ { status: 422, statusText: 'Unprocessable Entity' },+ { status: 499, statusText: 'Client Closed Request' },+ ])(+ 'short-circuits $status PostHogApiError without capturing an exception',+ ({ status, statusText }: { status: number; statusText: string }) => {+ const error = new PostHogApiError({+ status,+ statusText,+ body: '{"detail":"Not found."}',+ url: 'https://us.posthog.com/api/environments/2/symbol_sets/00000000-0000-0000-0000-000000000000/',+ method: 'GET',+ })++ const result = handleToolError(error, 'error-tracking-symbol-sets-retrieve')++ expect(captureException).not.toHaveBeenCalled()+ expect(result.isError).toBe(true)+ const [content] = result.content as Array<{ type: string; text: string }>+ expect(content?.text).toContain('[error-tracking-symbol-sets-retrieve]')+ expect(content?.text).toContain(`Status Code: ${status}`)+ }+ )++ it.each([+ { status: 500, statusText: 'Internal Server Error' },+ { status: 502, statusText: 'Bad Gateway' },+ { status: 503, statusText: 'Service Unavailable' },+ ])(+ 'captures $status PostHogApiError as an exception (real service failure)',+ ({ status, statusText }: { status: number; statusText: string }) => {+ const error = new PostHogApiError({+ status,+ statusText,+ body: '{"detail":"oops"}',+ url: 'https://us.posthog.com/api/environments/2/symbol_sets/abc/',+ method: 'GET',+ })++ const result = handleToolError(error, 'error-tracking-symbol-sets-retrieve')++ expect(captureException).toHaveBeenCalledTimes(1)+ expect(result.isError).toBe(true)+ }+ )++ it('short-circuits PostHogValidationError without capturing an exception', () => {+ const error = new PostHogValidationError({+ detail: 'invalid uuid',+ attr: 'id',+ code: 'invalid',+ extra: undefined,+ url: 'https://us.posthog.com/api/environments/2/symbol_sets/not-a-uuid/',+ method: 'GET',+ })++ const result = handleToolError(error, 'error-tracking-symbol-sets-retrieve')++ expect(captureException).not.toHaveBeenCalled()+ expect(result.isError).toBe(true)+ const [content] = result.content as Array<{ type: string; text: string }>+ expect(content?.text).toContain('Validation error')+ expect(content?.text).toContain('field: id')+ })++ it('unwraps a 4xx PostHogApiError hidden behind Error.cause', () => {+ const original = new PostHogApiError({+ status: 404,+ statusText: 'Not Found',+ body: '{"detail":"Not found."}',+ url: 'https://us.posthog.com/api/environments/2/symbol_sets/00000000-0000-0000-0000-000000000000/',+ method: 'GET',+ })+ const wrapped = wrapError('Failed to retrieve symbol set', original)++ const result = handleToolError(wrapped, 'error-tracking-symbol-sets-retrieve')++ expect(captureException).not.toHaveBeenCalled()+ expect(result.isError).toBe(true)+ })++ it('still captures unexpected non-HTTP errors', () => {+ const error = new Error('boom — something unexpected went wrong')++ const result = handleToolError(error, 'some-tool')++ expect(captureException).toHaveBeenCalledTimes(1)+ expect(result.isError).toBe(true)+ })+})