: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): support saved events table insights (#116999)
Adam Bowker3f79019c4201
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex f3d64e67bad2..680d96510b26 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -603,7 +603,7 @@ The marker only controls schema inclusion. The endpoint stays reachable, and aut## HogQL query schemas (WIP)[`frontend/src/queries/schema/schema-assistant-queries.ts`](https://github.com/PostHog/posthog/blob/master/frontend/src/queries/schema/schema-assistant-queries.ts) defines structured query types-for the AI assistant (trends, funnels, retention, etc.).+for the AI assistant (trends, funnels, retention, events tables, etc.).These schemas describe the shape of analytical queries with rich JSDoc commentsthat help agents generate correct HogQL.diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 2812bff9496c..1b4b3dd8cdb2 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -2372,6 +2372,20 @@"required": ["type", "key", "value", "operator"],"type": "object"},+ "AssistantDataTableNode": {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "DataTableNode",+ "type": "string"+ },+ "source": {+ "$ref": "#/definitions/AssistantEventsQuery"+ }+ },+ "required": ["kind", "source"],+ "type": "object"+ },"AssistantDataVisualizationAxis": {"additionalProperties": false,"properties": {@@ -2395,7 +2409,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -2630,7 +2644,7 @@},"display": {"$ref": "#/definitions/AssistantDataVisualizationDisplayType",- "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Headline number with its change over time (KPI, scorecard) → `Metric`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Parts of one whole → `ActionsPie`, `ActionsDonut` or `ActionsProportionBar`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Ranking of categories by one value (top N, horizontal bars) → `ActionsBarValue`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`."+ "description": "Chart type (default `ActionsTable`): `BoldNumber` = one value; `Metric` = KPI; `ActionsLineGraph` / `ActionsAreaGraph` = time series; `ActionsPie` / `ActionsDonut` / `ActionsProportionBar` = shares; `ActionsBar` / `ActionsStackedBar` = categories; `ActionsBarValue` = horizontal rankings; `TwoDimensionalHeatmap` = 2D aggregates; `ScatterPlot` = two measures; `BoxPlot` = distribution summaries with `chartSettings.boxPlot`."},"kind": {"const": "DataVisualizationNode",@@ -2968,6 +2982,24 @@"enum": ["status", "message", "conversation", "notebook", "update", "approval", "sandbox"],"type": "string"},+ "AssistantEventsQuery": {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "EventsQuery",+ "type": "string"+ },+ "select": {+ "description": "Event columns as HogQL expressions.",+ "items": {+ "$ref": "#/definitions/HogQLExpression"+ },+ "type": "array"+ }+ },+ "required": ["kind", "select"],+ "type": "object"+ },"AssistantFlagPropertyFilter": {"additionalProperties": false,"properties": {@@ -30929,6 +30961,9 @@},"InsightQuery": {"anyOf": [+ {+ "$ref": "#/definitions/AssistantDataTableNode"+ },{"$ref": "#/definitions/AssistantInsightVizNode"},@@ -30940,6 +30975,9 @@},{"$ref": "#/definitions/AssistantBareHogQLQuery"+ },+ {+ "$ref": "#/definitions/AssistantEventsQuery"}]},diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.tsindex 10f0b6dc42b3..2659766a6c01 100644--- a/frontend/src/queries/schema/schema-assistant-queries.ts+++ b/frontend/src/queries/schema/schema-assistant-queries.ts@@ -19,6 +19,7 @@ import {ErrorTrackingOrderBy,ErrorTrackingQueryStatus,EventsNode,+ EventsQuery,FunnelExclusionSteps,FunnelsFilterLegacy,InsightNodeKind,@@ -1864,9 +1865,7 @@ export interface AssistantDataVisualizationAxisDisplaySettings {/** Which Y axis this numeric series should use. Use `right` for a secondary Y axis. */yAxisPosition?: 'left' | 'right'/**- * Override how this individual series is rendered, independent of the chart-level `display` type.- * Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`.- * `auto` follows the chart-level display type.+ * Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.*/displayType?: 'auto' | 'line' | 'bar' | 'area'/** Draw a linear trend line for this series. Only meaningful for line, bar, and area charts. */@@ -2018,19 +2017,12 @@ export interface AssistantDataVisualizationNode {/** HogQL query object that produces the rows to visualize. */source: Record<string, any>/**- * Visualization type. Defaults to `ActionsTable` when omitted.- *- * Guidance:- * - Single-value result (one numeric column, one row) → `BoldNumber`.- * - Headline number with its change over time (KPI, scorecard) → `Metric`.- * - Time series → `ActionsLineGraph` or `ActionsAreaGraph`.- * - Parts of one whole → `ActionsPie`, `ActionsDonut` or `ActionsProportionBar`.- * - Categorical comparison → `ActionsBar` or `ActionsStackedBar`.- * - Ranking of categories by one value (top N, horizontal bars) → `ActionsBarValue`.- * - Two-dimensional aggregation → `TwoDimensionalHeatmap`.- * - Relationship between two numeric measures, one point per row → `ScatterPlot`.- * - Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.- * - Otherwise → `ActionsTable`.+ * Chart type (default `ActionsTable`): `BoldNumber` = one value; `Metric` = KPI;+ * `ActionsLineGraph` / `ActionsAreaGraph` = time series;+ * `ActionsPie` / `ActionsDonut` / `ActionsProportionBar` = shares;+ * `ActionsBar` / `ActionsStackedBar` = categories; `ActionsBarValue` = horizontal rankings;+ * `TwoDimensionalHeatmap` = 2D aggregates; `ScatterPlot` = two measures;+ * `BoxPlot` = distribution summaries with `chartSettings.boxPlot`.*/display?: AssistantDataVisualizationDisplayType/** Chart configuration. Ignored when `display` is `ActionsTable` or `BoldNumber`. */@@ -2055,8 +2047,26 @@ export interface AssistantBareHogQLQuery {[key: string]: unknown}+export interface AssistantEventsQuery {+ kind: NodeKind.EventsQuery+ /** Event columns as HogQL expressions. */+ select: EventsQuery['select']+ // The backend validates EventsQuery fields. Preserve filters and options without expanding the tool schema.+ [key: string]: unknown+}++export interface AssistantDataTableNode {+ kind: NodeKind.DataTableNode+ source: AssistantEventsQuery+ [key: string]: unknown+}++// Zod fills in omitted kinds and takes the first matching union branch. Match events sources+// before the generic insight wrapper so inferred tables keep their kind and table settings.export type InsightQuery =+ | AssistantDataTableNode| AssistantInsightVizNode| AssistantDataVisualizationNode| AssistantBareInsightQuery| AssistantBareHogQLQuery+ | AssistantEventsQuerydiff --git a/posthog/schema.py b/posthog/schema.pyindex 02c8a656e811..6004794d690a 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -521,10 +521,7 @@ class AssistantDataVisualizationAxisDisplaySettings(BaseModel):displayType: DisplayType | None = Field(default=None,description=(- "Override how this individual series is rendered, independent of the"- " chart-level `display` type. Use this to mix series types — e.g. plot one"- " series as `bar` and overlay another as `line`. `auto` follows the"- " chart-level display type."+ "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type."),)label: str | None = Field(@@ -4076,6 +4073,11 @@ class AssistantElementPropertyFilter5(BaseModel):)+class AssistantEventsQuery(BaseModel):+ kind: Literal["EventsQuery"] = "EventsQuery"+ select: list[str] = Field(..., description="Event columns as HogQL expressions.")++class AssistantForm(BaseModel):model_config = ConfigDict(extra="forbid",@@ -10229,6 +10231,11 @@ class AssistantBehavioralPropertyFilter(BaseModel):value: InlineBehavioralType+class AssistantDataTableNode(BaseModel):+ kind: Literal["DataTableNode"] = "DataTableNode"+ source: AssistantEventsQuery++class AssistantDataVisualizationNode(BaseModel):model_config = ConfigDict(extra="forbid",@@ -10240,18 +10247,13 @@ class AssistantDataVisualizationNode(BaseModel):display: AssistantDataVisualizationDisplayType | None = Field(default=None,description=(- "Visualization type. Defaults to `ActionsTable` when"- " omitted.\n\nGuidance:\n- Single-value result (one numeric column, one"- " row) → `BoldNumber`.\n- Headline number with its change over time (KPI,"- " scorecard) → `Metric`.\n- Time series → `ActionsLineGraph` or"- " `ActionsAreaGraph`.\n- Parts of one whole → `ActionsPie`, `ActionsDonut`"- " or `ActionsProportionBar`.\n- Categorical comparison → `ActionsBar` or"- " `ActionsStackedBar`.\n- Ranking of categories by one value (top N,"- " horizontal bars) → `ActionsBarValue`.\n- Two-dimensional aggregation →"- " `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures,"- " one point per row → `ScatterPlot`.\n- Distribution summaries from"- " pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n-"- " Otherwise → `ActionsTable`."+ "Chart type (default `ActionsTable`): `BoldNumber` = one value; `Metric` ="+ " KPI; `ActionsLineGraph` / `ActionsAreaGraph` = time series; `ActionsPie`"+ " / `ActionsDonut` / `ActionsProportionBar` = shares; `ActionsBar` /"+ " `ActionsStackedBar` = categories; `ActionsBarValue` = horizontal"+ " rankings; `TwoDimensionalHeatmap` = 2D aggregates; `ScatterPlot` = two"+ " measures; `BoxPlot` = distribution summaries with"+ " `chartSettings.boxPlot`."),)kind: Literal["DataVisualizationNode"] = "DataVisualizationNode"@@ -19023,10 +19025,22 @@ class InsightActorsQueryBase(BaseModel):class InsightQuery(RootModel[- AssistantInsightVizNode | AssistantDataVisualizationNode | AssistantBareInsightQuery | AssistantBareHogQLQuery+ AssistantDataTableNode+ | AssistantInsightVizNode+ | AssistantDataVisualizationNode+ | AssistantBareInsightQuery+ | AssistantBareHogQLQuery+ | AssistantEventsQuery]):- root: AssistantInsightVizNode | AssistantDataVisualizationNode | AssistantBareInsightQuery | AssistantBareHogQLQuery+ root: (+ AssistantDataTableNode+ | AssistantInsightVizNode+ | AssistantDataVisualizationNode+ | AssistantBareInsightQuery+ | AssistantBareHogQLQuery+ | AssistantEventsQuery+ )class IsolationForestDetectorConfig(BaseModel):diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 01b6c1aed631..1136d56d980d 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -1520,7 +1520,7 @@ class MCPInsightSerializer(InsightSerializer):Accepts raw product analytics queries and normalizes them into the correct saved-insightwrapper before persisting: HogQLQuery → DataVisualizationNode, insight queries- (TrendsQuery, FunnelsQuery, PathsQuery) → InsightVizNode. MetricsQuery and+ (TrendsQuery, FunnelsQuery, PathsQuery) → InsightVizNode, EventsQuery → DataTableNode. MetricsQuery andMetricsHistogramQuery stay bare."""@@ -1540,10 +1540,26 @@ class MCPInsightSerializer(InsightSerializer):except PydanticValidationError:pass+ try:+ return schema.DataTableNode(source=schema.EventsQuery.model_validate(value)).model_dump(+ exclude_none=True, mode="json"+ )+ except PydanticValidationError:+ pass+# Already-wrapped node → use as-is- for wrapped_cls in (schema.DataVisualizationNode, schema.BIVisualizationNode, schema.InsightVizNode):+ for wrapped_cls in (+ schema.DataVisualizationNode,+ schema.BIVisualizationNode,+ schema.InsightVizNode,+ schema.DataTableNode,+ ):try:wrapped_node = wrapped_cls.model_validate(value)+ if isinstance(wrapped_node, schema.DataTableNode) and not isinstance(+ wrapped_node.source, schema.EventsQuery+ ):+ raise serializers.ValidationError("MCP data table insights must have an EventsQuery source.")normalized_query = wrapped_node.model_dump(exclude_none=True, mode="json")if isinstance(wrapped_node, (schema.DataVisualizationNode, schema.BIVisualizationNode)):box_plot = wrapped_node.chartSettings.boxPlot if wrapped_node.chartSettings else Nonediff --git a/products/product_analytics/backend/tests/api/test_insight_query.py b/products/product_analytics/backend/tests/api/test_insight_query.pyindex 90590489d15e..63c0d3863746 100644--- a/products/product_analytics/backend/tests/api/test_insight_query.py+++ b/products/product_analytics/backend/tests/api/test_insight_query.py@@ -6,7 +6,7 @@ from unittest.mock import patchfrom django.test import SimpleTestCasefrom parameterized import parameterized-from rest_framework import status+from rest_framework import serializers, statusfrom posthog import schemafrom posthog.api.test.dashboards import DashboardAPI@@ -22,6 +22,70 @@ from ee.api.test.base import LicensedTestMixinclass TestMCPInsightSerializer(SimpleTestCase):+ @parameterized.expand([("bare", False), ("wrapped", True)])+ def test_normalizes_events_queries(self, _name: str, wrapped: bool) -> None:+ source = {+ "kind": "EventsQuery",+ "select": ["event", "timestamp", "properties.example_property"],+ "where": ["timestamp >= now() - interval 7 day"],+ "properties": [{"type": "event", "key": "example_property", "operator": "exact", "value": ["example"]}],+ "fixedProperties": [+ {"type": "event", "key": "example_scope", "operator": "exact", "value": ["visible"]},+ {+ "type": "AND",+ "values": [+ {+ "type": "OR",+ "values": [+ {"type": "event", "key": "example_group", "operator": "exact", "value": ["visible"]}+ ],+ }+ ],+ },+ ],+ "events": ["example_event", "another_event"],+ "filterTestAccounts": False,+ "after": "2026-01-01T00:00:00Z",+ "before": "2026-01-08T00:00:00Z",+ "orderBy": ["timestamp DESC"],+ "limit": 25,+ "offset": 10,+ }+ query: dict[str, Any] = (+ {+ "kind": "DataTableNode",+ "source": source,+ "columns": source["select"],+ "pinnedColumns": ["event"],+ "hiddenColumns": ["timestamp"],+ "showAbsoluteTime": True,+ "showPropertyFilter": True,+ "showDateRange": True,+ "expandable": False,+ }+ if wrapped+ else source+ )++ normalized = MCPInsightSerializer().validate_query(query)++ assert normalized == (query if wrapped else {"kind": "DataTableNode", "source": source})++ @parameterized.expand(+ [+ ("other_table_source", {"kind": "DataTableNode", "source": {"kind": "HogQLQuery", "query": "select 1"}}),+ ("missing_select", {"kind": "DataTableNode", "source": {"kind": "EventsQuery"}}),+ ("invalid_select", {"kind": "EventsQuery", "select": "event"}),+ (+ "invalid_property_filter",+ {"kind": "EventsQuery", "select": ["event"], "properties": [{"type": "invalid", "key": "example"}]},+ ),+ ]+ )+ def test_rejects_unsupported_or_malformed_events_tables(self, _name: str, query: dict[str, Any]) -> None:+ with self.assertRaises(serializers.ValidationError):+ MCPInsightSerializer().validate_query(query)+def test_preserves_explicit_box_plot_grouping_nulls(self) -> None:normalized_query = MCPInsightSerializer().validate_query({@@ -448,9 +512,28 @@ class TestInsight(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest, QueryMatc"DataVisualizationNode","HogQLQuery",),+ (+ "raw_events_query",+ {"kind": "EventsQuery", "select": ["event", "timestamp"], "event": "example_event", "limit": 25},+ "DataTableNode",+ "EventsQuery",+ ),+ (+ "already_wrapped_events_table",+ {+ "kind": "DataTableNode",+ "source": {"kind": "EventsQuery", "select": ["event", "timestamp"], "event": "example_event"},+ "showAbsoluteTime": True,+ "pinnedColumns": ["event"],+ },+ "DataTableNode",+ "EventsQuery",+ ),])- def test_mcp_create_normalizes_query(self, _name, query, expected_kind, expected_source_kind) -> None:+ def test_mcp_create_and_update_normalize_query(+ self, _name: str, query: dict[str, Any], expected_kind: str, expected_source_kind: str | None+ ) -> None:response = self.client.post(f"/api/projects/{self.team.id}/insights/",data={"name": "Test insight", "favorited": False, "saved": True, "query": query},@@ -462,6 +545,18 @@ class TestInsight(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest, QueryMatcif expected_source_kind is not None:assert response.json()["query"]["source"]["kind"] == expected_source_kind+ insight_id = response.json()["id"]+ stored_query = Insight.objects.get(pk=insight_id).query+ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/insights/{insight_id}/",+ data={"query": query},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )++ assert update_response.status_code == status.HTTP_200_OK+ assert update_response.json()["query"] == response.json()["query"]+ assert Insight.objects.get(pk=insight_id).query == stored_query+def test_mcp_bi_member_alias_null_round_trip(self) -> None:aliases = [{diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yamlindex 332edbd5cbb0..8f08b6ebcf17 100644--- a/products/product_analytics/mcp/tools.yaml+++ b/products/product_analytics/mcp/tools.yaml@@ -51,7 +51,8 @@ tools:Put the insight definition in `query.source`, under the wrapper node that matches it. Use- `InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:+ `InsightVizNode` for a product analytics chart, `DataVisualizationNode` for a SQL visualization, and+ `DataTableNode` with an `EventsQuery` source for a table of individual events:```json@@ -61,10 +62,8 @@ tools:```-- A bare query is accepted too. `{ "kind": "TrendsQuery", ... }` and `{ "kind": "HogQLQuery", ... }` are each-- wrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.+ Bare `TrendsQuery`, `HogQLQuery`, and `EventsQuery` definitions are accepted too. They are wrapped for you,+ so a query you just ran through one of the `query-*` tools can be passed straight through.Choose the TrendsQuery `trendsFilter.display` from the question the insight answers:@@ -223,7 +222,9 @@ tools:description: >Update a saved insight by numeric `id` or `short_id`. Can update name, description, query, tags, favoritedstatus, and dashboards. Returns insight metadata only — after updating the query, call the insight-query- tool with the same identifier if you want to see the recomputed results.+ tool with the same identifier if you want to see the recomputed results. Query uses the same format as+ insight-create. Replacing query replaces the entire definition; include all filters and visualization+ settings you want to retain.agent_note:If this update added the insight to a dashboard through the `dashboards` field, consider offering the user arecurring delivery of that dashboard as a next step. `dashboards` is a full replacement, so only offer whendiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex d0ee584579cf..879266126c8a 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7288,7 +7288,7 @@}},"insight-create": {- "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.",+ "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics chart, `DataVisualizationNode` for a SQL visualization, and `DataTableNode` with an `EventsQuery` source for a table of individual events:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\nBare `TrendsQuery`, `HogQLQuery`, and `EventsQuery` definitions are accepted too. They are wrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.","category": "Product analytics","feature": "product_analytics","summary": "Create insight",@@ -7330,7 +7330,7 @@}},"insight-update": {- "description": "Update a saved insight by numeric `id` or `short_id`. Can update name, description, query, tags, favorited status, and dashboards. Returns insight metadata only — after updating the query, call the insight-query tool with the same identifier if you want to see the recomputed results.",+ "description": "Update a saved insight by numeric `id` or `short_id`. Can update name, description, query, tags, favorited status, and dashboards. Returns insight metadata only — after updating the query, call the insight-query tool with the same identifier if you want to see the recomputed results. Query uses the same format as insight-create. Replacing query replaces the entire definition; include all filters and visualization settings you want to retain.","category": "Product analytics","feature": "product_analytics","summary": "Update insight",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 97b694cdd65a..9d3c2d405b6c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7485,7 +7485,7 @@}},"insight-create": {- "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.",+ "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics chart, `DataVisualizationNode` for a SQL visualization, and `DataTableNode` with an `EventsQuery` source for a table of individual events:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\nBare `TrendsQuery`, `HogQLQuery`, and `EventsQuery` definitions are accepted too. They are wrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_code` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value, and `ActionsBarValue` draws the same bars horizontally.","category": "Product analytics","feature": "product_analytics","summary": "Create insight",@@ -7541,7 +7541,7 @@}},"insight-update": {- "description": "Update a saved insight by numeric `id` or `short_id`. Can update name, description, query, tags, favorited status, and dashboards. Returns insight metadata only — after updating the query, call the insight-query tool with the same identifier if you want to see the recomputed results.",+ "description": "Update a saved insight by numeric `id` or `short_id`. Can update name, description, query, tags, favorited status, and dashboards. Returns insight metadata only — after updating the query, call the insight-query tool with the same identifier if you want to see the recomputed results. Query uses the same format as insight-create. Replacing query replaces the entire definition; include all filters and visualization settings you want to retain.","category": "Product analytics","feature": "product_analytics","summary": "Update insight",diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.tsindex c95f83125550..981deb40852d 100644--- a/services/mcp/src/tools/generated/product_analytics.ts+++ b/services/mcp/src/tools/generated/product_analytics.ts@@ -14,6 +14,22 @@ import {} from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const HogQLExpression = z.string()++const AssistantEventsQuery = z+ .object({+ kind: z.literal('EventsQuery').default('EventsQuery'),+ select: z.array(HogQLExpression).describe('Event columns as HogQL expressions.'),+ })+ .catchall(z.unknown())++const AssistantDataTableNode = z+ .object({+ kind: z.literal('DataTableNode').default('DataTableNode'),+ source: AssistantEventsQuery,+ })+ .catchall(z.unknown())+const AssistantInsightVizNode = z.object({kind: z.literal('InsightVizNode').default('InsightVizNode'),source: z@@ -88,7 +104,7 @@ const AssistantDataVisualizationAxisDisplaySettings = z.object({displayType: z.enum(['auto', 'line', 'bar', 'area']).describe(- 'Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.'+ "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.").optional(),label: z@@ -220,7 +236,7 @@ const AssistantDataVisualizationNode = z.object({'Chart configuration. Ignored when `display` is `ActionsTable` or `BoldNumber`.').optional(),display: AssistantDataVisualizationDisplayType.describe(- 'Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Headline number with its change over time (KPI, scorecard) → `Metric`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Parts of one whole → `ActionsPie`, `ActionsDonut` or `ActionsProportionBar`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Ranking of categories by one value (top N, horizontal bars) → `ActionsBarValue`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`.'+ 'Chart type (default `ActionsTable`): `BoldNumber` = one value; `Metric` = KPI; `ActionsLineGraph` / `ActionsAreaGraph` = time series; `ActionsPie` / `ActionsDonut` / `ActionsProportionBar` = shares; `ActionsBar` / `ActionsStackedBar` = categories; `ActionsBarValue` = horizontal rankings; `TwoDimensionalHeatmap` = 2D aggregates; `ScatterPlot` = two measures; `BoxPlot` = distribution summaries with `chartSettings.boxPlot`.').optional(),kind: z.literal('DataVisualizationNode').default('DataVisualizationNode'),source: z.record(z.string(), z.unknown()).describe('HogQL query object that produces the rows to visualize.'),@@ -255,10 +271,12 @@ const AssistantBareHogQLQuery = z.catchall(z.unknown())const InsightQuery = z.union([+ AssistantDataTableNode,AssistantInsightVizNode,AssistantDataVisualizationNode,AssistantBareInsightQuery,AssistantBareHogQLQuery,+ AssistantEventsQuery,])const ElementsStatsRetrieveSchema = () => {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.jsonindex c1a636cf32c9..45358ee5bd3f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json@@ -36,6 +36,37 @@},"query": {"anyOf": [+ {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "DataTableNode",+ "default": "DataTableNode",+ "type": "string"+ },+ "source": {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "EventsQuery",+ "default": "EventsQuery",+ "type": "string"+ },+ "select": {+ "description": "Event columns as HogQL expressions.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["select"],+ "type": "object"+ }+ },+ "required": ["source"],+ "type": "object"+ },{"properties": {"kind": {@@ -283,7 +314,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -356,7 +387,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -412,7 +443,7 @@"type": "object"},"display": {- "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Headline number with its change over time (KPI, scorecard) → `Metric`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Parts of one whole → `ActionsPie`, `ActionsDonut` or `ActionsProportionBar`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Ranking of categories by one value (top N, horizontal bars) → `ActionsBarValue`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`.",+ "description": "Chart type (default `ActionsTable`): `BoldNumber` = one value; `Metric` = KPI; `ActionsLineGraph` / `ActionsAreaGraph` = time series; `ActionsPie` / `ActionsDonut` / `ActionsProportionBar` = shares; `ActionsBar` / `ActionsStackedBar` = categories; `ActionsBarValue` = horizontal rankings; `TwoDimensionalHeatmap` = 2D aggregates; `ScatterPlot` = two measures; `BoxPlot` = distribution summaries with `chartSettings.boxPlot`.","enum": ["ActionsTable","BoldNumber",@@ -466,7 +497,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -572,6 +603,25 @@},"required": ["query"],"type": "object"+ },+ {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "EventsQuery",+ "default": "EventsQuery",+ "type": "string"+ },+ "select": {+ "description": "Event columns as HogQL expressions.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["select"],+ "type": "object"}]},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.jsonindex 9e8a7f1291b0..4840ee722129 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json@@ -47,6 +47,37 @@},"query": {"anyOf": [+ {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "DataTableNode",+ "default": "DataTableNode",+ "type": "string"+ },+ "source": {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "EventsQuery",+ "default": "EventsQuery",+ "type": "string"+ },+ "select": {+ "description": "Event columns as HogQL expressions.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["select"],+ "type": "object"+ }+ },+ "required": ["source"],+ "type": "object"+ },{"properties": {"kind": {@@ -294,7 +325,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -367,7 +398,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -423,7 +454,7 @@"type": "object"},"display": {- "description": "Visualization type. Defaults to `ActionsTable` when omitted.\n\nGuidance:\n- Single-value result (one numeric column, one row) → `BoldNumber`.\n- Headline number with its change over time (KPI, scorecard) → `Metric`.\n- Time series → `ActionsLineGraph` or `ActionsAreaGraph`.\n- Parts of one whole → `ActionsPie`, `ActionsDonut` or `ActionsProportionBar`.\n- Categorical comparison → `ActionsBar` or `ActionsStackedBar`.\n- Ranking of categories by one value (top N, horizontal bars) → `ActionsBarValue`.\n- Two-dimensional aggregation → `TwoDimensionalHeatmap`.\n- Relationship between two numeric measures, one point per row → `ScatterPlot`.\n- Distribution summaries from pre-aggregated SQL rows → `BoxPlot` with `chartSettings.boxPlot`.\n- Otherwise → `ActionsTable`.",+ "description": "Chart type (default `ActionsTable`): `BoldNumber` = one value; `Metric` = KPI; `ActionsLineGraph` / `ActionsAreaGraph` = time series; `ActionsPie` / `ActionsDonut` / `ActionsProportionBar` = shares; `ActionsBar` / `ActionsStackedBar` = categories; `ActionsBarValue` = horizontal rankings; `TwoDimensionalHeatmap` = 2D aggregates; `ScatterPlot` = two measures; `BoxPlot` = distribution summaries with `chartSettings.boxPlot`.","enum": ["ActionsTable","BoldNumber",@@ -477,7 +508,7 @@"type": "string"},"displayType": {- "description": "Override how this individual series is rendered, independent of the chart-level `display` type. Use this to mix series types — e.g. plot one series as `bar` and overlay another as `line`. `auto` follows the chart-level display type.",+ "description": "Override this series to mix chart types, such as bars and lines. `auto` uses the chart's display type.","enum": ["auto", "line", "bar", "area"],"type": "string"},@@ -583,6 +614,25 @@},"required": ["query"],"type": "object"+ },+ {+ "additionalProperties": {},+ "properties": {+ "kind": {+ "const": "EventsQuery",+ "default": "EventsQuery",+ "type": "string"+ },+ "select": {+ "description": "Event columns as HogQL expressions.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["select"],+ "type": "object"}]},diff --git a/services/mcp/tests/unit/insights-events-table.test.ts b/services/mcp/tests/unit/insights-events-table.test.tsnew file mode 100644index 000000000000..b28dec3a5b82--- /dev/null+++ b/services/mcp/tests/unit/insights-events-table.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest'++import { GENERATED_TOOLS } from '@/tools/generated/product_analytics'++describe('saving events tables', () => {+ const source = {+ kind: 'EventsQuery',+ select: ['event', 'timestamp', 'properties.example_property'],+ where: ['timestamp >= now() - interval 7 day'],+ properties: [{ type: 'event', key: 'example_property', operator: 'exact', value: ['example'] }],+ fixedProperties: [+ { type: 'event', key: 'example_scope', operator: 'exact', value: ['visible'] },+ {+ type: 'AND',+ values: [+ {+ type: 'OR',+ values: [{ type: 'event', key: 'example_group', operator: 'exact', value: ['visible'] }],+ },+ ],+ },+ ],+ events: ['example_event', 'another_event'],+ filterTestAccounts: false,+ after: '2026-01-01T00:00:00Z',+ before: '2026-01-08T00:00:00Z',+ orderBy: ['timestamp DESC'],+ limit: 25,+ offset: 10,+ }+ const table = {+ kind: 'DataTableNode',+ source,+ columns: source.select,+ pinnedColumns: ['event'],+ hiddenColumns: ['timestamp'],+ showAbsoluteTime: true,+ showPropertyFilter: true,+ showDateRange: true,+ expandable: false,+ }++ describe.each(['insight-create', 'insight-update'])('%s', (toolName) => {+ const schema = GENERATED_TOOLS[toolName]!().schema+ const params = toolName === 'insight-create' ? { name: 'Example events' } : { id: 'AaVQ8Ijw' }++ it.each([+ ['bare', source, source],+ ['wrapped', table, table],+ ['inferred wrapper', { ...table, kind: undefined }, table],+ [+ 'minimal inferred wrapper',+ { source: { kind: 'EventsQuery', select: ['event'] } },+ { kind: 'DataTableNode', source: { kind: 'EventsQuery', select: ['event'] } },+ ],+ ])('preserves filters, columns and settings for a %s events query', (_name, query, expected) => {+ const parsed = schema.parse({ ...params, query }) as Record<string, unknown>++ expect(parsed.query).toEqual(expected)+ })++ it.each([+ ['other table source', { kind: 'DataTableNode', source: { kind: 'HogQLQuery', query: 'select 1' } }],+ ['missing select', { kind: 'DataTableNode', source: { kind: 'EventsQuery' } }],+ ['invalid select', { kind: 'EventsQuery', select: 'event' }],+ ])('rejects %s', (_name, query) => {+ expect(schema.safeParse({ ...params, query }).success).toBe(false)+ })+ })+})diff --git a/services/mcp/tests/unit/insights-query-handler.test.ts b/services/mcp/tests/unit/insights-query-handler.test.tsindex af560a6729ca..f451e930537c 100644--- a/services/mcp/tests/unit/insights-query-handler.test.ts+++ b/services/mcp/tests/unit/insights-query-handler.test.ts@@ -181,6 +181,27 @@ describe('queryHandler — link reflects overrides', () => {describe('queryHandler — result shape for UI rendering', () => {const formatted = 'c\n1'+ it.each(['optimized', 'json'] as const)(+ 'returns event rows without a formatter in %s output',+ async (output_format) => {+ const query = {+ kind: 'DataTableNode',+ source: { kind: 'EventsQuery', select: ['event', 'timestamp'], limit: 25 },+ }+ const queryData = { columns: ['event', 'timestamp'], results: [['example_event', '2026-01-01T00:00:00Z']] }+ const { context, insightsQuery } = createContext({+ getData: { id: 42, short_id: 'abc12345', query },+ queryData,+ })++ const result = (await queryHandler(context, { insightId: '42', output_format })) as QueryResult++ expect(insightsQuery).toHaveBeenCalledWith({ query })+ expect(result.results).toEqual(queryData)+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBeUndefined()+ }+ )+it('keeps structured results for a HogQL insight in optimized output', async () => {const { context } = createContext({queryData: { columns: ['c'], results: [[1]], formatted_results: formatted },