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): classify streaming tool failures by HTTP status (#71414)

posthog[bot]085866d852f7
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 27f210b788f3..1808a44ea329 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -294,9 +294,11 @@ export class ApiClient {
if (!response.ok) {
const errorText = await response.text()
- throw new Error(
- `SSE request failed:\nURL: ${opts.method} ${url}\nStatus Code: ${response.status} (${response.statusText})\nError Message: ${errorText}`
- )
+ // Mirror fetchJson's typed-error mapping so a failed streaming call
+ // (e.g. a backend 4xx validation rejection) is classified as
+ // `validation`/`api_4xx` rather than collapsing into the generic
+ // `internal` bucket and minting a spurious error-tracking issue.
+ throw this.buildApiError(response, errorText, url, opts.method)
}
if (!response.body) {
@@ -352,6 +354,78 @@ export class ApiClient {
}
}
+ /**
+ * Maps a non-OK PostHog API response to the typed error that best describes
+ * it (invalid key, rate limit, permission, validation, or generic API
+ * error). Shared by fetchJson and the SSE path (requestSSE) so both surface
+ * the same recoverable-vs-genuine-failure signal to the tool-error
+ * classifier — a streaming failure should be classified by its HTTP status,
+ * not lumped into `internal`.
+ *
+ * The response body is read by the caller (SSE and JSON paths read it at
+ * different points) and passed in as `errorText`.
+ */
+ private buildApiError(response: Response, errorText: string, url: string, method: string): Error {
+ if (response.status === 401) {
+ return new Error(ErrorCode.INVALID_API_KEY)
+ }
+
+ if (response.status === 429) {
+ return new PostHogRateLimitError({
+ body: errorText,
+ url,
+ method,
+ retryAfterSeconds: parseRetryAfterSeconds(response.headers.get('Retry-After')),
+ })
+ }
+
+ let errorData: any
+ try {
+ errorData = JSON.parse(errorText)
+ } catch {
+ errorData = { detail: errorText }
+ }
+
+ if (response.status === 403 && errorData?.code === 'permission_denied') {
+ const scopeMatch = /required scope ['"]([^'"]+)['"]/.exec(errorData.detail || '')
+ const missingScope = scopeMatch?.[1]
+ // Warn, not error: PostHogPermissionError is thrown and handled by callers,
+ // and a missing scope is a user-config issue rather than a service bug.
+ console.warn(
+ `[API] Permission denied on ${method} ${url}: ${errorData.detail || 'unknown'}${missingScope ? ` (missing scope: ${missingScope})` : ''}`
+ )
+ return new PostHogPermissionError({
+ detail: errorData.detail || 'permission denied',
+ missingScope,
+ url,
+ method,
+ })
+ }
+
+ if (errorData?.type === 'validation_error') {
+ const detail = errorData.detail || errorData.code || 'unknown'
+ const attrLog = errorData.attr ? ` (field: ${errorData.attr})` : ''
+ console.error(`[API] Validation error on ${method} ${url}: ${detail}${attrLog}`)
+ return new PostHogValidationError({
+ detail,
+ attr: errorData.attr ?? undefined,
+ code: errorData.code ?? undefined,
+ extra: (errorData.extra ?? undefined) as Record<string, unknown> | undefined,
+ url,
+ method,
+ })
+ }
+
+ console.error(`[API] Request failed on ${method} ${url}: ${response.status} ${response.statusText}`)
+ return new PostHogApiError({
+ status: response.status,
+ statusText: response.statusText,
+ body: errorText,
+ url,
+ method,
+ })
+ }
+
private async fetchJson<T>(url: string, options?: RequestInit): Promise<Result<T>> {
const method = options?.method ?? 'GET'
let waitBudgetMs = RATE_LIMIT_TOTAL_WAIT_BUDGET_MS
@@ -402,49 +476,8 @@ export class ApiClient {
}
if (!response.ok) {
- if (response.status === 401) {
- throw new Error(ErrorCode.INVALID_API_KEY)
- }
-
const errorText = await response.text()
- let errorData: any
- try {
- errorData = JSON.parse(errorText)
- } catch {
- errorData = { detail: errorText }
- }
-
- if (response.status === 403 && errorData?.code === 'permission_denied') {
- const scopeMatch = /required scope ['"]([^'"]+)['"]/.exec(errorData.detail || '')
- const missingScope = scopeMatch?.[1]
- // Warn, not error: PostHogPermissionError is thrown and handled by callers,
- // and a missing scope is a user-config issue rather than a service bug.
- console.warn(
- `[API] Permission denied on ${method} ${url}: ${errorData.detail || 'unknown'}${missingScope ? ` (missing scope: ${missingScope})` : ''}`
- )
- throw new PostHogPermissionError({
- detail: errorData.detail || 'permission denied',
- missingScope,
- url,
- method,
- })
- }
-
- if (errorData.type === 'validation_error') {
- const detail = errorData.detail || errorData.code || 'unknown'
- const attrLog = errorData.attr ? ` (field: ${errorData.attr})` : ''
- console.error(`[API] Validation error on ${method} ${url}: ${detail}${attrLog}`)
- throw new PostHogValidationError({
- detail,
- attr: errorData.attr ?? undefined,
- code: errorData.code ?? undefined,
- extra: (errorData.extra ?? undefined) as Record<string, unknown> | undefined,
- url,
- method,
- })
- }
-
if (response.status === 404) {
const experimentMatch = /\/experiments\/(\d+)/.exec(url)
if (experimentMatch) {
@@ -458,14 +491,7 @@ export class ApiClient {
}
}
- console.error(`[API] Request failed on ${method} ${url}: ${response.status} ${response.statusText}`)
- throw new PostHogApiError({
- status: response.status,
- statusText: response.statusText,
- body: errorText,
- url,
- method,
- })
+ throw this.buildApiError(response, errorText, url, method)
}
const rawText = await response.text()
diff --git a/services/mcp/tests/unit/requestSSE.test.ts b/services/mcp/tests/unit/requestSSE.test.ts
index ae0e43e52d36..e0f6f0d2443c 100644
--- a/services/mcp/tests/unit/requestSSE.test.ts
+++ b/services/mcp/tests/unit/requestSSE.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiClient } from '@/api/client'
+import { PostHogApiError, PostHogValidationError } from '@/lib/errors'
function createMockStream(chunks: string[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder()
@@ -121,20 +122,37 @@ describe('ApiClient.requestSSE', () => {
expect(onEvent).toHaveBeenNthCalledWith(2, 'done', { completed: ['abc'], failed: [] })
})
- it('should throw with status code and error text on HTTP error response', async () => {
- const mockResponse = new Response('Unauthorized', {
- status: 401,
- statusText: 'Unauthorized',
+ // A failed streaming call must surface the same typed error the non-streaming
+ // path (fetchJson) does, so the tool-error classifier can bucket it by HTTP
+ // status. Before this, requestSSE threw a plain Error that always collapsed
+ // to `internal` — hiding backend 4xx validation rejections and minting a
+ // spurious error-tracking issue for each.
+ it('should throw a typed PostHogValidationError on a backend validation_error response', async () => {
+ const mockResponse = new Response(
+ JSON.stringify({ type: 'validation_error', code: 'invalid', detail: 'session_ids must not be empty' }),
+ { status: 400, statusText: 'Bad Request' }
+ )
+ vi.stubGlobal('fetch', makeMockFetch(mockResponse))
+
+ const err = await client
+ .requestSSE({ method: 'POST', path: '/api/stream', onEvent: vi.fn() })
+ .catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(PostHogValidationError)
+ expect((err as PostHogValidationError).detail).toBe('session_ids must not be empty')
+ })
+
+ it('should throw a typed PostHogApiError carrying the status on a 5xx response', async () => {
+ const mockResponse = new Response('Internal Server Error', {
+ status: 500,
+ statusText: 'Internal Server Error',
})
vi.stubGlobal('fetch', makeMockFetch(mockResponse))
- await expect(
- client.requestSSE({
- method: 'GET',
- path: '/api/stream',
- onEvent: vi.fn(),
- })
- ).rejects.toThrow('401')
+ const err = await client
+ .requestSSE({ method: 'GET', path: '/api/stream', onEvent: vi.fn() })
+ .catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(PostHogApiError)
+ expect((err as PostHogApiError).status).toBe(500)
})
it('should throw when response body is missing', async () => {