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.

feat(mcp): capture $mcp_error_message on errored tool calls (#71316)

Daniel Visca3a0284e1c0c9
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index d9449d9196ea..4cb926afba36 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -2126,7 +2126,7 @@
"type": "Numeric"
},
"$mcp_error_message": {
- "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",
+ "description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.",
"label": "MCP error message"
},
"$mcp_error_status": {
@@ -4235,7 +4235,7 @@
"type": "Numeric"
},
"$mcp_error_message": {
- "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",
+ "description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.",
"label": "MCP error message"
},
"$mcp_error_status": {
@@ -6938,7 +6938,7 @@
"type": "Numeric"
},
"$mcp_error_message": {
- "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",
+ "description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.",
"label": "MCP error message"
},
"$mcp_error_status": {
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 5844d8e612d6..d12cbd43c784 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2747,7 +2747,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
},
"$mcp_error_message": {
"label": "MCP error message",
- "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",
+ "description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.",
},
"$mcp_server_name": {
"label": "MCP server name",
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 1f17f509a2fb..aa26e3f667cd 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -247,7 +247,7 @@ export class ToolExecutor {
Date.now() - startMs,
true,
state,
- errorAnalyticsProperties(classification),
+ errorAnalyticsProperties(classification, error),
intentMeta
)
@@ -340,7 +340,7 @@ export class ToolExecutor {
Date.now() - startMs,
true,
state,
- errorAnalyticsProperties(classification),
+ errorAnalyticsProperties(classification, error),
intentMeta
)
@@ -463,7 +463,7 @@ export class ToolExecutor {
Date.now() - startMs,
true,
state,
- errorAnalyticsProperties(classification),
+ errorAnalyticsProperties(classification, error),
intentMeta
)
const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)
@@ -539,13 +539,78 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification
return { errorType: 'internal' }
}
+// Mirrors the SDK's MAX_ERROR_MESSAGE_LENGTH so `$mcp_error_message` stays within
+// the bound external servers get when they pass `error` to the SDK.
+const MAX_ERROR_MESSAGE_LENGTH = 2048
+
+/**
+ * Extracts a capturable message from a thrown value, restricted to an allowlist
+ * of error classes whose message shape we control. `$mcp_error_message` is
+ * readable by every analytics viewer in the project — not just the caller that
+ * received the tool result — so arbitrary `Error.message`s and thrown strings
+ * are never captured: tools echo caller input into them (document previews, SQL
+ * fragments) and `PostHogApiError`'s default message embeds the upstream
+ * response body. API errors are rebuilt from status + method + URL path instead.
+ */
+function extractErrorMessage(error: unknown): string | undefined {
+ const raw = resolveSafeErrorMessage(error)
+ if (!raw) {
+ return undefined
+ }
+ // Strip control characters except newline/tab (multi-line validation errors stay readable)
+ const sanitized = raw
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '')
+ .trim()
+ .slice(0, MAX_ERROR_MESSAGE_LENGTH)
+ return sanitized || undefined
+}
+
+function resolveSafeErrorMessage(error: unknown): string | undefined {
+ // Static recovery walkthroughs generated by our own constructors.
+ if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {
+ return error.message
+ }
+ // Documented value-free: offending field paths + issue codes, never input values.
+ if (error instanceof ToolInputValidationError) {
+ return error.message
+ }
+ if (error instanceof Error && error.name === 'TimeoutError') {
+ return 'Tool call timed out'
+ }
+ const apiError = findRecoverableApiError(error)
+ if (apiError instanceof PostHogValidationError) {
+ // `detail` is the raw API validation body; for query tools it echoes the caller's
+ // offending HogQL/filter expression (`/query/` resolver errors quote the bad name),
+ // so capture only the controlled code + field, never the free-text detail.
+ const code = apiError.code ? `: ${apiError.code}` : ''
+ const field = apiError.attr ? ` (field: ${apiError.attr})` : ''
+ return `Validation error${code}${field}`
+ }
+ if (apiError instanceof PostHogApiError) {
+ // Rebuilt summary: no response body, no query string.
+ return `HTTP ${apiError.status} ${apiError.statusText} on ${apiError.method} ${safeUrlPath(apiError.url)}`
+ }
+ return undefined
+}
+
+function safeUrlPath(url: string): string {
+ try {
+ return new URL(url).pathname
+ } catch {
+ return ''
+ }
+}
+
/**
* Properties stamped onto an errored `$mcp_tool_call` so the dashboard can slice
* failures by reason. `$mcp_error_type` aligns with the SDK's native field; the
* SDK derives a generic type from the thrown error when none is supplied, and an
- * explicit value here overrides it.
+ * explicit value here overrides it. `$mcp_error_message` carries a sanitized,
+ * allowlisted summary of the failure (see `extractErrorMessage`) so tool-quality
+ * drill-downs can show what went wrong without persisting caller-derived text.
*/
-function errorAnalyticsProperties(classification: ToolErrorClassification): Record<string, unknown> {
+function errorAnalyticsProperties(classification: ToolErrorClassification, error: unknown): Record<string, unknown> {
+ const message = extractErrorMessage(error)
return {
$mcp_error_type: classification.errorType,
...(classification.status !== undefined ? { $mcp_error_status: classification.status } : {}),
@@ -553,5 +618,6 @@ function errorAnalyticsProperties(classification: ToolErrorClassification): Reco
...(classification.validationInputKeys?.length
? { $mcp_validation_input_keys: classification.validationInputKeys }
: {}),
+ ...(message !== undefined ? { $mcp_error_message: message } : {}),
}
}
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 690400bf0973..2fe87e3cef6e 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -42,7 +42,13 @@ import { InstructionsBuilder } from '@/hono/instructions'
import type { ResolvedState } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
import { ToolExecutor } from '@/hono/tool-executor'
-import { PostHogRateLimitError, wrapError } from '@/lib/errors'
+import {
+ PostHogApiError,
+ PostHogRateLimitError,
+ PostHogValidationError,
+ ToolInputValidationError,
+ wrapError,
+} from '@/lib/errors'
const mockTrackToolCall = vi.mocked(trackToolCall)
@@ -173,6 +179,105 @@ describe('ToolExecutor metrics', () => {
expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_type: 'internal' })
})
+ // $mcp_error_message is readable by every analytics viewer in the project, not just
+ // the caller that received the tool result — so only messages whose shape WE control
+ // are captured. Arbitrary thrown values echo caller input (document previews, SQL
+ // fragments, upstream response bodies) and must never reach analytics.
+ it.each([
+ ['a generic Error', new Error('preview of caller document: SECRET=abc123')],
+ ['a thrown string', 'raw string echoing tool input'],
+ ['a non-Error object', { secret_payload: 'do not capture' }],
+ ])('omits $mcp_error_message when the tool throws %s', async (_label, thrown) => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ throw thrown
+ }) as any
+ )
+
+ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+
+ const extras = trackToolCallExtras('fail-tool')
+ expect(extras).toMatchObject({ $mcp_error_type: 'internal' })
+ expect(extras).not.toHaveProperty('$mcp_error_message')
+ })
+
+ it.each([
+ [
+ 'a ToolInputValidationError (value-free field descriptors)',
+ new ToolInputValidationError('Invalid input for tool: date_from (invalid_type)', {
+ fields: ['date_from'],
+ }),
+ 'Invalid input for tool: date_from (invalid_type)',
+ ],
+ [
+ 'a PostHogValidationError (controlled code + field only, never the detail body)',
+ new PostHogValidationError({
+ // detail echoes the caller's offending expression; a query tool caller can
+ // hide a secret here, so it must never reach analytics.
+ detail: 'Unable to resolve field: SECRET=sk_live_abc123',
+ attr: 'query',
+ code: 'invalid_input',
+ extra: undefined,
+ url: 'https://us.posthog.com/api/environments/2/query/',
+ method: 'POST',
+ }),
+ 'Validation error: invalid_input (field: query)',
+ ],
+ [
+ 'a TimeoutError',
+ Object.assign(new Error('deadline of 30000ms exceeded while calling https://internal.example'), {
+ name: 'TimeoutError',
+ }),
+ 'Tool call timed out',
+ ],
+ ])('stamps $mcp_error_message for %s', async (_label, thrown, expected) => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ throw thrown
+ }) as any
+ )
+
+ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+
+ expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_message: expected })
+ })
+
+ it('rebuilds PostHogApiError messages from status + path, never the response body or query string', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ throw new PostHogApiError({
+ status: 502,
+ statusText: 'Bad Gateway',
+ body: '{"secret": "upstream response body must not leak"}',
+ url: 'https://us.posthog.com/api/environments/2/insights/?token=sk_live_secret',
+ method: 'GET',
+ })
+ }) as any
+ )
+
+ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+
+ expect(trackToolCallExtras('fail-tool')).toMatchObject({
+ $mcp_error_message: 'HTTP 502 Bad Gateway on GET /api/environments/2/insights/',
+ })
+ })
+
+ it('truncates $mcp_error_message and strips control characters, keeping newlines', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ // ToolInputValidationError.message is passed through verbatim, so it exercises
+ // the sanitizer/truncation path in extractErrorMessage.
+ throw new ToolInputValidationError(`line2\x00\x08${'x'.repeat(3000)}`, { fields: ['date_from'] })
+ }) as any
+ )
+
+ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+
+ const message = trackToolCallExtras('fail-tool')?.$mcp_error_message as string
+ expect(message.startsWith('line2xxx')).toBe(true)
+ expect(message).toHaveLength(2048)
+ })
+
it('carries the upstream status alongside the error type for API failures', async () => {
vi.spyOn(catalog, 'getToolByName').mockReturnValue(
makeFakeTool('execute-sql', async () => {
@@ -190,6 +295,8 @@ describe('ToolExecutor metrics', () => {
expect(trackToolCallExtras('execute-sql')).toMatchObject({
$mcp_error_type: 'rate_limited',
$mcp_error_status: 429,
+ // Subclasses of PostHogApiError get the same rebuilt-safe message shape.
+ $mcp_error_message: 'HTTP 429 Too Many Requests on POST /api/environments/2/mcp_tools/execute_sql/',
})
})