: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): retain codes for blocking query failures (#113079)
Vasco de Krijgerc5dd2ddc06c5
diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex 030f1d75e140..7722c08cc4a1 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -8,7 +8,7 @@ from posthog.sync import database_sync_to_asyncfrom products.product_analytics.backend.facade.models import Insight-from ee.hogai.context.insight.query_executor import execute_and_format_query+from ee.hogai.context.insight.query_executor import execute_and_format_query, get_clickhouse_error_codefrom ee.hogai.tool_errors import MaxToolError, MaxToolRetryableErrorfrom ee.hogai.utils.helpers import build_insight_urlfrom ee.hogai.utils.prompt import format_prompt_string@@ -111,7 +111,9 @@ class InsightContext:elif isinstance(e, MaxToolError):raiseelse:- raise MaxToolRetryableError(error_message, error_type="internal") from e+ raise MaxToolRetryableError(+ error_message, error_type="internal", error_code=get_clickhouse_error_code(e.__cause__)+ ) 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 0b3e14009899..9d442e00f79a 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -118,6 +118,13 @@ logger = structlog.get_logger(__name__)TIMING_LOG_PREFIX = "[QUERY_EXECUTOR]"+def get_clickhouse_error_code(error: BaseException | None) -> str | None:+ if not isinstance(error, InternalCHQueryError):+ return None+ code = look_up_clickhouse_error_code_meta(error).name.lower()+ return code if internal_ch_error_user_message(code) else None++def _hogql_tool_error(error: ExposedHogQLError) -> MaxToolError:cause: BaseException = errorseen: set[int] = set()@@ -505,7 +512,9 @@ class AssistantQueryExecutor: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+ raise MaxToolTransientError(+ str(err), error_type=error_type, error_code=get_clickhouse_error_code(err)+ ) from errexcept ExposedHogQLError as err:raise _hogql_tool_error(err) from errexcept (@@ -537,13 +546,10 @@ 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- 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,+ error_code=get_clickhouse_error_code(err),) from errexcept Exception as err:if isinstance(err, InternalCHQueryError):@@ -560,7 +566,7 @@ class AssistantQueryExecutor:max_len = 500if len(err_message) > max_len:err_message = err_message[:max_len] + "… (truncated)"- raise Exception(f"There was an unknown error running this query: {err_message}")+ raise Exception(f"There was an unknown error running this query: {err_message}") from err# A failed query can come back as a structurally-valid response that carries an `error`# field and empty `results` instead of raising — e.g. a direct-SQL adapter statementdiff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.pyindex 6e148cdbe7e4..ee0e455e11ea 100644--- a/products/posthog_ai/backend/api/test_mcp_tools.py+++ b/products/posthog_ai/backend/api/test_mcp_tools.py@@ -24,7 +24,9 @@ from posthog.errors import (CHQueryErrorCorruptedParquetMetadata,CHQueryErrorIllegalTypeOfArgument,CHQueryErrorQueryWasCancelled,+ CHQueryErrorS3Error,CHQueryErrorS3FileChangedDuringRead,+ InternalCHQueryError,)from posthog.event_usage import EventSourcefrom posthog.exceptions import (@@ -332,10 +334,28 @@ class TestMCPToolsAPI(APIBaseTest):"internal","Tool failed: MaxToolRetryableError: Warehouse file metadata is corrupt. You may retry with adjusted inputs.",),- (+ param(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.",+ error_code="s3_error",+ ),+ param(+ CHQueryErrorS3Error("Storage read failed", code=499),+ "api_5xx",+ "Tool failed: MaxToolTransientError: Code: 499.\nStorage read failed. You may retry this operation once without changes.",+ error_code="s3_error",+ ),+ param(+ InternalCHQueryError("Too many parts", code=252, code_name="caller-supplied-name"),+ "internal",+ "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Code: 252.\nToo many parts. You may retry with adjusted inputs.",+ error_code="too_many_parts",+ ),+ (+ InternalCHQueryError("Unknown failure", code=99999, code_name="s3_error"),+ "internal",+ "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Code: 99999.\nUnknown failure. You may retry with adjusted inputs.",),(_wrapped_hogql_error(TableAccessDeniedError("restricted_table"), "Warehouse table access denied"),