: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
feat(mcp): record backend error codes in existing analytics (#112567)
posthog[bot]cc34706fea11
diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 5e3909c79236..0b3e14009899 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -481,15 +481,15 @@ class AssistantQueryExecutor:# Check for query execution errors before using resultsif query_status.get("error"):- if rejection := describe_clickhouse_rejection(- query_status.get("error_code"), query_status.get("error_message")- ):- raise MaxToolRetryableError(rejection, error_type="validation")- if error_message := query_status.get("error_message") or internal_ch_error_user_message(- query_status.get("error_code")- ):+ error_code = query_status.get("error_code")+ error_code = (+ error_code.lower() if error_code and internal_ch_error_user_message(error_code) else None+ )+ if rejection := describe_clickhouse_rejection(error_code, query_status.get("error_message")):+ raise MaxToolRetryableError(rejection, error_type="validation", error_code=error_code)+ if error_message := query_status.get("error_message") or internal_ch_error_user_message(error_code):# Async status loses the exception type, so keep retry advice without guessing its category.- raise MaxToolRetryableError(error_message, error_type="internal")+ raise MaxToolRetryableError(error_message, error_type="internal", error_code=error_code)raise Exception("Query failed")# Use the completed query results@@ -537,12 +537,19 @@ class AssistantQueryExecutor:raise MaxToolFatalError(err_message, error_type="api_5xx") from errelif isinstance(err, APIException) and err.status_code == 429:raise MaxToolTransientError(err_message, error_type="rate_limited") from err- raise MaxToolRetryableError(err_message, error_type=error_type) from err+ error_code = (+ look_up_clickhouse_error_code_meta(err).name.lower() if isinstance(err, ExposedCHQueryError) else None+ )+ raise MaxToolRetryableError(+ err_message,+ error_type=error_type,+ error_code=error_code if internal_ch_error_user_message(error_code) else None,+ ) from errexcept Exception as err:- if isinstance(err, InternalCHQueryError) and (- rejection := describe_clickhouse_rejection(look_up_clickhouse_error_code_meta(err).name.lower())- ):- raise MaxToolRetryableError(rejection, error_type="validation") from err+ if isinstance(err, InternalCHQueryError):+ error_code = look_up_clickhouse_error_code_meta(err).name.lower()+ if rejection := describe_clickhouse_rejection(error_code):+ raise MaxToolRetryableError(rejection, error_type="validation", error_code=error_code) from errelapsed = time.time() - start_time# Catch-all for unexpected errors during query execution. Surface the underlying error# text (truncated) so callers can diagnose the failure instead of an opaque message —diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex e43ee0ef2a33..c1f998796587 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -40,7 +40,7 @@ from posthog.hogql.constants import DEFAULT_POSTHOG_AI_RETURNED_ROWSfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context-from posthog.errors import ExposedCHQueryError, InternalCHQueryError+from posthog.errors import CHQueryErrorIllegalTypeOfArgument, ExposedCHQueryError, InternalCHQueryErrorfrom posthog.models import Organization, Team, Userfrom ee.hogai.context.insight.context import InsightContext@@ -307,18 +307,54 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertIn("HogQL error", str(context.exception))+ @parameterized.expand(+ [+ ("unknown", ExposedCHQueryError("ClickHouse error"), "ClickHouse error", "internal", None),+ (+ "argument_type",+ CHQueryErrorIllegalTypeOfArgument("Expected an integer argument", code=43),+ "Expected an integer argument",+ "validation",+ "illegal_type_of_argument",+ ),+ (+ "bad_arguments",+ ExposedCHQueryError("This function requires two arguments", code=36),+ "This function requires two arguments",+ "validation",+ "bad_arguments",+ ),+ (+ "storage_error",+ ExposedCHQueryError("Storage read failed", code=499),+ "Storage read failed",+ "internal",+ "s3_error",+ ),+ (+ "server_error",+ ExposedCHQueryError("Server failure", code=99999, code_name="caller-supplied-name"),+ "Server failure",+ "internal",+ None,+ ),+ ]+ )@patch("ee.hogai.context.insight.query_executor.process_query_dict")- async def test_run_and_format_query_handles_exposed_ch_query_error(self, mock_process_query):- """Test handling of ExposedCHQueryError"""-- mock_process_query.side_effect = ExposedCHQueryError("ClickHouse error")+ async def test_run_and_format_query_handles_exposed_ch_query_error(+ self, _name, error, expected_message, expected_type, expected_code, mock_process_query+ ):+ mock_process_query.side_effect = errorquery = AssistantTrendsQuery(series=[])with self.assertRaises(MaxToolRetryableError) as context:await self.query_runner.arun_and_format_query(query)- self.assertIn("ClickHouse error", str(context.exception))+ self.assertEqual(str(context.exception), expected_message)+ self.assertEqual(context.exception.error_type, expected_type)+ self.assertEqual(context.exception.error_code, expected_code)+ self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")@patch("ee.hogai.context.insight.query_executor.process_query_dict")async def test_run_and_format_query_handles_generic_exception(self, mock_process_query):@@ -418,21 +454,23 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):@parameterized.expand([- ("validation", "Unknown field: missing_column", None, "Unknown field: missing_column"),- ("timeout", "Query timed out", "error", "Query timed out"),+ ("validation", "Unknown field: missing_column", None, "Unknown field: missing_column", None),+ ("timeout", "Query timed out", "error", "Query timed out", None),("memory_limit","Query memory limit exceeded","clickhouse_memory_limit_exceeded","Query memory limit exceeded",+ None,),- ("warehouse_connection", "Warehouse connection failed", None, "Warehouse connection failed"),+ ("warehouse_connection", "Warehouse connection failed", None, "Warehouse connection failed", None),("known_server_code",None,- "too_many_parts",+ "TOO_MANY_PARTS","The database had a temporary problem while it ran this query. ""Wait a few minutes, then run the query again. If the problem continues, contact support.",+ "too_many_parts",),("storage_failure",@@ -440,6 +478,14 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):"s3_error","PostHog couldn't read from storage while running this query. Wait a few minutes, ""then run the query again. If the problem continues, contact support.",+ "s3_error",+ ),+ (+ "unrecognized_code",+ "Query input is invalid",+ '{"property":"synthetic-private-value"}',+ "Query input is invalid",+ None,),])@@ -451,6 +497,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):error_message: str | None,error_code: str | None,expected_message: str,+ expected_code: str | None,mock_get_query_status: Mock,mock_process_query: Mock,) -> None:@@ -475,6 +522,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertEqual(str(context.exception), expected_message)self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")self.assertEqual(context.exception.error_type, "internal")+ self.assertEqual(context.exception.error_code, expected_code)@parameterized.expand([@@ -527,11 +575,12 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):await self.query_runner.arun_and_format_query(AssistantHogQLQuery(query="SELECT 1"))self.assertEqual(str(context.exception), expected_message)self.assertEqual(context.exception.error_type, "validation")+ self.assertEqual(context.exception.error_code, error_code.lower())self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")@parameterized.expand([- (code, code_name, expected_message, expected_exception)+ (code, code_name, name, expected_message, expected_exception)for code, name, expected_message, expected_exception in [(47,@@ -560,7 +609,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):)@patch("ee.hogai.context.insight.query_executor.process_query_dict")async def test_internal_clickhouse_query_rejection(- self, code, code_name, expected_message, expected_exception, mock_process_query+ self, code, code_name, expected_code, expected_message, expected_exception, mock_process_query):mock_process_query.side_effect = InternalCHQueryError("stored-secret", code=code, code_name=code_name)with self.assertRaises(expected_exception) as context:@@ -569,6 +618,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertEqual(str(context.exception), expected_message)if isinstance(context.exception, MaxToolRetryableError):self.assertEqual(context.exception.error_type, "validation")+ self.assertEqual(context.exception.error_code, expected_code)self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")@parameterized.expand([("keeper_exception",), ("syntax_error",), (None,)])diff --git a/ee/hogai/tool_errors.py b/ee/hogai/tool_errors.pyindex dc8a0deb6921..c8b5bcaccd97 100644--- a/ee/hogai/tool_errors.py+++ b/ee/hogai/tool_errors.py@@ -20,15 +20,21 @@ class MaxToolError(Exception):"""error_type: MaxToolErrorType = "internal"+ error_code: str | None = None- def __init__(self, message: str, *, error_type: MaxToolErrorType | None = None) -> None:+ def __init__(+ self, message: str, *, error_type: MaxToolErrorType | None = None, error_code: str | None = None+ ) -> None:"""Args:message: Detailed, actionable error message that helps the LLM understand what went wrong+ error_code: Machine-readable name of the leaf failure, for analytics. It must hold no caller input."""super().__init__(message)if error_type is not None:self.error_type = error_type+ if error_code is not None:+ self.error_code = error_code@propertydef retry_strategy(self) -> Literal["never", "once", "adjusted"]:diff --git a/products/posthog_ai/backend/api/mcp_tools.py b/products/posthog_ai/backend/api/mcp_tools.pyindex 1bba9aad565f..b96f3f5f3ad0 100644--- a/products/posthog_ai/backend/api/mcp_tools.py+++ b/products/posthog_ai/backend/api/mcp_tools.py@@ -46,6 +46,10 @@ class MCPToolResponse(MCPToolResult):error_type: MaxToolErrorType | None = pydantic.Field(default=None, description="Failure category for MCP analytics.")+ error_code: str | None = pydantic.Field(+ default=None,+ description="Machine-readable name of the leaf failure for MCP analytics, such as a ClickHouse error name.",+ )class DocsSearchRequestSerializer(serializers.Serializer):@@ -177,6 +181,7 @@ class MCPToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):"success": False,"content": f"Tool failed: {e.to_summary()}.{e.retry_hint}","error_type": e.error_type,+ **({"error_code": e.error_code} if e.error_code else {}),})except Exception as e:diff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.pyindex 8dc2d9bb8cbf..6e148cdbe7e4 100644--- a/products/posthog_ai/backend/api/test_mcp_tools.py+++ b/products/posthog_ai/backend/api/test_mcp_tools.py@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, Mock, patchfrom django.db import OperationalError-from parameterized import parameterized+from parameterized import param, parameterizedfrom psycopg.errors import QueryCanceledfrom rest_framework import statusfrom rest_framework.exceptions import APIException, PermissionDenied, ValidationError@@ -231,9 +231,15 @@ class TestMCPToolsAPI(APIBaseTest):self.assertEqual(response.json(), expected)mock_runner_cls.return_value.run.assert_called_once()+ @parameterized.expand(+ [+ ("without_code", None, {}),+ ("with_code", "unknown_identifier", {"error_code": "unknown_identifier"}),+ ]+ )@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)- def test_invoke_tool_error_returns_error_response(self, mock_execute):- mock_execute.side_effect = MaxToolRetryableError("Query validation failed: syntax error")+ def test_invoke_tool_error_returns_error_response(self, _name, error_code, expected_extra, mock_execute):+ mock_execute.side_effect = MaxToolRetryableError("Query validation failed: syntax error", error_code=error_code)response = self.client.post(f"/api/environments/{self.team.id}/mcp_tools/execute_sql/",@@ -248,6 +254,7 @@ class TestMCPToolsAPI(APIBaseTest):"success": False,"content": "Tool failed: MaxToolRetryableError: Query validation failed: syntax error. You may retry with adjusted inputs.","error_type": "validation",+ **expected_extra,},)@@ -314,10 +321,11 @@ class TestMCPToolsAPI(APIBaseTest):"internal","Tool failed: MaxToolRetryableError: QueryVisitor has no method visit_select_query. You may retry with adjusted inputs.",),- (+ param(CHQueryErrorIllegalTypeOfArgument("Illegal argument type", code=43),"validation","Tool failed: MaxToolRetryableError: Illegal argument type. You may retry with adjusted inputs.",+ error_code="illegal_type_of_argument",),(CHQueryErrorCorruptedParquetMetadata("Warehouse file metadata is corrupt", code=1001),@@ -361,7 +369,7 @@ class TestMCPToolsAPI(APIBaseTest):)@patch("ee.hogai.context.insight.query_executor.process_query_dict")def test_query_failures_preserve_recovery_advice(- self, error: Exception, error_type: str, content: str, mock_query: Mock+ self, error: Exception, error_type: str, content: str, mock_query: Mock, *, error_code: str | None = None) -> None:mock_query.side_effect = error@@ -372,7 +380,10 @@ class TestMCPToolsAPI(APIBaseTest):)self.assertEqual(response.status_code, 200)- self.assertEqual(response.json(), {"success": False, "content": content, "error_type": error_type})+ expected = {"success": False, "content": content, "error_type": error_type}+ if error_code:+ expected["error_code"] = error_code+ self.assertEqual(response.json(), expected)@parameterized.expand([@@ -397,6 +408,16 @@ class TestMCPToolsAPI(APIBaseTest):"query_was_cancelled","Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Query failed. You may retry with adjusted inputs.",),+ param(+ "storage_error",+ None,+ None,+ "S3_ERROR",+ "Tool failed: MaxToolRetryableError: PostHog couldn't read from storage while running this query. "+ "Wait a few minutes, then run the query again. If the problem continues, contact support.. "+ "You may retry with adjusted inputs.",+ expected_error_code="s3_error",+ ),("polling_error",ConnectionError("Query status unavailable"),@@ -419,6 +440,8 @@ class TestMCPToolsAPI(APIBaseTest):mock_query: Mock,mock_status: Mock,_mock_sleep: AsyncMock,+ *,+ expected_error_code: str | None = None,) -> None:mock_query.return_value = {"query_status": {"id": "test-query-id", "complete": False}}mock_status.side_effect = polling_error@@ -437,7 +460,10 @@ class TestMCPToolsAPI(APIBaseTest):)self.assertEqual(response.status_code, 200)- self.assertEqual(response.json(), {"success": False, "content": content, "error_type": "internal"})+ expected = {"success": False, "content": content, "error_type": "internal"}+ if expected_error_code:+ expected["error_code"] = expected_error_code+ self.assertEqual(response.json(), expected)@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)def test_invoke_tool_unexpected_error_returns_internal_error(self, mock_execute):diff --git a/products/posthog_ai/frontend/generated/api.schemas.ts b/products/posthog_ai/frontend/generated/api.schemas.tsindex 93ea5ad1553f..066e9d65463a 100644--- a/products/posthog_ai/frontend/generated/api.schemas.ts+++ b/products/posthog_ai/frontend/generated/api.schemas.ts@@ -666,6 +666,8 @@ export interface MCPToolResponseApi {success: boolean/** Failure category for MCP analytics. */error_type?: MCPToolResponseApiErrorType+ /** Machine-readable name of the leaf failure for MCP analytics, such as a ClickHouse error name. */+ error_code?: string | null}export interface DocsSearchRequestApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7c59a01a1e8b..488397fb36ad 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -63103,6 +63103,8 @@ export namespace Schemas {success: boolean;/** Failure category for MCP analytics. */error_type?: MCPToolResponseErrorType;+ /** Machine-readable name of the leaf failure for MCP analytics, such as a ClickHouse error name. */+ error_code?: string | null;}/**diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex aac3619038bb..b9a80b5801b8 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -942,7 +942,8 @@ function classifyToolError(error: unknown, toolName: string): ToolErrorClassificfunction resolveToolErrorClassification(error: unknown): ToolErrorClassification {if (error instanceof MCPToolResultError) {- return { errorType: error.errorType }+ const errorCode = error.errorCode ? sanitizeErrorToken(error.errorCode) : undefined+ return { errorType: error.errorType, ...(errorCode ? { errorCode } : {}) }}if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {return { errorType: 'missing_context' }diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 939f0b833e5b..cbf345632801 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -27,7 +27,8 @@ export class MCPToolError extends Error {export class MCPToolResultError extends Error {constructor(message: string,- public readonly errorType: NonNullable<Schemas.MCPToolResponse['error_type']>+ public readonly errorType: NonNullable<Schemas.MCPToolResponse['error_type']>,+ public readonly errorCode?: string) {super(message)this.name = 'MCPToolResultError'diff --git a/services/mcp/src/tools/posthogAiTools/invokeTool.ts b/services/mcp/src/tools/posthogAiTools/invokeTool.tsindex 35e9b9e64691..5cbd0ce126e4 100644--- a/services/mcp/src/tools/posthogAiTools/invokeTool.ts+++ b/services/mcp/src/tools/posthogAiTools/invokeTool.ts@@ -32,7 +32,9 @@ export async function invokeMcpTool(body: { args },})if (!result.success) {- throw result.error_type ? new MCPToolResultError(result.content, result.error_type) : new Error(result.content)+ throw result.error_type+ ? new MCPToolResultError(result.content, result.error_type, result.error_code ?? undefined)+ : new Error(result.content)}return result}diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 98d081861e57..589277b87326 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -44,6 +44,7 @@ import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'import {+ MCPToolResultError,PostHogApiError,PostHogRateLimitError,PostHogValidationError,@@ -119,6 +120,7 @@ describe('ToolExecutor metrics', () => {{ tool: 'execute-sql', useSingleExec: false, type: 'internal' },{ tool: 'execute-sql', useSingleExec: true, type: 'internal' },{ tool: 'execute-sql', useSingleExec: true, type: 'validation' },+ { tool: 'execute-sql', useSingleExec: false, type: 'validation' },{ tool: 'execute-sql', useSingleExec: false, type: 'memory_limit' },{ tool: 'execute-sql', useSingleExec: true, type: 'memory_limit' },{ tool: 'read-data-schema', useSingleExec: false, type: 'permission' },@@ -142,6 +144,7 @@ describe('ToolExecutor metrics', () => {success: false,content,error_type: type,+ error_code: type === 'validation' ? 'unknown_identifier' : undefined,})))@@ -162,6 +165,11 @@ describe('ToolExecutor metrics', () => {expect(captureException).toHaveBeenCalledTimes(['validation', 'permission'].includes(type) ? 0 : 1)const properties = trackToolCallExtras(tool)expect(properties).toMatchObject({ $mcp_error_type: type, $mcp_error_message: `Tool failed: ${type}` })+ if (type === 'validation') {+ expect(properties?.$mcp_error_code).toBe('unknown_identifier')+ } else {+ expect(properties).not.toHaveProperty('$mcp_error_code')+ }expect(JSON.stringify(properties)).not.toContain('private caller query')const errorMetadata = {isError: true,@@ -293,6 +301,47 @@ describe('ToolExecutor metrics', () => {expect(JSON.stringify(extras)).not.toContain("'from' property")})+ // A tool that fails inside PostHog's backend answers with an error type and, when the+ // backend knows it, the leaf failure name. Without the name every such failure reads+ // as one `internal` or `validation` bucket.+ it.each([+ ['a code from the backend', 'unknown_identifier', 'unknown_identifier'],+ ['a code with control characters', 'bad\ncode ', 'badcode'],+ ])('stamps $mcp_error_code for an MCPToolResultError with %s', async (_label, errorCode, expected) => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('fail-tool', async () => {+ throw new MCPToolResultError('Tool failed', 'validation', errorCode)+ }) as any+ )++ await executor.handleToolCall(+ { name: 'fail-tool', arguments: {} },+ makeToolExecutorState([{ name: 'fail-tool' }])+ )++ expect(trackToolCallExtras('fail-tool')).toMatchObject({+ $mcp_error_type: 'validation',+ $mcp_error_code: expected,+ })+ })++ it('omits $mcp_error_code for an MCPToolResultError without a code', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('fail-tool', async () => {+ throw new MCPToolResultError('Tool failed', 'internal')+ }) as any+ )++ await executor.handleToolCall(+ { name: 'fail-tool', arguments: {} },+ makeToolExecutorState([{ name: 'fail-tool' }])+ )++ const extras = trackToolCallExtras('fail-tool')+ expect(extras).toMatchObject({ $mcp_error_type: 'internal' })+ expect(extras).not.toHaveProperty('$mcp_error_code')+ })+it.each([['a ToolInputValidationError (value-free field descriptors)',diff --git a/services/mcp/tests/tools/invokeTool.test.ts b/services/mcp/tests/tools/invokeTool.test.tsindex 7d14c622d570..1fef82052ad0 100644--- a/services/mcp/tests/tools/invokeTool.test.ts+++ b/services/mcp/tests/tools/invokeTool.test.ts@@ -1,7 +1,13 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { ApiClient } from '@/api/client'-import { PostHogApiError, PostHogPermissionError, PostHogRateLimitError, PostHogValidationError } from '@/lib/errors'+import {+ MCPToolResultError,+ PostHogApiError,+ PostHogPermissionError,+ PostHogRateLimitError,+ PostHogValidationError,+} from '@/lib/errors'import { invokeMcpTool } from '@/tools/posthogAiTools/invokeTool'import type { Context } from '@/tools/types'@@ -37,6 +43,37 @@ describe('invokeMcpTool', () => {expect(result).toEqual({ success: true, content: 'rows' })})+ it.each(['unknown_identifier', null, undefined])(+ 'preserves backend error type and optional code through the API client: %s',+ async (errorCode) => {+ const content =+ 'Tool failed: MaxToolRetryableError: Check the column names. You may retry with adjusted inputs.'+ stubFetch(+ new Response(+ JSON.stringify({+ success: false,+ content,+ error_type: 'validation',+ error_code: errorCode,+ }),+ { status: 200 }+ )+ )++ const error = await invokeMcpTool(makeContext(), 'execute_sql', { query: 'SELECT missing_column' }).catch(+ (e) => e+ )++ expect(error).toBeInstanceOf(MCPToolResultError)+ expect({ message: error.message, errorType: error.errorType, errorCode: error.errorCode }).toEqual({+ message: content,+ errorType: 'validation',+ errorCode: errorCode ?? undefined,+ })+ expect(fetch).toHaveBeenCalledOnce()+ }+ )+it('keeps failures from older backends as errors during a rolling deploy', async () => {stubFetch(new Response(JSON.stringify({ success: false, content: 'Tool failed' })))