: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): accurately report downstream django errors (#64429)
Joshua Snyder948faf7526b1
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 61f6144f6578..390939fde341 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -344,6 +344,8 @@ function classifyToolError(error: unknown, toolName: string): void {const apiError = findRecoverableApiError(error)if (apiError instanceof PostHogValidationError) {toolErrorsTotal.inc({ tool: toolName, error_type: 'validation' })+ } else if (apiError instanceof PostHogApiError && apiError.status === 429) {+ toolErrorsTotal.inc({ tool: toolName, error_type: 'rate_limited' })} else if (apiError instanceof PostHogApiError && apiError.status >= 500) {toolErrorsTotal.inc({ tool: toolName, error_type: 'api_5xx' })} else if (apiError instanceof PostHogApiError) {diff --git a/services/mcp/src/tools/posthogAiTools/invokeTool.ts b/services/mcp/src/tools/posthogAiTools/invokeTool.tsindex 3ebbd0f474b5..34328ad12fd7 100644--- a/services/mcp/src/tools/posthogAiTools/invokeTool.ts+++ b/services/mcp/src/tools/posthogAiTools/invokeTool.ts@@ -1,3 +1,10 @@+import {+ parseRetryAfterSeconds,+ PostHogApiError,+ PostHogPermissionError,+ PostHogRateLimitError,+ PostHogValidationError,+} from '@/lib/errors'import type { Context } from '@/tools/types'export interface McpToolResult {@@ -20,10 +27,11 @@ export async function invokeMcpTool(): Promise<McpToolResult> {const projectId = await context.stateManager.getProjectId()+ const method = 'POST'const url = `${context.api.baseUrl}/api/environments/${projectId}/mcp_tools/${toolName}/`const response = await fetch(url, {- method: 'POST',+ method,headers: {Authorization: `Bearer ${context.api.config.apiToken}`,'Content-Type': 'application/json',@@ -32,19 +40,59 @@ export async function invokeMcpTool(})if (!response.ok) {- const errorText = await response.text()- let errorMessage: string- try {- const errorData = JSON.parse(errorText)- errorMessage = errorData.content || errorText- } catch {- errorMessage = errorText- }- return {- success: false,- content: `Failed to invoke MCP tool '${toolName}': ${errorMessage}`,- }+ // Surface the typed errors the main ApiClient throws so error+ // classification can tell a rate limit apart from a server fault.+ throw await buildInvokeError(response, method, url)}return response.json() as Promise<McpToolResult>}++async function buildInvokeError(response: Response, method: string, url: string): Promise<Error> {+ const body = await response.text()++ if (response.status === 429) {+ return new PostHogRateLimitError({+ body,+ url,+ method,+ retryAfterSeconds: parseRetryAfterSeconds(response.headers.get('Retry-After')),+ })+ }++ let errorData: any+ try {+ errorData = JSON.parse(body)+ } catch {+ errorData = { detail: body }+ }++ if (response.status === 403 && errorData?.code === 'permission_denied') {+ const scopeMatch = /required scope ['"]([^'"]+)['"]/.exec(errorData.detail || '')+ return new PostHogPermissionError({+ detail: errorData.detail || 'permission denied',+ missingScope: scopeMatch?.[1],+ url,+ method,+ })+ }++ if (errorData?.type === 'validation_error') {+ return new PostHogValidationError({+ detail: errorData.detail || errorData.code || 'unknown',+ attr: errorData.attr ?? undefined,+ code: errorData.code ?? undefined,+ extra: (errorData.extra ?? undefined) as Record<string, unknown> | undefined,+ url,+ method,+ })+ }++ return new PostHogApiError({+ status: response.status,+ statusText: response.statusText,+ body,+ url,+ method,+ })+}diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 2f5c19d69aef..c5b599e209a4 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -36,6 +36,7 @@ vi.mock('@/resources', () => ({import { z } from 'zod'+import { PostHogRateLimitError, wrapError } from '@/lib/errors'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'@@ -143,6 +144,43 @@ describe('ToolExecutor metrics', () => {expect(mockToolDurationStartTimer.mock.results[0]!.value).toHaveBeenCalledWith({ status: 'error' })})+ it('classifies a downstream 429 as rate_limited, keeping it out of the error rate', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('execute-sql', async () => {+ throw new PostHogRateLimitError({+ body: '{}',+ url: 'https://us.posthog.com/api/environments/2/mcp_tools/execute_sql/',+ method: 'POST',+ retryAfterSeconds: 5,+ })+ }) as any+ )++ await executor.handleToolCall({ name: 'execute-sql', arguments: {} }, makeState([{ name: 'execute-sql' }]))++ expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })+ })++ it('classifies a 429 wrapped in a cause chain as rate_limited', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('execute-sql', async () => {+ throw wrapError(+ 'Failed to run query',+ new PostHogRateLimitError({+ body: '{}',+ url: 'https://us.posthog.com/api/environments/2/mcp_tools/execute_sql/',+ method: 'POST',+ retryAfterSeconds: null,+ })+ )+ }) as any+ )++ await executor.handleToolCall({ name: 'execute-sql', arguments: {} }, makeState([{ name: 'execute-sql' }]))++ expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })+ })+it('records validation_error without starting a timer', async () => {vi.spyOn(catalog, 'getToolByName').mockReturnValue({name: 'strict-tool',diff --git a/services/mcp/tests/tools/invokeTool.test.ts b/services/mcp/tests/tools/invokeTool.test.tsnew file mode 100644index 000000000000..f817a45dcacb--- /dev/null+++ b/services/mcp/tests/tools/invokeTool.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { PostHogApiError, PostHogPermissionError, PostHogRateLimitError, PostHogValidationError } from '@/lib/errors'+import { invokeMcpTool } from '@/tools/posthogAiTools/invokeTool'+import type { Context } from '@/tools/types'++function makeContext(): Context {+ return {+ api: {+ baseUrl: 'https://us.posthog.com',+ config: { apiToken: 'phx_test' },+ },+ stateManager: {+ getProjectId: vi.fn().mockResolvedValue(2),+ },+ } as unknown as Context+}++describe('invokeMcpTool', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ const stubFetch = (response: Response): void => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response))+ }++ it('returns the tool result on success', async () => {+ stubFetch(new Response(JSON.stringify({ success: true, content: 'rows' }), { status: 200 }))++ const result = await invokeMcpTool(makeContext(), 'execute_sql', { query: 'SELECT 1' })++ expect(result).toEqual({ success: true, content: 'rows' })+ })++ it('throws PostHogRateLimitError on a 429 so it is not bucketed as an internal error', async () => {+ stubFetch(+ new Response(JSON.stringify({ detail: 'Request was throttled.' }), {+ status: 429,+ headers: { 'Retry-After': '7' },+ })+ )++ const error = await invokeMcpTool(makeContext(), 'execute_sql', { query: 'SELECT 1' }).catch((e) => e)++ expect(error).toBeInstanceOf(PostHogRateLimitError)+ expect(error).toBeInstanceOf(PostHogApiError)+ expect((error as PostHogRateLimitError).status).toBe(429)+ expect((error as PostHogRateLimitError).retryAfterSeconds).toBe(7)+ })++ it('throws PostHogApiError carrying the status on a 5xx', async () => {+ stubFetch(new Response('upstream exploded', { status: 503, statusText: 'Service Unavailable' }))++ const error = await invokeMcpTool(makeContext(), 'execute_sql', { query: 'SELECT 1' }).catch((e) => e)++ expect(error).toBeInstanceOf(PostHogApiError)+ expect((error as PostHogApiError).status).toBe(503)+ })++ it('throws PostHogPermissionError on a 403 permission_denied', async () => {+ stubFetch(+ new Response(JSON.stringify({ code: 'permission_denied', detail: "required scope 'query:read'" }), {+ status: 403,+ })+ )++ const error = await invokeMcpTool(makeContext(), 'execute_sql', { query: 'SELECT 1' }).catch((e) => e)++ expect(error).toBeInstanceOf(PostHogPermissionError)+ expect((error as PostHogPermissionError).missingScope).toBe('query:read')+ })++ it('throws PostHogValidationError on a validation_error body', async () => {+ stubFetch(+ new Response(JSON.stringify({ type: 'validation_error', detail: 'bad query', attr: 'query' }), {+ status: 400,+ })+ )++ const error = await invokeMcpTool(makeContext(), 'execute_sql', { query: 'SELECT 1' }).catch((e) => e)++ expect(error).toBeInstanceOf(PostHogValidationError)+ expect((error as PostHogValidationError).attr).toBe('query')+ })+})