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): restore connectionId on execute-sql tool (#60454)

Jovan Sakovic8c7360874f5a
diff --git a/ee/hogai/tools/execute_sql/mcp_tool.py b/ee/hogai/tools/execute_sql/mcp_tool.py
index 4cbfe2fe1cd5..e509ec8ddecf 100644
--- a/ee/hogai/tools/execute_sql/mcp_tool.py
+++ b/ee/hogai/tools/execute_sql/mcp_tool.py
@@ -1,5 +1,7 @@
from pydantic import BaseModel, Field
+from posthog.schema import AssistantHogQLQuery, HogQLQuery
+
from ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserException
from ee.hogai.chat_agent.sql.mixins import HogQLOutputParserMixin
from ee.hogai.context.insight.context import InsightContext
@@ -13,6 +15,14 @@ class ExecuteSQLMCPToolArgs(BaseModel):
default=True,
description="Whether to truncate large blob/JSON values in results. Set to false for full untruncated results.",
)
+ connectionId: str | None = Field(
+ default=None,
+ description=(
+ "Optional id of an external data source (e.g. a Postgres or DuckDB direct-query connection). "
+ "When set, runs the query against that source instead of the ClickHouse catalog. "
+ "Use external-data-sources-list to discover available connection ids."
+ ),
+ )
@mcp_tool_registry.register(scopes=["query:read"])
@@ -27,14 +37,25 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):
args_schema = ExecuteSQLMCPToolArgs
async def execute(self, args: ExecuteSQLMCPToolArgs) -> str:
- try:
- validated_query = await self._validate_hogql_query(args.query)
- except PydanticOutputParserException as e:
- raise MaxToolRetryableError(f"Query validation failed: {e.validation_message}")
+ query: AssistantHogQLQuery | HogQLQuery
+ if args.connectionId:
+ # Queries targeting an external connection reference tables that aren't in the
+ # default ClickHouse database, so the local parse/print HogQL validation step
+ # would reject them. Defer validation to the runner, which resolves the schema
+ # for the selected connection.
+ cleaned_query = args.query.rstrip(";").strip() if args.query else ""
+ if not cleaned_query:
+ raise MaxToolRetryableError("Query validation failed: Query is empty")
+ query = HogQLQuery(query=cleaned_query, connectionId=args.connectionId)
+ else:
+ try:
+ query = await self._validate_hogql_query(args.query)
+ except PydanticOutputParserException as e:
+ raise MaxToolRetryableError(f"Query validation failed: {e.validation_message}")
insight_context = InsightContext(
team=self._team,
- query=validated_query,
+ query=query,
name="",
description="",
user=self._user,
diff --git a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py
index 686649b3fb66..a223db00340f 100644
--- a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py
+++ b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py
@@ -1,8 +1,10 @@
from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event
-from unittest.mock import Mock, patch
+from unittest.mock import AsyncMock, Mock, patch
from asgiref.sync import sync_to_async
+from posthog.schema import HogQLQuery
+
from products.product_analytics.backend.models.insight import Insight
from ee.hogai.tool_errors import MaxToolRetryableError
@@ -60,3 +62,36 @@ class TestExecuteSQLMCPTool(ClickhouseTestMixin, NonAtomicBaseTest):
)
self.assertIn("Revenue Trends", content)
+
+ async def test_connection_id_skips_local_validation_and_wraps_in_hogql_query(self):
+ # When a connectionId is set the query may reference tables that only exist on the
+ # external connection, so we must bypass the local HogQL parse/print step and pass
+ # a real HogQLQuery (which carries connectionId) down to the runner.
+ captured: dict = {}
+
+ async def fake_execute_and_format(self, *args, **kwargs):
+ captured["query"] = self.query
+ return "ok"
+
+ with (
+ patch(
+ "ee.hogai.tools.execute_sql.mcp_tool.InsightContext.execute_and_format",
+ new=fake_execute_and_format,
+ ),
+ patch.object(self.tool, "_validate_hogql_query", new=AsyncMock()) as validate_mock,
+ ):
+ result = await self.tool.execute(
+ ExecuteSQLMCPToolArgs(query="SELECT * FROM ducklake_orders", connectionId="conn_abc"),
+ )
+
+ self.assertEqual(result, "ok")
+ validate_mock.assert_not_awaited()
+ self.assertIsInstance(captured["query"], HogQLQuery)
+ self.assertEqual(captured["query"].connectionId, "conn_abc")
+ self.assertEqual(captured["query"].query, "SELECT * FROM ducklake_orders")
+
+ async def test_connection_id_with_empty_query_raises(self):
+ with self.assertRaises(MaxToolRetryableError):
+ await self.tool.execute(
+ ExecuteSQLMCPToolArgs(query=" ", connectionId="conn_abc"),
+ )
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 02e5cdcc099b..e20d3ccd14f2 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -133,6 +133,10 @@
"default": true,
"description": "Whether to truncate large blob/JSON values in results. Defaults to true. Set to false when you need full untruncated results (e.g., for dumping to a file).",
"type": "boolean"
+ },
+ "connectionId": {
+ "description": "Optional id of an external data source (e.g. a Postgres or DuckDB direct-query connection). When set, runs the query against that source instead of the ClickHouse catalog. Use external-data-sources-list to discover available connection ids.",
+ "type": "string"
}
},
"required": ["query"]
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 9571b145aa3e..0c5fac992bdc 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -607,6 +607,12 @@ export const ExecuteSQLSchema = z.object({
.describe(
'Whether to truncate large blob/JSON values in results. Defaults to true. Set to false when you need full untruncated results (e.g., for dumping to a file).'
),
+ connectionId: z
+ .string()
+ .optional()
+ .describe(
+ 'Optional id of an external data source (e.g. a Postgres or DuckDB direct-query connection). When set, runs the query against that source instead of the ClickHouse catalog. Use external-data-sources-list to discover available connection ids.'
+ ),
})
export const ReadDataWarehouseSchemaSchema = z
diff --git a/services/mcp/src/tools/posthogAiTools/executeSql.ts b/services/mcp/src/tools/posthogAiTools/executeSql.ts
index 1ce37811e1ab..580b86bee234 100644
--- a/services/mcp/src/tools/posthogAiTools/executeSql.ts
+++ b/services/mcp/src/tools/posthogAiTools/executeSql.ts
@@ -16,6 +16,7 @@ export const executeSqlHandler: ToolBase<typeof schema, string>['handler'] = asy
const result = await invokeMcpTool(context, 'execute_sql', {
query: params.query,
truncate: params.truncate ?? true,
+ ...(params.connectionId !== undefined && { connectionId: params.connectionId }),
})
if (!result.success) {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/execute-sql.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/execute-sql.json
index 64216a7e0f47..f6eb87bad3cf 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/execute-sql.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/execute-sql.json
@@ -1,6 +1,10 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "connectionId": {
+ "description": "Optional id of an external data source (e.g. a Postgres or DuckDB direct-query connection). When set, runs the query against that source instead of the ClickHouse catalog. Use external-data-sources-list to discover available connection ids.",
+ "type": "string"
+ },
"query": {
"description": "The final SQL query to be executed.",
"minLength": 1,