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.

fix(mcp): preserve memory error types in schema reads (#112036)

Vasco de Krijgerab628b5d0457
diff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.py
index 733cba31d86b..bf2d68d4ca8f 100644
--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py
+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py
@@ -3,11 +3,12 @@ from django.db import OperationalError
from prometheus_client import Counter
from posthog.api.statement_timeout import is_query_canceled
+from posthog.exceptions import ClickHouseClusterMemoryLimitExceeded, ClickHouseQueryMemoryLimitExceeded
from posthog.sync import database_sync_to_async
from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit
from ee.hogai.mcp_tool import MCPTool, mcp_tool_registry
-from ee.hogai.tool_errors import MaxToolRetryableError, MaxToolTransientError
+from ee.hogai.tool_errors import MaxToolFatalError, MaxToolRetryableError, MaxToolTransientError
from .core import ReadTaxonomyToolArgs, execute_taxonomy_query
@@ -43,6 +44,16 @@ class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):
return await _execute_query()
except ValueError as e:
raise MaxToolRetryableError(str(e))
+ except ClickHouseClusterMemoryLimitExceeded as e:
+ raise MaxToolTransientError(
+ ClickHouseClusterMemoryLimitExceeded.default_detail.rstrip("."), error_type="rate_limited"
+ ) from e
+ except ClickHouseQueryMemoryLimitExceeded as e:
+ raise MaxToolFatalError(
+ "Reading the schema ran out of memory. This tool does not support date filters. "
+ "Use execute-sql with a short, explicit date range for a targeted lookup",
+ error_type="memory_limit",
+ ) from e
except OperationalError as e:
# Only a statement cancelled by statement_timeout (SQLSTATE 57014) is worth a retry.
# Let connection loss, shutdown, deadlocks, and the like reach the generic handler so
diff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.py
index 531a4c4704ce..a21e5f90dd28 100644
--- a/products/posthog_ai/backend/api/test_mcp_tools.py
+++ b/products/posthog_ai/backend/api/test_mcp_tools.py
@@ -23,6 +23,7 @@ from posthog.hogql.errors import (
from posthog.errors import (
CHQueryErrorCorruptedParquetMetadata,
CHQueryErrorIllegalTypeOfArgument,
+ CHQueryErrorQueryWasCancelled,
CHQueryErrorS3FileChangedDuringRead,
)
from posthog.event_usage import EventSource
@@ -165,10 +166,54 @@ class TestMCPToolsAPI(APIBaseTest):
self.assertEqual(run_kwargs["user"], self.user)
self.assertEqual(run_kwargs["analytics_props"], {"source": EventSource.MCP})
+ @parameterized.expand(
+ [
+ (
+ "statement_timeout",
+ None,
+ "timeout",
+ "Tool failed: MaxToolTransientError: Reading the taxonomy timed out. This can happen on large projects. You may retry this operation once without changes.",
+ ),
+ (
+ "query_memory_limit",
+ ClickHouseQueryMemoryLimitExceeded("private backend detail"),
+ "memory_limit",
+ "Tool failed: MaxToolFatalError: Reading the schema ran out of memory. This tool does not support date filters. Use execute-sql with a short, explicit date range for a targeted lookup.",
+ ),
+ (
+ "cluster_memory_limit",
+ ClickHouseClusterMemoryLimitExceeded("private backend detail"),
+ "rate_limited",
+ "Tool failed: MaxToolTransientError: We're under heavy load right now and couldn't finish this query. Please try again in a few minutes. You may retry this operation once without changes.",
+ ),
+ (
+ "cancelled",
+ CHQueryErrorQueryWasCancelled("private backend detail", code=394),
+ None,
+ "The tool raised an internal error. Do not immediately retry the tool call.",
+ ),
+ (
+ "unknown",
+ RuntimeError("private backend detail"),
+ None,
+ "The tool raised an internal error. Do not immediately retry the tool call.",
+ ),
+ ]
+ )
+ @patch("products.posthog_ai.backend.api.mcp_tools.capture_exception")
@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()
+ def test_read_taxonomy_errors_preserve_recovery_advice(
+ self,
+ _name: str,
+ error: Exception | None,
+ error_type: str | None,
+ content: str,
+ mock_runner_cls: Mock,
+ mock_capture: Mock,
+ ) -> None:
+ if error is 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(
@@ -178,14 +223,13 @@ class TestMCPToolsAPI(APIBaseTest):
)
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",
- },
- )
+ expected = {"success": False, "content": content}
+ if error_type is not None:
+ expected["error_type"] = error_type
+ else:
+ self.assertEqual(mock_capture.call_args.args, (error,))
+ self.assertEqual(response.json(), expected)
+ mock_runner_cls.return_value.run.assert_called_once()
@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)
def test_invoke_tool_error_returns_error_response(self, mock_execute):