: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): preserve existing query errors and retry advice (#107927)
Vasco de Krijger6b7bdc6ae5db
diff --git a/ee/hogai/chat_agent/query_executor/nodes.py b/ee/hogai/chat_agent/query_executor/nodes.pyindex 0aad818b7b73..d981514f0c75 100644--- a/ee/hogai/chat_agent/query_executor/nodes.py+++ b/ee/hogai/chat_agent/query_executor/nodes.py@@ -8,7 +8,7 @@ from ee.hogai.artifacts.utils import unwrap_visualization_artifact_contentfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.core.node import AssistantNode-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolErrorfrom ee.hogai.utils.types import AssistantState, PartialAssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessage@@ -39,7 +39,7 @@ class QueryExecutorNode(AssistantNode):event_source=self.context_manager.event_source,)formatted_query_result = await context.execute_and_format()- except MaxToolRetryableError as err:+ except MaxToolError as err:# Handle known query execution errors (exposed to users)return PartialAssistantState(messages=[diff --git a/ee/hogai/chat_agent/query_executor/test/test_nodes.py b/ee/hogai/chat_agent/query_executor/test/test_nodes.pyindex 5a3ea736eecd..0fd65be2f99f 100644--- a/ee/hogai/chat_agent/query_executor/test/test_nodes.py+++ b/ee/hogai/chat_agent/query_executor/test/test_nodes.py@@ -243,7 +243,7 @@ class TestQueryExecutorNode(ClickhouseTestMixin, NonAtomicBaseTest):assert isinstance(msg, AssistantMessage)self.assertEqual(msg.content,- "There was an error running this query: Error executing query: This query exceeds the capabilities of our picolator. Try de-brolling its flim-flam.",+ "There was an error running this query: This query exceeds the capabilities of our picolator. Try de-brolling its flim-flam.",)self.assertEqual(msg.type, "ai")self.assertIsNotNone(msg.id)diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex 596b687d7ccc..030f1d75e140 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -9,7 +9,7 @@ from posthog.sync import database_sync_to_asyncfrom products.product_analytics.backend.facade.models import Insightfrom ee.hogai.context.insight.query_executor import execute_and_format_query-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolError, MaxToolRetryableErrorfrom ee.hogai.utils.helpers import build_insight_urlfrom ee.hogai.utils.prompt import format_prompt_stringfrom ee.hogai.utils.query import validate_assistant_query@@ -108,8 +108,10 @@ class InsightContext:error_message = f"Error executing query: {str(e)}"if return_exceptions:results = error_message+ elif isinstance(e, MaxToolError):+ raiseelse:- raise MaxToolRetryableError(error_message)+ raise MaxToolRetryableError(error_message, error_type="internal") from ereturn format_prompt_string(prompt_template,diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 4550ba0676fe..eda002e356a9 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -13,7 +13,7 @@ import structlogfrom asgiref.sync import async_to_syncfrom posthoganalytics import capture_exceptionfrom pydantic import BaseModel-from rest_framework.exceptions import APIException+from rest_framework.exceptions import APIException, PermissionDeniedfrom posthog.schema import (AssistantFunnelsQuery,@@ -39,14 +39,19 @@ from posthog.hogql.constants import LimitContextfrom posthog.hogql.errors import (ExposedHogQLError,NotImplementedError as HogQLNotImplementedError,+ QueryError,+ SyntaxError as HogQLSyntaxError,+ TableAccessDeniedError,)from posthog.api.services.query import process_query_dictfrom posthog.clickhouse.client.execute_async import get_query_status+from posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queries, tags_contextfrom posthog.dataclasses import frozen-from posthog.errors import ExposedCHQueryError+from posthog.errors import CH_TRANSIENT_ERRORS, ExposedCHQueryError, QueryErrorCategory, classify_query_errorfrom posthog.event_usage import EventSource+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOutfrom posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES, ExecutionModefrom posthog.models import Teamfrom posthog.sync import database_sync_to_async@@ -69,7 +74,14 @@ from ee.hogai.context.insight.format import (get_boxplot_results,is_boxplot_query,)-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import (+ MaxToolAccessDeniedError,+ MaxToolError,+ MaxToolErrorType,+ MaxToolFatalError,+ MaxToolRetryableError,+ MaxToolTransientError,+)from ee.hogai.utils.prompt import format_prompt_stringfrom ee.hogai.utils.query import validate_assistant_queryfrom ee.hogai.utils.types.base import AnyAssistantGeneratedQuery, AnyPydanticModelQuery@@ -97,6 +109,20 @@ logger = structlog.get_logger(__name__)TIMING_LOG_PREFIX = "[QUERY_EXECUTOR]"+def _hogql_tool_error(error: ExposedHogQLError) -> MaxToolError:+ cause: BaseException = error+ seen: set[int] = set()+ while type(cause) is ExposedHogQLError and cause.__cause__ is not None and id(cause) not in seen:+ seen.add(id(cause))+ cause = cause.__cause__++ if isinstance(cause, TableAccessDeniedError):+ return MaxToolFatalError(str(error), error_type="permission")+ # User-safe errors can also describe outages; only known input errors should skip exception capture.+ error_type: MaxToolErrorType = "validation" if isinstance(cause, (QueryError, HogQLSyntaxError)) else "internal"+ return MaxToolRetryableError(str(error), error_type=error_type)++@frozenclass FormattedQueryResult:formatted: str@@ -440,25 +466,37 @@ class AssistantQueryExecutor:logger.error(f"{TIMING_LOG_PREFIX} Query timeout after {poll_count} polls, {polling_elapsed:.3f}s")- raise APIException(+ raise ClickHouseQueryTimeOut("Query hasn't completed in time. It's worth trying again, maybe with a shorter time range.")# Check for query execution errors before using resultsif query_status.get("error"):if error_message := query_status.get("error_message"):- raise APIException(error_message)+ # Async status loses the exception type, so keep retry advice without guessing its category.+ raise MaxToolRetryableError(error_message, error_type="internal")raise Exception("Query failed")# Use the completed query resultsresponse_dict = query_status["results"]+ except MaxToolError:+ raise+ except UserAccessControlError as err:+ raise MaxToolAccessDeniedError(err.resource, err.required_level) from err+ except (PermissionDenied, TableAccessDeniedError) as err:+ raise MaxToolFatalError(str(err), error_type="permission") from err+ except (*CH_TRANSIENT_ERRORS, ConcurrencyLimitExceeded) as err:+ error_type: MaxToolErrorType = (+ "rate_limited" if classify_query_error(err) == QueryErrorCategory.RATE_LIMITED else "api_5xx"+ )+ raise MaxToolTransientError(str(err), error_type=error_type) from err+ except ExposedHogQLError as err:+ raise _hogql_tool_error(err) from errexcept (APIException,- ExposedHogQLError,HogQLNotImplementedError,ExposedCHQueryError,- UserAccessControlError,) as err:elapsed = time.time() - start_time# Handle known query execution errors with user-friendly messages@@ -470,7 +508,21 @@ class AssistantQueryExecutor:err_message = ", ".join(map(str, err.detail))if debug_timing:logger.exception(f"{TIMING_LOG_PREFIX} Query execution failed after {elapsed:.3f}s: {err_message}")- raise MaxToolRetryableError(err_message)+ error_type = (+ "validation"+ if isinstance(err, APIException) or classify_query_error(err) == QueryErrorCategory.USER_ERROR+ else "internal"+ )+ if isinstance(err, ClickHouseQueryTimeOut):+ error_type = "timeout"+ elif isinstance(err, ClickHouseQueryMemoryLimitExceeded):+ error_type = "memory_limit"+ elif isinstance(err, APIException) and err.status_code >= 500:+ if classify_query_error(err) != QueryErrorCategory.QUERY_PERFORMANCE_ERROR:+ raise MaxToolFatalError(err_message, error_type="api_5xx") from err+ elif 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 errexcept Exception as err:elapsed = time.time() - start_time# Catch-all for unexpected errors during query execution. Surface the underlying error@@ -491,7 +543,7 @@ class AssistantQueryExecutor:# table, indistinguishable from "zero rows matched". Surface it as an error, mirroring the# `query_status.error` check the async-polling branch above already does.if isinstance(response_dict, dict) and (error := response_dict.get("error")):- raise MaxToolRetryableError(str(error))+ raise MaxToolRetryableError(str(error), error_type="internal")total_elapsed = time.time() - start_timeif debug_timing:diff --git a/ee/hogai/context/insight/test/test_context.py b/ee/hogai/context/insight/test/test_context.pyindex a37dc88ec894..b2e5d0bc71cf 100644--- a/ee/hogai/context/insight/test/test_context.py+++ b/ee/hogai/context/insight/test/test_context.py@@ -141,7 +141,9 @@ class TestInsightContext(BaseTest):with self.assertRaises(MaxToolRetryableError) as exc:await context.execute_and_format()- self.assertIn("Error executing query: Query failed", str(exc.exception))+ self.assertEqual(str(exc.exception), "Error executing query: Query failed")+ self.assertEqual(exc.exception.error_type, "internal")+ self.assertEqual(exc.exception.retry_hint, " You may retry with adjusted inputs.")@patch("ee.hogai.context.insight.context.execute_and_format_query")async def test_execute_and_format_returns_exception_when_flag_set(self, mock_execute):diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex e856064adcf0..2bcfbb6f5649 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -51,7 +51,7 @@ from ee.hogai.context.insight.query_executor import (get_example_prompt,is_supported_query,)-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolFatalError, MaxToolRetryableErrorfrom ee.hogai.utils.query import validate_assistant_query@@ -289,10 +289,10 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):query = AssistantTrendsQuery(series=[])- with self.assertRaises(MaxToolRetryableError) as context:+ with self.assertRaises(MaxToolFatalError) as context:await self.query_runner.arun_and_format_query(query)- self.assertIn("API error message", str(context.exception))+ self.assertEqual(str(context.exception), "API error message")@patch("ee.hogai.context.insight.query_executor.process_query_dict")async def test_run_and_format_query_handles_exposed_hogql_error(self, mock_process_query):@@ -364,7 +364,9 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):with self.assertRaises(MaxToolRetryableError) as context:await self.query_runner.arun_and_format_query(query)- self.assertIn("max execution time", str(context.exception))+ self.assertEqual(str(context.exception), "Query has hit the max execution time before completing.")+ self.assertEqual(context.exception.error_type, "internal")+ self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")@patch("ee.hogai.context.insight.query_executor.process_query_dict")@patch("ee.hogai.context.insight.query_executor.get_query_status")@@ -414,30 +416,45 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertIn("Query hasn't completed in time", str(context.exception))+ @parameterized.expand(+ [+ ("validation", "Unknown field: missing_column", None),+ ("timeout", "Query timed out", "error"),+ ("memory_limit", "Query memory limit exceeded", "clickhouse_memory_limit_exceeded"),+ ("warehouse_connection", "Warehouse connection failed", None),+ ]+ )@patch("ee.hogai.context.insight.query_executor.process_query_dict")@patch("ee.hogai.context.insight.query_executor.get_query_status")- async def test_async_query_polling_with_error(self, mock_get_query_status, mock_process_query):- """Test async query polling that returns an error"""- # Initial response with incomplete query+ async def test_async_query_polling_with_error(+ self,+ _name: str,+ error_message: str,+ error_code: str | None,+ mock_get_query_status: Mock,+ mock_process_query: Mock,+ ) -> None:mock_process_query.return_value = {"query_status": {"id": "test-query-id", "complete": False}}- # Mock polling to return errormock_get_query_status.return_value = Mock(model_dump=lambda mode: {"id": "test-query-id","complete": True,"error": True,- "error_message": "Query failed with error",+ "error_message": error_message,+ "error_code": error_code,})query = AssistantTrendsQuery(series=[])with patch("ee.hogai.context.insight.query_executor.asyncio.sleep"):- with self.assertRaises(Exception) as context:+ with self.assertRaises(MaxToolRetryableError) as context:await self.query_runner.arun_and_format_query(query)- self.assertIn("Query failed with error", str(context.exception))+ self.assertEqual(str(context.exception), error_message)+ self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")+ self.assertEqual(context.exception.error_type, "internal")@override_settings(TEST=False)@patch("ee.hogai.context.insight.query_executor.process_query_dict")diff --git a/ee/hogai/tool_errors.py b/ee/hogai/tool_errors.pyindex 51d4810e11a9..dc8a0deb6921 100644--- a/ee/hogai/tool_errors.py+++ b/ee/hogai/tool_errors.py@@ -1,5 +1,7 @@from typing import Literal+MaxToolErrorType = Literal["validation", "permission", "timeout", "memory_limit", "rate_limited", "api_5xx", "internal"]+class MaxToolError(Exception):"""@@ -17,12 +19,16 @@ class MaxToolError(Exception):- What can be done about it (for retryable errors)"""- def __init__(self, message: str):+ error_type: MaxToolErrorType = "internal"++ def __init__(self, message: str, *, error_type: MaxToolErrorType | None = None) -> None:"""Args:message: Detailed, actionable error message that helps the LLM understand what went wrong"""super().__init__(message)+ if error_type is not None:+ self.error_type = error_type@propertydef retry_strategy(self) -> Literal["never", "once", "adjusted"]:@@ -78,6 +84,8 @@ class MaxToolTransientError(MaxToolError):Transient error due to temporary service issues. Can be retried once without changes."""+ error_type = "api_5xx"+@propertydef retry_strategy(self) -> Literal["never", "once", "adjusted"]:return "once"@@ -88,6 +96,8 @@ class MaxToolRetryableError(MaxToolError):Solvable error that can be fixed with adjusted inputs. Can be retried with corrections."""+ error_type = "validation"+@propertydef retry_strategy(self) -> Literal["never", "once", "adjusted"]:return "adjusted"@@ -99,6 +109,8 @@ class MaxToolAccessDeniedError(MaxToolFatalError):This is a fatal error - the user needs to contact their admin to get access."""+ error_type = "permission"+def __init__(self,resource: str,diff --git a/ee/hogai/tools/execute_sql/test/test_tool.py b/ee/hogai/tools/execute_sql/test/test_tool.pyindex 18d3ab17009b..5aa2f16b643a 100644--- a/ee/hogai/tools/execute_sql/test/test_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_tool.py@@ -1,10 +1,12 @@from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event, flush_persons_and_events-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, Mock, patchfrom django.test import SimpleTestCasefrom asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfig+from parameterized import parameterized+from rest_framework.exceptions import PermissionDeniedfrom posthog.schema import (ArtifactContentType,@@ -17,6 +19,7 @@ from posthog.schema import (VisualizationArtifactContent,)+from posthog.exceptions import ClickHouseAtCapacityfrom posthog.models import Organization, Team, Userfrom products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation@@ -112,6 +115,24 @@ class TestExecuteSQLTool(ClickhouseTestMixin, NonAtomicBaseTest):self.assertIn("test_event", artifact_messages.messages[1].content)self.assertIn("another_event", artifact_messages.messages[1].content)+ @parameterized.expand(+ [+ (+ ClickHouseAtCapacity("Query service is busy"),+ "MaxToolTransientError: Query service is busy. You may retry this operation once without changes.",+ ),+ (PermissionDenied("Query access denied"), "MaxToolFatalError: Query access denied."),+ ]+ )+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")+ async def test_query_failures_preserve_recovery_advice(+ self, error: Exception, expected: str, mock_query: Mock+ ) -> None:+ mock_query.side_effect = error+ tool = await self._create_tool()++ self.assertEqual(await tool._arun_impl("SELECT 1", "Example query", "Example description"), (expected, None))+async def test_successful_sql_execution_can_set_chart_axis_labels(self):_create_event(team=self.team, distinct_id="user1", event="test_event")_create_event(team=self.team, distinct_id="user2", event="test_event")diff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.pyindex 0a933d401434..278c767c22ea 100644--- a/ee/hogai/tools/execute_sql/tool.py+++ b/ee/hogai/tools/execute_sql/tool.py@@ -30,7 +30,7 @@ from ee.hogai.context import AssistantContextManagerfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.tool import MaxTool, ToolMessagesArtifact-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolError, MaxToolRetryableErrorfrom ee.hogai.utils.prompt import format_prompt_stringfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import NodePath@@ -168,6 +168,8 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):result = await insight_context.execute_and_format()except MaxToolRetryableError as e:return format_prompt_string(EXECUTE_SQL_RECOVERABLE_ERROR_PROMPT, error=str(e)), None+ except MaxToolError as e:+ return f"{e.to_summary()}.{e.retry_hint}", Noneexcept Exception:return EXECUTE_SQL_UNRECOVERABLE_ERROR_PROMPT, Nonediff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.pyindex 899555fb9121..733cba31d86b 100644--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py@@ -55,4 +55,6 @@ class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):READ_TAXONOMY_TIMED_OUT_COUNTER.labels(query_kind=args.query.kind).inc()# MaxToolError appends its own retry hint and a period, so this ends bare. The hint for# a transient error offers one unchanged retry, so do not suggest narrowing the read.- raise MaxToolTransientError("Reading the taxonomy timed out. This can happen on large projects") from e+ raise MaxToolTransientError(+ "Reading the taxonomy timed out. This can happen on large projects", error_type="timeout"+ ) from ediff --git a/products/error_tracking/backend/max_tools.py b/products/error_tracking/backend/max_tools.pyindex 07804d87706f..a2f5d7158ee4 100644--- a/products/error_tracking/backend/max_tools.py+++ b/products/error_tracking/backend/max_tools.py@@ -27,7 +27,7 @@ from ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserExcfrom ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.llm import MaxChatOpenAIfrom ee.hogai.tool import MaxTool-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolErrorfrom .prompts import (ERROR_TRACKING_FILTER_INITIAL_PROMPT,@@ -319,7 +319,7 @@ class SearchErrorTrackingIssuesTool(MaxTool):utc_now = timezone.now().astimezone(UTC)executor = AssistantQueryExecutor(self._team, utc_now, user=self._user)query_results = await executor.aexecute_query(query)- except MaxToolRetryableError:+ except MaxToolError:raiseexcept Exception as e:capture_exception(e)diff --git a/products/error_tracking/backend/test/test_search_issues.py b/products/error_tracking/backend/test/test_search_issues.pyindex 0757a216d0d0..204a191d220c 100644--- a/products/error_tracking/backend/test/test_search_issues.py+++ b/products/error_tracking/backend/test/test_search_issues.py@@ -6,13 +6,14 @@ from posthog.test.base import (_create_person,flush_persons_and_events,)-from unittest.mock import patch+from unittest.mock import Mock, patchfrom django.utils.timezone import nowfrom dateutil.relativedelta import relativedeltafrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized+from rest_framework.exceptions import APIExceptionfrom posthog.schema import (DateRange,@@ -22,6 +23,9 @@ from posthog.schema import (MaxErrorTrackingSearchResponse,)+from posthog.exceptions import ClickHouseAtCapacity++from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.error_tracking.backend.max_tools import SearchErrorTrackingIssuesToolfrom products.error_tracking.backend.models import (ErrorTrackingIssue,@@ -30,6 +34,7 @@ from products.error_tracking.backend.models import ()from ee.hogai.context.context import AssistantContextManager+from ee.hogai.tool_errors import MaxToolAccessDeniedError, MaxToolError, MaxToolFatalError, MaxToolTransientErrorfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import NodePath@@ -304,6 +309,8 @@ class TestSearchErrorTrackingIssuesTool(ClickhouseTestMixin, NonAtomicBaseTest):class TestSearchErrorTrackingIssuesToolFormatting(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False+async def _create_tool(self):config: RunnableConfig = RunnableConfig()context_manager = AssistantContextManager(team=self.team, user=self.user, config=config)@@ -317,6 +324,41 @@ class TestSearchErrorTrackingIssuesToolFormatting(NonAtomicBaseTest):node_path=(NodePath(name="test_node", tool_call_id="test", message_id="test"),),)+ @parameterized.expand(+ [+ (ClickHouseAtCapacity("Query service is busy"), MaxToolTransientError, "rate_limited"),+ (UserAccessControlError("error_tracking", "viewer"), MaxToolAccessDeniedError, "permission"),+ (APIException("Query service failed"), MaxToolFatalError, "api_5xx"),+ ]+ )+ @patch("products.error_tracking.backend.max_tools.capture_exception")+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")+ async def test_query_errors_reach_the_tool_handler(+ self,+ error: Exception,+ expected_exception: type[MaxToolError],+ error_type: str,+ mock_process_query: Mock,+ mock_capture: Mock,+ ) -> None:+ mock_process_query.side_effect = error+ tool = await self._create_tool()++ with self.assertRaises(expected_exception) as context:+ await tool.ainvoke(+ {+ "query": ErrorTrackingQuery(+ dateRange=DateRange(date_from="-7d"),+ orderBy=ErrorTrackingOrderBy.LAST_SEEN,+ volumeResolution=1,+ )+ }+ )++ self.assertEqual(context.exception.error_type, error_type)+ self.assertIs(context.exception.__cause__, error)+ mock_capture.assert_not_called()+async def test_format_issue_with_all_fields(self):tool = await self._create_tool()issue = ErrorTrackingIssueSchema.model_validate(diff --git a/products/posthog_ai/backend/api/mcp_tools.py b/products/posthog_ai/backend/api/mcp_tools.pyindex ed739e7697de..1bba9aad565f 100644--- a/products/posthog_ai/backend/api/mcp_tools.py+++ b/products/posthog_ai/backend/api/mcp_tools.py@@ -28,7 +28,7 @@ from posthog.models.user import Userfrom posthog.renderers import SafeJSONRendererfrom ee.hogai.mcp_tool import MCPToolResult, mcp_tool_registry-from ee.hogai.tool_errors import MaxToolError+from ee.hogai.tool_errors import MaxToolError, MaxToolErrorTypefrom ee.hogai.tools.docs_search_shadow import fetch_inkeep_with_shadowfrom ee.hogai.tools.search import format_inkeep_docs_response@@ -43,6 +43,9 @@ class MCPToolRequest(pydantic.BaseModel):class MCPToolResponse(MCPToolResult):success: bool = pydantic.Field(description="Whether the tool completed successfully.")+ error_type: MaxToolErrorType | None = pydantic.Field(+ default=None, description="Failure category for MCP analytics."+ )class DocsSearchRequestSerializer(serializers.Serializer):@@ -173,6 +176,7 @@ class MCPToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):{"success": False,"content": f"Tool failed: {e.to_summary()}.{e.retry_hint}",+ "error_type": e.error_type,})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 9d03acf57a2f..531a4c4704ce 100644--- a/products/posthog_ai/backend/api/test_mcp_tools.py+++ b/products/posthog_ai/backend/api/test_mcp_tools.py@@ -1,17 +1,51 @@from datetime import UTC, datetimefrom posthog.test.base import APIBaseTest-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, Mock, patch++from django.db import OperationalErrorfrom parameterized import parameterized+from psycopg.errors import QueryCanceledfrom rest_framework import status+from rest_framework.exceptions import APIException, PermissionDenied, ValidationErrorfrom posthog.schema import CachedTeamTaxonomyQueryResponse+from posthog.hogql.errors import (+ ExposedHogQLError,+ NotImplementedError as HogQLNotImplementedError,+ QueryError,+ SyntaxError as HogQLSyntaxError,+ TableAccessDeniedError,+)++from posthog.errors import (+ CHQueryErrorCorruptedParquetMetadata,+ CHQueryErrorIllegalTypeOfArgument,+ CHQueryErrorS3FileChangedDuringRead,+)from posthog.event_usage import EventSource+from posthog.exceptions import (+ ClickHouseAtCapacity,+ ClickHouseClusterMemoryLimitExceeded,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQuerySizeExceeded,+ ClickHouseQueryTimeOut,+)from posthog.models import Organization, Team+from products.access_control.backend.facade.user_access_control import UserAccessControlError+from ee.hogai.mcp_tool import MCPToolResult+from ee.hogai.tool_errors import MaxToolRetryableError+++def _wrapped_hogql_error(cause: Exception, message: str) -> ExposedHogQLError:+ error = ExposedHogQLError(message)+ error.__cause__ = cause+ return errorclass TestMCPToolsAPI(APIBaseTest):@@ -59,6 +93,24 @@ class TestMCPToolsAPI(APIBaseTest):self.assertFalse(data["success"])self.assertIn("validation error", data["content"].lower())+ @parameterized.expand([("missing", "00000000-0000-4000-8000-000000000000"), ("malformed", "not-a-uuid")])+ def test_invoke_execute_sql_with_invalid_connection(self, _name: str, connection_id: str) -> None:+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_tools/execute_sql/",+ {"args": {"query": "SELECT 1", "connectionId": connection_id}},+ format="json",+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(+ response.json(),+ {+ "success": False,+ "content": "Tool failed: MaxToolRetryableError: Invalid connectionId: no direct-query-capable data source with this id in this team, or you don't have access to it.. You may retry with adjusted inputs.",+ "error_type": "internal",+ },+ )+@parameterized.expand([("text_only", False), ("structured_query", True)])@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)def test_invoke_execute_sql_success(self, _name: str, structured: bool, mock_execute: AsyncMock) -> None:@@ -113,10 +165,30 @@ class TestMCPToolsAPI(APIBaseTest):self.assertEqual(run_kwargs["user"], self.user)self.assertEqual(run_kwargs["analytics_props"], {"source": EventSource.MCP})+ @patch("ee.hogai.utils.helpers.TeamTaxonomyQueryRunner")+ def test_read_taxonomy_timeout_preserves_recovery_advice(self, mock_runner_cls: Mock) -> None:+ error = OperationalError("canceling statement due to statement timeout")+ error.__cause__ = QueryCanceled()+ mock_runner_cls.return_value.run.side_effect = error++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_tools/read_taxonomy/",+ {"args": {"query": {"kind": "events"}}},+ format="json",+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(+ response.json(),+ {+ "success": False,+ "content": "Tool failed: MaxToolTransientError: Reading the taxonomy timed out. This can happen on large projects. You may retry this operation once without changes.",+ "error_type": "timeout",+ },+ )+@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)def test_invoke_tool_error_returns_error_response(self, mock_execute):- from ee.hogai.tool_errors import MaxToolRetryableError-mock_execute.side_effect = MaxToolRetryableError("Query validation failed: syntax error")response = self.client.post(@@ -126,9 +198,190 @@ class TestMCPToolsAPI(APIBaseTest):)self.assertEqual(response.status_code, 200)- data = response.json()- self.assertFalse(data["success"])- self.assertIn("Tool failed", data["content"])+ self.assertEqual(+ response.json(),+ {+ "success": False,+ "content": "Tool failed: MaxToolRetryableError: Query validation failed: syntax error. You may retry with adjusted inputs.",+ "error_type": "validation",+ },+ )++ @parameterized.expand(+ [+ (+ ClickHouseAtCapacity("Query service is busy"),+ "rate_limited",+ "Tool failed: MaxToolTransientError: Query service is busy. You may retry this operation once without changes.",+ ),+ (+ ClickHouseClusterMemoryLimitExceeded("Cluster memory is full"),+ "rate_limited",+ "Tool failed: MaxToolTransientError: Cluster memory is full. You may retry this operation once without changes.",+ ),+ (+ PermissionDenied("Query access denied"),+ "permission",+ "Tool failed: MaxToolFatalError: Query access denied.",+ ),+ (+ UserAccessControlError("insight", "viewer"),+ "permission",+ "Tool failed: MaxToolAccessDeniedError: The user does not have viewer access to access insights. Suggest the user to contact their project admin to request access..",+ ),+ (+ ClickHouseQueryTimeOut("Query timed out"),+ "timeout",+ "Tool failed: MaxToolRetryableError: Query timed out. You may retry with adjusted inputs.",+ ),+ (+ ClickHouseQueryMemoryLimitExceeded("Query memory limit exceeded"),+ "memory_limit",+ "Tool failed: MaxToolRetryableError: Query memory limit exceeded. You may retry with adjusted inputs.",+ ),+ (+ ClickHouseEstimatedQueryExecutionTimeTooLong("Query estimate exceeded the time limit"),+ "validation",+ "Tool failed: MaxToolRetryableError: Query estimate exceeded the time limit. You may retry with adjusted inputs.",+ ),+ (+ ClickHouseQuerySizeExceeded("Query size exceeded"),+ "validation",+ "Tool failed: MaxToolRetryableError: Query size exceeded. You may retry with adjusted inputs.",+ ),+ (APIException("Query service failed"), "api_5xx", "Tool failed: MaxToolFatalError: Query service failed."),+ (+ ValidationError("Invalid query input"),+ "validation",+ "Tool failed: MaxToolRetryableError: Invalid query input. You may retry with adjusted inputs.",+ ),+ (+ HogQLSyntaxError("Unexpected SELECT"),+ "validation",+ "Tool failed: MaxToolRetryableError: Unexpected SELECT. You may retry with adjusted inputs.",+ ),+ (+ QueryError("Unknown field: missing_column"),+ "validation",+ "Tool failed: MaxToolRetryableError: Unknown field: missing_column. You may retry with adjusted inputs.",+ ),+ (+ HogQLNotImplementedError("QueryVisitor has no method visit_select_query"),+ "internal",+ "Tool failed: MaxToolRetryableError: QueryVisitor has no method visit_select_query. You may retry with adjusted inputs.",+ ),+ (+ CHQueryErrorIllegalTypeOfArgument("Illegal argument type", code=43),+ "validation",+ "Tool failed: MaxToolRetryableError: Illegal argument type. You may retry with adjusted inputs.",+ ),+ (+ CHQueryErrorCorruptedParquetMetadata("Warehouse file metadata is corrupt", code=1001),+ "internal",+ "Tool failed: MaxToolRetryableError: Warehouse file metadata is corrupt. You may retry with adjusted inputs.",+ ),+ (+ CHQueryErrorS3FileChangedDuringRead("Warehouse file changed while reading", code=499),+ "api_5xx",+ "Tool failed: MaxToolTransientError: Warehouse file changed while reading. You may retry this operation once without changes.",+ ),+ (+ _wrapped_hogql_error(TableAccessDeniedError("restricted_table"), "Warehouse table access denied"),+ "permission",+ "Tool failed: MaxToolFatalError: Warehouse table access denied.",+ ),+ (+ _wrapped_hogql_error(+ _wrapped_hogql_error(QueryError("Invalid query input"), "Query validation failed"),+ "Warehouse SQL is invalid",+ ),+ "validation",+ "Tool failed: MaxToolRetryableError: Warehouse SQL is invalid. You may retry with adjusted inputs.",+ ),+ (+ _wrapped_hogql_error(ConnectionError("connection refused"), "Warehouse connection failed"),+ "internal",+ "Tool failed: MaxToolRetryableError: Warehouse connection failed. You may retry with adjusted inputs.",+ ),+ (+ ExposedHogQLError("Managed warehouse is not available"),+ "internal",+ "Tool failed: MaxToolRetryableError: Managed warehouse is not available. You may retry with adjusted inputs.",+ ),+ (+ ValueError("Invalid query result encoding"),+ "internal",+ "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Invalid query result encoding. You may retry with adjusted inputs.",+ ),+ ]+ )+ @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+ ) -> None:+ mock_query.side_effect = error++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_tools/execute_sql/",+ {"args": {"query": "SELECT 1"}},+ format="json",+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json(), {"success": False, "content": content, "error_type": error_type})++ @parameterized.expand(+ [+ (+ "query_error",+ None,+ "Query failed",+ "Tool failed: MaxToolRetryableError: Query failed. You may retry with adjusted inputs.",+ ),+ (+ "missing_error_message",+ None,+ None,+ "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Query failed. You may retry with adjusted inputs.",+ ),+ (+ "polling_error",+ ConnectionError("Query status unavailable"),+ None,+ "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Query status unavailable. You may retry with adjusted inputs.",+ ),+ ]+ )+ @patch("ee.hogai.context.insight.query_executor.asyncio.sleep", new_callable=AsyncMock)+ @patch("ee.hogai.context.insight.query_executor.get_query_status")+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")+ def test_async_query_failures_preserve_recovery_advice(+ self,+ _name: str,+ polling_error: Exception | None,+ error_message: str | None,+ content: str,+ mock_query: Mock,+ mock_status: Mock,+ _mock_sleep: AsyncMock,+ ) -> None:+ mock_query.return_value = {"query_status": {"id": "test-query-id", "complete": False}}+ mock_status.side_effect = polling_error+ mock_status.return_value.model_dump.return_value = {+ "id": "test-query-id",+ "complete": True,+ "error": True,+ "error_message": error_message,+ }++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_tools/execute_sql/",+ {"args": {"query": "SELECT 1"}},+ format="json",+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json(), {"success": False, "content": content, "error_type": "internal"})@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):@@ -141,9 +394,13 @@ class TestMCPToolsAPI(APIBaseTest):)self.assertEqual(response.status_code, 200)- data = response.json()- self.assertFalse(data["success"])- self.assertIn("internal error", data["content"].lower())+ self.assertEqual(+ response.json(),+ {+ "success": False,+ "content": "The tool raised an internal error. Do not immediately retry the tool call.",+ },+ )class TestDocsSearchAction(APIBaseTest):diff --git a/products/posthog_ai/frontend/generated/api.schemas.ts b/products/posthog_ai/frontend/generated/api.schemas.tsindex 2ca44de9e758..f46e46fa298e 100644--- a/products/posthog_ai/frontend/generated/api.schemas.ts+++ b/products/posthog_ai/frontend/generated/api.schemas.ts@@ -640,6 +640,23 @@ export interface MCPToolRequestApi {*/export type MCPToolResponseApiStructuredContent = { [key: string]: JsonValueApi } | null+/**+ * Failure category for MCP analytics.+ */+export type MCPToolResponseApiErrorType =+ | (typeof MCPToolResponseApiErrorType)[keyof typeof MCPToolResponseApiErrorType]+ | null++export const MCPToolResponseApiErrorType = {+ Validation: 'validation',+ Permission: 'permission',+ Timeout: 'timeout',+ MemoryLimit: 'memory_limit',+ RateLimited: 'rate_limited',+ Api5xx: 'api_5xx',+ Internal: 'internal',+} as const+export interface MCPToolResponseApi {/** Formatted tool output for the model. */content: string@@ -647,6 +664,8 @@ export interface MCPToolResponseApi {structured_content?: MCPToolResponseApiStructuredContent/** Whether the tool completed successfully. */success: boolean+ /** Failure category for MCP analytics. */+ error_type?: MCPToolResponseApiErrorType}export interface DocsSearchRequestApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c8e0d91e8c05..d1f3dc7ede80 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -61943,6 +61943,22 @@ export namespace Schemas {*/export type MCPToolResponseStructuredContent = {[key: string]: JsonValue} | null;+ /**+ * Failure category for MCP analytics.+ */+ export type MCPToolResponseErrorType = typeof MCPToolResponseErrorType[keyof typeof MCPToolResponseErrorType] | null;+++ export const MCPToolResponseErrorType = {+ Validation: 'validation',+ Permission: 'permission',+ Timeout: 'timeout',+ MemoryLimit: 'memory_limit',+ RateLimited: 'rate_limited',+ Api5xx: 'api_5xx',+ Internal: 'internal',+ } as const;+export interface MCPToolResponse {/** Formatted tool output for the model. */content: string;@@ -61950,6 +61966,8 @@ export namespace Schemas {structured_content?: MCPToolResponseStructuredContent;/** Whether the tool completed successfully. */success: boolean;+ /** Failure category for MCP analytics. */+ error_type?: MCPToolResponseErrorType;}/**diff --git a/services/mcp/src/cli/tool-call-properties.ts b/services/mcp/src/cli/tool-call-properties.tsindex 344209bff0b0..5d9db402d2f0 100644--- a/services/mcp/src/cli/tool-call-properties.ts+++ b/services/mcp/src/cli/tool-call-properties.ts@@ -1,3 +1,4 @@+import { MCPToolResultError } from '@/lib/errors'import type { ExecInnerCallProperties } from '@/tools/exec'import { getToolCategory, getToolDescription } from '@/tools/toolDefinitions'@@ -41,14 +42,10 @@ function errorClass(properties: ExecInnerCallProperties): 'validation_error' | 'return 'error'}-/**- * The hosted server's `$mcp_error_type` vocabulary, derived from the little the- * CLI records (a validation flag and an HTTP status) — without it, CLI failures- * land in the analytics tools' untyped bucket and can't be broken down by reason.- */-function errorType(- properties: ExecInnerCallProperties-): 'validation' | 'permission' | 'rate_limited' | 'api_4xx' | 'api_5xx' | 'internal' {+function errorType(properties: ExecInnerCallProperties): MCPToolResultError['errorType'] | 'api_4xx' {+ if (properties.error instanceof MCPToolResultError) {+ return properties.error.errorType+ }if (properties.validation_error) {return 'validation'}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 87917dbddb31..71ca3d73ee18 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -17,6 +17,7 @@ import {PostHogApiError,PostHogValidationError,ToolInputValidationError,+ MCPToolResultError,findPostHogPermissionError,findRecoverableApiError,} from '@/lib/errors'@@ -500,6 +501,7 @@ export class ToolExecutor {this.servedToolDescription(tool.name))+ const errorMessage = extractErrorMessage(error)if (tool.name === EXECUTE_SQL_TOOL_NAME) {void trackExecuteSqlGeneration(tool.name,@@ -508,7 +510,7 @@ export class ToolExecutor {{durationMs: Date.now() - startMs,isError: true,- errorMessage: error instanceof Error ? error.message : String(error),+ errorMessage,},analyticsMeta)@@ -517,7 +519,7 @@ export class ToolExecutor {void trackToolSpan(tool.name, state, {durationMs: Date.now() - startMs,isError: true,- errorMessage: error instanceof Error ? error.message : String(error),+ errorMessage,input: validation.data,})@@ -743,6 +745,9 @@ export class ToolExecutor {if (!properties.validation_error) {toolCallDurationSeconds.observe({ tool: toolName, status }, properties.duration_ms / 1000)}+ const errorMessage = properties.validation_error+ ? properties.error_message+ : extractErrorMessage(properties.error)if (toolName === EXECUTE_SQL_TOOL_NAME && properties.input) {void trackExecuteSqlGeneration(toolName,@@ -751,7 +756,7 @@ export class ToolExecutor {{durationMs: properties.duration_ms,isError: !properties.success,- errorMessage: properties.error_message,+ errorMessage,},analyticsMeta)@@ -759,7 +764,7 @@ export class ToolExecutor {void trackToolSpan(toolName, state, {durationMs: properties.duration_ms,isError: !properties.success,- errorMessage: properties.error_message,+ errorMessage,input: properties.input,output: properties.output,})@@ -883,6 +888,7 @@ type ToolErrorType =| 'validation'| 'permission'| 'timeout'+ | 'memory_limit'| 'rate_limited'| 'api_5xx'| 'api_4xx'@@ -914,6 +920,9 @@ function classifyToolError(error: unknown, toolName: string): ToolErrorClassific}function resolveToolErrorClassification(error: unknown): ToolErrorClassification {+ if (error instanceof MCPToolResultError) {+ return { errorType: error.errorType }+ }if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {return { errorType: 'missing_context' }}@@ -1016,6 +1025,9 @@ function extractErrorMessage(error: unknown): string | undefined {}function resolveSafeErrorMessage(error: unknown): string | undefined {+ if (error instanceof MCPToolResultError) {+ return `Tool failed: ${error.errorType}`+ }// Static recovery walkthroughs generated by our own constructors.if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {return error.messagediff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 51dea5d79218..86c244c4d9e9 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -1,5 +1,6 @@import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'+import type { Schemas } from '@/api/generated'import { getPostHogClient } from '@/lib/posthog'import { getToolRecoveryHint } from '@/lib/tool-error-hints'import { sanitizeHeaderValue } from '@/lib/utils'@@ -23,6 +24,16 @@ export class MCPToolError extends Error {}}+export class MCPToolResultError extends Error {+ constructor(+ message: string,+ public readonly errorType: NonNullable<Schemas.MCPToolResponse['error_type']>+ ) {+ super(message)+ this.name = 'MCPToolResultError'+ }+}+/*** Thrown by `StateManager.getProjectId()` when no project can be resolved for* the current session — neither pinned via header, cached from a prior init,@@ -495,7 +506,8 @@ export function handleToolError(error: any, tool?: string, distinctId?: string,error instanceof MissingProjectContextError ||error instanceof MissingOrganizationContextError ||error instanceof ToolInputValidationError ||- error instanceof ExecCommandError+ error instanceof ExecCommandError ||+ (error instanceof MCPToolResultError && ['validation', 'permission'].includes(error.errorType))) {return {content: [diff --git a/services/mcp/src/tools/posthogAiTools/executeSql.ts b/services/mcp/src/tools/posthogAiTools/executeSql.tsindex d2512d334052..29a93622554a 100644--- a/services/mcp/src/tools/posthogAiTools/executeSql.ts+++ b/services/mcp/src/tools/posthogAiTools/executeSql.ts@@ -23,10 +23,6 @@ export const executeSqlHandler: ToolBase<typeof schema, ExecuteSqlResult>['handl...(params.sendRawQuery !== undefined && { sendRawQuery: params.sendRawQuery }),})- if (!result.success) {- throw new Error(result.content)- }-return result.structured_content? {...result.structured_content,diff --git a/services/mcp/src/tools/posthogAiTools/invokeTool.ts b/services/mcp/src/tools/posthogAiTools/invokeTool.tsindex b044691945a0..35e9b9e64691 100644--- a/services/mcp/src/tools/posthogAiTools/invokeTool.ts+++ b/services/mcp/src/tools/posthogAiTools/invokeTool.ts@@ -1,4 +1,5 @@import type { Schemas } from '@/api/generated'+import { MCPToolResultError } from '@/lib/errors'import type { Context } from '@/tools/types'export type McpToolResult = Schemas.MCPToolResponse@@ -25,9 +26,13 @@ export async function invokeMcpTool(): Promise<McpToolResult> {const projectId = await context.stateManager.getProjectId()- return await context.api.request<McpToolResult>({+ const result = await context.api.request<McpToolResult>({method: 'POST',path: `/api/environments/${projectId}/mcp_tools/${toolName}/`,body: { args },})+ if (!result.success) {+ throw result.error_type ? new MCPToolResultError(result.content, result.error_type) : new Error(result.content)+ }+ return result}diff --git a/services/mcp/src/tools/posthogAiTools/readDataSchema.ts b/services/mcp/src/tools/posthogAiTools/readDataSchema.tsindex 6e1ea660106e..407cee9ece11 100644--- a/services/mcp/src/tools/posthogAiTools/readDataSchema.ts+++ b/services/mcp/src/tools/posthogAiTools/readDataSchema.ts@@ -17,10 +17,6 @@ export const readDataSchemaHandler: ToolBase<typeof schema, string>['handler'] =query: params.query,})- if (!result.success) {- throw new Error(result.content)- }-return result.content}diff --git a/services/mcp/tests/cli/tool-call-properties.test.ts b/services/mcp/tests/cli/tool-call-properties.test.tsindex 7efd73780301..4d289c79e04a 100644--- a/services/mcp/tests/cli/tool-call-properties.test.ts+++ b/services/mcp/tests/cli/tool-call-properties.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { buildToolCallProperties } from '@/cli/tool-call-properties'+import { MCPToolResultError } from '@/lib/errors'import type { ExecInnerCallProperties } from '@/tools/exec'import { getToolCategory, getToolDescription } from '@/tools/toolDefinitions'@@ -16,6 +17,7 @@ describe('buildToolCallProperties', () => {success: false,output_format: 'text',error_message: 'API error: {"detail": "secret notebook content …"}',+ error: new Error('Private backend error details'),input: { markdown: 'private caller-supplied text' },}@@ -68,14 +70,29 @@ describe('buildToolCallProperties', () => {{ error_status: 502 },{ error_class: 'api_error', error_status: 502, $mcp_error_type: 'api_5xx', $mcp_error_status: 502 },],+ [+ 'backend validation failure',+ { error: new MCPToolResultError('Private SQL input', 'validation') },+ { error_class: 'error', $mcp_error_type: 'validation' },+ ],+ [+ 'backend query timeout',+ { error: new MCPToolResultError('Private query details', 'timeout') },+ { error_class: 'error', $mcp_error_type: 'timeout' },+ ],+ [+ 'backend query memory failure',+ { error: new MCPToolResultError('Private query details', 'memory_limit') },+ { error_class: 'error', $mcp_error_type: 'memory_limit' },+ ],])('classifies a %s without carrying the message', (_name, extra, expected) => {- expect(buildToolCallProperties('feature-flag-get-all', { ...base, ...extra })).toEqual({- tool_name: 'feature-flag-get-all',- $mcp_tool_name: 'feature-flag-get-all',+ expect(buildToolCallProperties('execute-sql', { ...base, ...extra })).toEqual({+ tool_name: 'execute-sql',+ $mcp_tool_name: 'execute-sql',$mcp_duration_ms: 42,$mcp_is_error: true,output_format: 'text',- ...catalogMetadata('feature-flag-get-all'),+ ...catalogMetadata('execute-sql'),...expected,})})diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 4d34b5233478..82aa5d170dff 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const { mockToolCallsInc, mockToolDurationObserve, mockToolDurationStartTimer, mockToolErrorsInc } = vi.hoisted(() => {const mockStop = vi.fn()@@ -37,7 +37,8 @@ vi.mock('@/resources', () => ({import { z } from 'zod'-import { trackToolCall } from '@/hono/analytics'+import { ApiClient } from '@/api/client'+import { trackExecuteSqlGeneration, trackToolCall, trackToolSpan } from '@/hono/analytics'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'@@ -49,6 +50,7 @@ import {ToolInputValidationError,wrapError,} from '@/lib/errors'+import { getPostHogClient } from '@/lib/posthog'import { URI_MAP } from '@/resources/ui-apps.generated'import { normalizeParamAliases } from '@/tools/cast-helpers'@@ -99,12 +101,80 @@ describe('ToolExecutor metrics', () => {mockToolDurationStartTimer.mockClear()mockToolErrorsInc.mockClear()mockTrackToolCall.mockClear()+ vi.mocked(trackExecuteSqlGeneration).mockClear()+ vi.mocked(trackToolSpan).mockClear()catalog = new ToolCatalog()await catalog.warmup()executor = new ToolExecutor(catalog, new InstructionsBuilder(''))})+ afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ it.each([+ { tool: 'execute-sql', useSingleExec: false, type: 'api_5xx' },+ { 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: 'memory_limit' },+ { tool: 'execute-sql', useSingleExec: true, type: 'memory_limit' },+ { tool: 'read-data-schema', useSingleExec: false, type: 'permission' },+ { tool: 'read-data-schema', useSingleExec: true, type: 'api_5xx' },+ ])(+ 'classifies backend result errors without capturing caller content: %j',+ async ({ tool, useSingleExec, type }) => {+ const captureException = vi.spyOn(getPostHogClient(), 'captureException').mockImplementation(() => {})+ const tools = catalog+ .getPreBuiltEntries()+ .map((entry) => toolFromPreBuilt(catalog.getToolByName(entry.name)!, entry))+ const state = makeToolExecutorState(tools, { useSingleExec })+ state.context.api = new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' })+ state.context.stateManager.getProjectId = vi.fn().mockResolvedValue(2)+ const content = 'Tool failed: private caller query. You may retry with adjusted inputs.'+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ success: false,+ content,+ error_type: type,+ })+ )+ )+ )+ const args = { query: tool === 'execute-sql' ? 'SELECT 1' : { kind: 'events' } }+ const result = await executor.handleToolCall(+ useSingleExec+ ? { name: 'exec', arguments: { command: `call ${tool} ${JSON.stringify(args)}` } }+ : { name: tool, arguments: args },+ state+ )++ expect(result).toMatchObject({+ isError: true,+ content: [{ type: 'text', text: `Error: [${tool}]: ${content}` }],+ })+ expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool, error_type: type })+ 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}` })+ expect(JSON.stringify(properties)).not.toContain('private caller query')+ const errorMetadata = {+ isError: true,+ errorMessage: `Tool failed: ${type}`,+ }+ expect(trackToolSpan).toHaveBeenCalledWith(tool, state, expect.objectContaining(errorMetadata))+ if (tool === 'execute-sql') {+ expect(trackExecuteSqlGeneration).toHaveBeenCalledOnce()+ expect(vi.mocked(trackExecuteSqlGeneration).mock.calls[0]?.[3]).toMatchObject(errorMetadata)+ }+ }+ )+describe('direct tool calls', () => {it('records success counter and duration timer', async () => {vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)diff --git a/services/mcp/tests/tools/invokeTool.test.ts b/services/mcp/tests/tools/invokeTool.test.tsindex 1a4373519d6f..7d14c622d570 100644--- a/services/mcp/tests/tools/invokeTool.test.ts+++ b/services/mcp/tests/tools/invokeTool.test.ts@@ -37,6 +37,12 @@ describe('invokeMcpTool', () => {expect(result).toEqual({ success: true, content: 'rows' })})+ it('keeps failures from older backends as errors during a rolling deploy', async () => {+ stubFetch(new Response(JSON.stringify({ success: false, content: 'Tool failed' })))++ await expect(invokeMcpTool(makeContext(), 'execute_sql', {})).rejects.toMatchObject({ message: 'Tool failed' })+ })+it('throws PostHogRateLimitError on a 429 so it is not bucketed as an internal error', async () => {// `Retry-After` is past the client's total retry budget, so this returns without waiting.stubFetch(