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): let insight tools save metrics queries (#118073)

posthog[bot]1061ece292fa
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 77d2b2e5bfd1..238eb0e24551 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -2226,7 +2226,14 @@
"additionalProperties": {},
"properties": {
"kind": {
- "$ref": "#/definitions/InsightNodeKind"
+ "anyOf": [
+ {
+ "$ref": "#/definitions/InsightNodeKind"
+ },
+ {
+ "$ref": "#/definitions/AssistantMetricsNodeKind"
+ }
+ ]
}
},
"required": ["kind"],
@@ -4092,6 +4099,10 @@
],
"type": "string"
},
+ "AssistantMetricsNodeKind": {
+ "enum": ["MetricsQuery", "MetricsHistogramQuery"],
+ "type": "string"
+ },
"AssistantMultipleBreakdownFilter": {
"anyOf": [
{
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index 12b8ade737da..cef43ef8b99d 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -2039,12 +2039,16 @@ export interface AssistantDataVisualizationNode {
tableSettings?: AssistantDataVisualizationTableSettings
}
-// `MCPInsightSerializer.validate_query` wraps these two shapes server-side before it saves the
-// insight, so a query straight out of a `query-*` tool can be passed through unchanged. Both carry
+// `MCPInsightSerializer.validate_query` wraps these shapes server-side before it saves the
+// insight, so a query straight out of a `query-*` tool can be passed through unchanged. Each carries
// an index signature because zod strips every key the schema does not declare, which would send
// `{ kind }` alone to the endpoint and save an empty insight.
+// A metrics query is saved bare and is not wrapped. It shares this shape because a separate union
+// member puts `insight-update` over the claude.ai tool schema size limit.
+export type AssistantMetricsNodeKind = NodeKind.MetricsQuery | NodeKind.MetricsHistogramQuery
+
export interface AssistantBareInsightQuery {
- kind: InsightNodeKind
+ kind: InsightNodeKind | AssistantMetricsNodeKind
[key: string]: unknown
}
diff --git a/posthog/schema.py b/posthog/schema.py
index 5c5c5c50f602..1afc131c48ca 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -47,6 +47,7 @@ from posthog.schema_enums import (
AssistantGenericPropertyFilterType as AssistantGenericPropertyFilterType,
AssistantLifecycleStatus as AssistantLifecycleStatus,
AssistantMessageType as AssistantMessageType,
+ AssistantMetricsNodeKind as AssistantMetricsNodeKind,
AssistantNavigateUrl as AssistantNavigateUrl,
AssistantNumericValuePropertyFilterOperator as AssistantNumericValuePropertyFilterOperator,
AssistantRetentionDisplayType as AssistantRetentionDisplayType,
@@ -3857,7 +3858,7 @@ class AssistantBIVisualizationNode(BaseModel):
class AssistantBareInsightQuery(BaseModel):
- kind: InsightNodeKind
+ kind: InsightNodeKind | AssistantMetricsNodeKind
class AssistantBreakdownFilter(BaseModel):
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index ed5a7e894d53..80e944db46d1 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -373,6 +373,11 @@ class AssistantMessageType(StrEnum):
AI_TASK_EXECUTION = "ai/task_execution"
+class AssistantMetricsNodeKind(StrEnum):
+ METRICS_QUERY = "MetricsQuery"
+ METRICS_HISTOGRAM_QUERY = "MetricsHistogramQuery"
+
+
class AssistantNavigateUrl(StrEnum):
ACTIONS = "actions"
ACTIVITY = "activity"
diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.py
index 25a6bd770124..82a60baa60aa 100644
--- a/products/metrics/backend/tests/test_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_query_runner.py
@@ -218,24 +218,33 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert expected_message in response.json()["detail"]
build_runner.assert_not_called()
- def test_insight_saves_with_metrics_query(self) -> None:
+ @parameterized.expand([("web", {}), ("mcp", {"X-PostHog-Client": "mcp"})])
+ def test_insight_saves_with_metrics_query(self, _name: str, client_headers: dict[str, str]) -> None:
+ query = {
+ "kind": "MetricsQuery",
+ "clauses": [{"name": "a", "metricName": "queue_depth", "aggregation": "sum"}],
+ "dateRange": {"date_from": "-24h"},
+ }
response = self.client.post(
f"/api/projects/{self.team.pk}/insights/",
- {
- "name": "queue depth",
- "saved": True,
- "query": {
- "kind": "MetricsQuery",
- "clauses": [{"name": "a", "metricName": "queue_depth", "aggregation": "sum"}],
- "dateRange": {"date_from": "-24h"},
- },
- },
+ {"name": "queue depth", "saved": True, "query": query},
format="json",
+ headers=client_headers,
)
assert response.status_code == 201, response.json()
assert response.json()["query"]["kind"] == "MetricsQuery"
+ update_response = self.client.patch(
+ f"/api/projects/{self.team.pk}/insights/{response.json()['id']}/",
+ {"query": query},
+ format="json",
+ headers=client_headers,
+ )
+
+ assert update_response.status_code == 200, update_response.json()
+ assert update_response.json()["query"] == response.json()["query"]
+
def test_validate_query_runner_access_granted(self) -> None:
query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index 3fcd18a9752c..4780b7d69466 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -67,6 +67,10 @@ tools:
so a query you just ran through one of the `query-*` tools can be passed straight through.
+ Save a `MetricsQuery` or `MetricsHistogramQuery` bare, as the top-level `query`. Do not put it in an
+ `InsightVizNode`.
+
+
Choose the TrendsQuery `trendsFilter.display` from the question the insight answers:
- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 81ec4da20af4..183d95cf682e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -7365,7 +7365,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 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.",
+ "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\nSave a `MetricsQuery` or `MetricsHistogramQuery` bare, as the top-level `query`. Do not put it in an `InsightVizNode`.\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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 19fb02556c67..76912baca4ed 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -7564,7 +7564,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 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.",
+ "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\nSave a `MetricsQuery` or `MetricsHistogramQuery` bare, as the top-level `query`. Do not put it in an `InsightVizNode`.\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",
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index 99c7723b4693..874ba75ed24c 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -270,9 +270,11 @@ const InsightNodeKind = z.enum([
'WebOverviewQuery',
])
+const AssistantMetricsNodeKind = z.enum(['MetricsQuery', 'MetricsHistogramQuery'])
+
const AssistantBareInsightQuery = z
.object({
- kind: InsightNodeKind,
+ kind: z.union([InsightNodeKind, AssistantMetricsNodeKind]),
})
.catchall(z.unknown())
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
index 08570ac9cc4b..16fcf5526826 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
@@ -622,18 +622,26 @@
"additionalProperties": {},
"properties": {
"kind": {
- "enum": [
- "TrendsQuery",
- "FunnelsQuery",
- "RetentionQuery",
- "PathsQuery",
- "PathsV2Query",
- "StickinessQuery",
- "LifecycleQuery",
- "WebStatsTableQuery",
- "WebOverviewQuery"
- ],
- "type": "string"
+ "anyOf": [
+ {
+ "enum": [
+ "TrendsQuery",
+ "FunnelsQuery",
+ "RetentionQuery",
+ "PathsQuery",
+ "PathsV2Query",
+ "StickinessQuery",
+ "LifecycleQuery",
+ "WebStatsTableQuery",
+ "WebOverviewQuery"
+ ],
+ "type": "string"
+ },
+ {
+ "enum": ["MetricsQuery", "MetricsHistogramQuery"],
+ "type": "string"
+ }
+ ]
}
},
"required": ["kind"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
index be5edcb6b1c1..b3b91c79c5ed 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
@@ -633,18 +633,26 @@
"additionalProperties": {},
"properties": {
"kind": {
- "enum": [
- "TrendsQuery",
- "FunnelsQuery",
- "RetentionQuery",
- "PathsQuery",
- "PathsV2Query",
- "StickinessQuery",
- "LifecycleQuery",
- "WebStatsTableQuery",
- "WebOverviewQuery"
- ],
- "type": "string"
+ "anyOf": [
+ {
+ "enum": [
+ "TrendsQuery",
+ "FunnelsQuery",
+ "RetentionQuery",
+ "PathsQuery",
+ "PathsV2Query",
+ "StickinessQuery",
+ "LifecycleQuery",
+ "WebStatsTableQuery",
+ "WebOverviewQuery"
+ ],
+ "type": "string"
+ },
+ {
+ "enum": ["MetricsQuery", "MetricsHistogramQuery"],
+ "type": "string"
+ }
+ ]
}
},
"required": ["kind"],
diff --git a/services/mcp/tests/unit/insight-query-shapes.test.ts b/services/mcp/tests/unit/insight-query-shapes.test.ts
index ece416b7935d..a64dee5d2fcf 100644
--- a/services/mcp/tests/unit/insight-query-shapes.test.ts
+++ b/services/mcp/tests/unit/insight-query-shapes.test.ts
@@ -49,6 +49,18 @@ const acceptedQueries = [
shape: 'bare WebStatsTableQuery',
query: { kind: 'WebStatsTableQuery', breakdownBy: 'Page', properties: [], dateRange: { date_from: '-7d' } },
},
+ {
+ shape: 'bare MetricsQuery',
+ query: {
+ kind: 'MetricsQuery',
+ clauses: [{ name: 'a', metricName: 'process.cpu.utilization', aggregation: 'avg' }],
+ dateRange: { date_from: '-24h' },
+ },
+ },
+ {
+ shape: 'bare MetricsHistogramQuery',
+ query: { kind: 'MetricsHistogramQuery', metricName: 'http.server.duration' },
+ },
]
const tools = [