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): accept the bare insight queries the API already wraps (#102193)

Thomas Obermüllerca32a396ab2e
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 9f00a8a2cb9e..2be43c6366e0 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -2157,6 +2157,31 @@
"enum": ["exact", "is_not"],
"type": "string"
},
+ "AssistantBareHogQLQuery": {
+ "additionalProperties": {},
+ "properties": {
+ "kind": {
+ "const": "HogQLQuery",
+ "type": "string"
+ },
+ "query": {
+ "description": "The HogQL query to run.",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "query"],
+ "type": "object"
+ },
+ "AssistantBareInsightQuery": {
+ "additionalProperties": {},
+ "properties": {
+ "kind": {
+ "$ref": "#/definitions/InsightNodeKind"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
"AssistantBaseMultipleBreakdownFilter": {
"additionalProperties": false,
"properties": {
@@ -29414,6 +29439,12 @@
},
{
"$ref": "#/definitions/AssistantDataVisualizationNode"
+ },
+ {
+ "$ref": "#/definitions/AssistantBareInsightQuery"
+ },
+ {
+ "$ref": "#/definitions/AssistantBareHogQLQuery"
}
]
},
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index 8f75393d4ed8..b00974e51c05 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -21,6 +21,7 @@ import {
EventsNode,
FunnelExclusionSteps,
FunnelsFilterLegacy,
+ InsightNodeKind,
LifecycleFilterLegacy,
MultipleBreakdownType,
Node,
@@ -1990,4 +1991,24 @@ export interface AssistantDataVisualizationNode {
tableSettings?: AssistantDataVisualizationTableSettings
}
-export type InsightQuery = AssistantInsightVizNode | AssistantDataVisualizationNode
+// `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
+// 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.
+export interface AssistantBareInsightQuery {
+ kind: InsightNodeKind
+ [key: string]: unknown
+}
+
+export interface AssistantBareHogQLQuery {
+ kind: NodeKind.HogQLQuery
+ /** The HogQL query to run. */
+ query: string
+ [key: string]: unknown
+}
+
+export type InsightQuery =
+ | AssistantInsightVizNode
+ | AssistantDataVisualizationNode
+ | AssistantBareInsightQuery
+ | AssistantBareHogQLQuery
diff --git a/posthog/schema.py b/posthog/schema.py
index d219929af95d..2944f34ca1b6 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -462,6 +462,11 @@ class ApprovalResumePayload(BaseModel):
proposal_id: str
+class AssistantBareHogQLQuery(BaseModel):
+ kind: Literal["HogQLQuery"] = "HogQLQuery"
+ query: str = Field(..., description="The HogQL query to run.")
+
+
class AssistantBaseMultipleBreakdownFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -3411,6 +3416,10 @@ class AssistantArrayPropertyFilter(BaseModel):
)
+class AssistantBareInsightQuery(BaseModel):
+ kind: InsightNodeKind
+
+
class AssistantBreakdownFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -17880,8 +17889,12 @@ class InsightActorsQueryBase(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class InsightQuery(RootModel[AssistantInsightVizNode | AssistantDataVisualizationNode]):
- root: AssistantInsightVizNode | AssistantDataVisualizationNode
+class InsightQuery(
+ RootModel[
+ AssistantInsightVizNode | AssistantDataVisualizationNode | AssistantBareInsightQuery | AssistantBareHogQLQuery
+ ]
+):
+ root: AssistantInsightVizNode | AssistantDataVisualizationNode | AssistantBareInsightQuery | AssistantBareHogQLQuery
class IsolationForestDetectorConfig(BaseModel):
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index de77a99d085d..a6de872ba529 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -90,15 +90,22 @@ tools:
you want to see the computed results.
- Put the insight definition in `query.source`:
+ 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:
```json
- { "name": "Example", "query": { "kind": "InsightVizNode", "source": { "kind": "HogQLQuery", "query": "SELECT
- 1" } } }
+ { "name": "Example", "query": { "kind": "DataVisualizationNode", "source": { "kind": "HogQLQuery", "query":
+ "SELECT 1" } } }
```
+
+
+ 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.
exclude_params:
- query
include_params:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ab702feefd90..0a840b201180 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6173,7 +6173,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`:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"InsightVizNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```",
+ "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.",
"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 0c5b1b38089f..5cb81d5dcbc4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6370,7 +6370,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`:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"InsightVizNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```",
+ "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.",
"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 e59bdead252e..c76ecc2e1b03 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -195,7 +195,37 @@ const AssistantDataVisualizationNode = z.object({
).optional(),
})
-const InsightQuery = z.union([AssistantInsightVizNode, AssistantDataVisualizationNode])
+const InsightNodeKind = z.enum([
+ 'TrendsQuery',
+ 'FunnelsQuery',
+ 'RetentionQuery',
+ 'PathsQuery',
+ 'PathsV2Query',
+ 'StickinessQuery',
+ 'LifecycleQuery',
+ 'WebStatsTableQuery',
+ 'WebOverviewQuery',
+])
+
+const AssistantBareInsightQuery = z
+ .object({
+ kind: InsightNodeKind,
+ })
+ .catchall(z.unknown())
+
+const AssistantBareHogQLQuery = z
+ .object({
+ kind: z.literal('HogQLQuery').default('HogQLQuery'),
+ query: z.string().describe('The HogQL query to run.'),
+ })
+ .catchall(z.unknown())
+
+const InsightQuery = z.union([
+ AssistantInsightVizNode,
+ AssistantDataVisualizationNode,
+ AssistantBareInsightQuery,
+ AssistantBareHogQLQuery,
+])
const ElementsStatsRetrieveSchema = () => {
const ElementsStatsRetrieveQueryParams = orvalSchemas.ElementsStatsRetrieveQueryParams()
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 c7c768fe2a9e..d3497dc3714f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
@@ -493,6 +493,43 @@
},
"required": ["source"],
"type": "object"
+ },
+ {
+ "additionalProperties": {},
+ "properties": {
+ "kind": {
+ "enum": [
+ "TrendsQuery",
+ "FunnelsQuery",
+ "RetentionQuery",
+ "PathsQuery",
+ "PathsV2Query",
+ "StickinessQuery",
+ "LifecycleQuery",
+ "WebStatsTableQuery",
+ "WebOverviewQuery"
+ ],
+ "type": "string"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": {},
+ "properties": {
+ "kind": {
+ "const": "HogQLQuery",
+ "default": "HogQLQuery",
+ "type": "string"
+ },
+ "query": {
+ "description": "The HogQL query to run.",
+ "type": "string"
+ }
+ },
+ "required": ["query"],
+ "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.json
index 3688797e8a1a..3f8127c96408 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
@@ -504,6 +504,43 @@
},
"required": ["source"],
"type": "object"
+ },
+ {
+ "additionalProperties": {},
+ "properties": {
+ "kind": {
+ "enum": [
+ "TrendsQuery",
+ "FunnelsQuery",
+ "RetentionQuery",
+ "PathsQuery",
+ "PathsV2Query",
+ "StickinessQuery",
+ "LifecycleQuery",
+ "WebStatsTableQuery",
+ "WebOverviewQuery"
+ ],
+ "type": "string"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": {},
+ "properties": {
+ "kind": {
+ "const": "HogQLQuery",
+ "default": "HogQLQuery",
+ "type": "string"
+ },
+ "query": {
+ "description": "The HogQL query to run.",
+ "type": "string"
+ }
+ },
+ "required": ["query"],
+ "type": "object"
}
]
},
diff --git a/services/mcp/tests/unit/insight-query-shapes.test.ts b/services/mcp/tests/unit/insight-query-shapes.test.ts
new file mode 100644
index 000000000000..0f7fe8ad570b
--- /dev/null
+++ b/services/mcp/tests/unit/insight-query-shapes.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+
+import { GENERATED_TOOLS } from '@/tools/generated/product_analytics'
+
+const BARE_TRENDS_QUERY = {
+ kind: 'TrendsQuery',
+ series: [{ kind: 'EventsNode', event: '$pageview', name: '$pageview' }],
+ dateRange: { date_from: '-7d' },
+ interval: 'day',
+}
+
+// Every shape `MCPInsightSerializer.validate_query` normalizes and saves. The bare ones are
+// wrapped server-side, so the tool boundary has to pass them through rather than reject them.
+const acceptedQueries = [
+ {
+ shape: 'wrapped InsightVizNode',
+ query: { kind: 'InsightVizNode', source: BARE_TRENDS_QUERY },
+ },
+ {
+ shape: 'wrapped DataVisualizationNode',
+ query: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'select 1' } },
+ },
+ { shape: 'bare TrendsQuery', query: BARE_TRENDS_QUERY },
+ { shape: 'bare HogQLQuery', query: { kind: 'HogQLQuery', query: 'select 1' } },
+ {
+ shape: 'bare WebStatsTableQuery',
+ query: { kind: 'WebStatsTableQuery', breakdownBy: 'Page', properties: [], dateRange: { date_from: '-7d' } },
+ },
+]
+
+const tools = [
+ { tool: 'insight-create', base: {} },
+ { tool: 'insight-update', base: { id: 1 } },
+]
+
+const cases = tools.flatMap(({ tool, base }) => acceptedQueries.map((accepted) => ({ tool, base, ...accepted })))
+
+describe('insight query shapes', () => {
+ it.each(cases)('$tool accepts a $shape', ({ tool, base, query }) => {
+ const { schema } = GENERATED_TOOLS[tool]!()
+
+ expect(schema.safeParse({ ...base, query }).success).toBe(true)
+ })
+
+ it.each(tools)('$tool sends a bare query on to the endpoint whole', ({ tool, base }) => {
+ const { schema } = GENERATED_TOOLS[tool]!()
+
+ const result = schema.safeParse({ ...base, query: BARE_TRENDS_QUERY })
+
+ // The bare branches carry an index signature so the query keeps its body. Without it zod
+ // strips every key it does not declare, and the insight saves as an empty TrendsQuery.
+ expect(result.success).toBe(true)
+ expect((result.data as { query: unknown }).query).toEqual(BARE_TRENDS_QUERY)
+ })
+
+ it.each(tools)('$tool rejects a query kind the endpoint refuses to save', ({ tool, base }) => {
+ const { schema } = GENERATED_TOOLS[tool]!()
+
+ const query = { kind: 'ErrorTrackingQuery', dateRange: { date_from: '-7d' }, orderBy: 'last_seen' }
+
+ expect(schema.safeParse({ ...base, query }).success).toBe(false)
+ })
+})