: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
feat(mcp): add query-lifecycle-actors tool (#57929)
Georgis Andonis20e93b3a3597
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex f390c89ace8d..18485606ba6a 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -2320,6 +2320,30 @@"required": ["id", "kind", "name"],"type": "object"},+ "AssistantLifecycleActorsQuery": {+ "additionalProperties": false,+ "description": "Drills into a lifecycle insight to list the persons behind a specific bucket. Returned rows are `distinct_id`, `email`, and `name`. Lifecycle is a bucket-membership query, so no per-actor `event_count` or matched recordings are projected — the underlying lifecycle runner does not surface a `matching_events` column.\n\nUse the selector fields (`day`, `status`) to identify the specific bucket — a lifecycle insight is a 4-row stack (new / returning / resurrecting / dormant) per day.\n\nNote: lifecycle insights only support a single series and do not expose `compareFilter`, so `series` and `compare` selectors are intentionally omitted.",+ "properties": {+ "day": {+ "description": "Bucket date for the data point. Must be an ISO date string (YYYY-MM-DD), e.g. '2024-01-15'.",+ "type": "string"+ },+ "kind": {+ "const": "InsightActorsQuery",+ "type": "string"+ },+ "source": {+ "$ref": "#/definitions/AssistantLifecycleQuery",+ "description": "The source lifecycle insight query whose bucket we are drilling into."+ },+ "status": {+ "$ref": "#/definitions/AssistantLifecycleStatus",+ "description": "Lifecycle status to drill into for the given day. Must be one of the bucket names visible in the source's `lifecycleFilter.toggledLifecycles` (defaults to all four when omitted)."+ }+ },+ "required": ["kind", "source", "day", "status"],+ "type": "object"+ },"AssistantLifecycleEventsNode": {"additionalProperties": false,"properties": {@@ -2446,6 +2470,11 @@}]},+ "AssistantLifecycleStatus": {+ "description": "A single lifecycle bucket — see `AssistantLifecycleActorsQuery.status`.",+ "enum": ["new", "returning", "resurrecting", "dormant"],+ "type": "string"+ },"AssistantMessage": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.tsindex a3629ad6f396..dc5abc3def74 100644--- a/frontend/src/queries/schema/schema-assistant-queries.ts+++ b/frontend/src/queries/schema/schema-assistant-queries.ts@@ -1253,6 +1253,37 @@ export interface AssistantTrendsActorsQuery {includeRecordings?: boolean}+/** A single lifecycle bucket — see `AssistantLifecycleActorsQuery.status`. */+export type AssistantLifecycleStatus = 'new' | 'returning' | 'resurrecting' | 'dormant'++/**+ * Drills into a lifecycle insight to list the persons behind a specific bucket. Returned rows+ * are `distinct_id`, `email`, and `name`. Lifecycle is a bucket-membership query, so no+ * per-actor `event_count` or matched recordings are projected — the underlying lifecycle+ * runner does not surface a `matching_events` column.+ *+ * Use the selector fields (`day`, `status`) to identify the specific bucket — a lifecycle insight+ * is a 4-row stack (new / returning / resurrecting / dormant) per day.+ *+ * Note: lifecycle insights only support a single series and do not expose `compareFilter`, so+ * `series` and `compare` selectors are intentionally omitted.+ */+export interface AssistantLifecycleActorsQuery {+ kind: NodeKind.InsightActorsQuery++ /** The source lifecycle insight query whose bucket we are drilling into. */+ source: AssistantLifecycleQuery++ /** Bucket date for the data point. Must be an ISO date string (YYYY-MM-DD), e.g. '2024-01-15'. */+ day: string++ /**+ * Lifecycle status to drill into for the given day. Must be one of the bucket names visible+ * in the source's `lifecycleFilter.toggledLifecycles` (defaults to all four when omitted).+ */+ status: AssistantLifecycleStatus+}+/*** Query LLM traces to inspect AI/LLM usage. Returns a list of traces with latency,* token usage, costs, errors, and other metadata. Use for AI observability — debuggingdiff --git a/posthog/schema.py b/posthog/schema.pyindex f1879658586b..26aab952ce94 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -445,6 +445,13 @@ class AssistantInsightVizNode(BaseModel):)+class AssistantLifecycleStatus(StrEnum):+ NEW = "new"+ RETURNING = "returning"+ RESURRECTING = "resurrecting"+ DORMANT = "dormant"++class AssistantMessageType(StrEnum):HUMAN = "human"TOOL = "tool"@@ -20104,6 +20111,29 @@ class WebVitalsPathBreakdownQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class AssistantLifecycleActorsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ day: str = Field(+ ...,+ description=("Bucket date for the data point. Must be an ISO date string (YYYY-MM-DD), e.g. '2024-01-15'."),+ )+ kind: Literal["InsightActorsQuery"] = "InsightActorsQuery"+ source: AssistantLifecycleQuery = Field(+ ...,+ description=("The source lifecycle insight query whose bucket we are drilling into."),+ )+ status: AssistantLifecycleStatus = Field(+ ...,+ description=(+ "Lifecycle status to drill into for the given day. Must be one of the"+ " bucket names visible in the source's `lifecycleFilter.toggledLifecycles`"+ " (defaults to all four when omitted)."+ ),+ )++class CachedErrorTrackingIssueCorrelationQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",diff --git a/services/mcp/definitions/prompts/query-lifecycle-actors.md b/services/mcp/definitions/prompts/query-lifecycle-actors.mdnew file mode 100644index 000000000000..0cc630de129f--- /dev/null+++ b/services/mcp/definitions/prompts/query-lifecycle-actors.md@@ -0,0 +1,22 @@+List the persons in a specific bucket of a lifecycle insight. Use this to answer "who are the new / returning / resurrecting / dormant users on day Y?".++`source` is the lifecycle query that defines the population (event, date range, filters). Build it directly when the user's request already names a bucket-day, or reuse one you previously ran via `query-lifecycle` when drilling in from a chart.++Selectors:++- `day` **(required)**: the bucket date as an ISO date string (YYYY-MM-DD), e.g. `"2024-01-15"`. Must align with the source's interval (a day boundary for `interval=day`, the start of the week for `interval=week`, etc.).+- `status` **(required)**: which lifecycle bucket to drill into. One of `new`, `returning`, `resurrecting`, `dormant`.+ - `new` — users performing the event for the first time during the period.+ - `returning` — users active in the previous period and active in this one.+ - `resurrecting` — users inactive for one or more periods and active again now.+ - `dormant` — users active in the previous period but inactive now.++Response:++Each returned row contains `distinct_id`, `email`, and `name`. Results are limited to the top 100 actors. Matched session recordings are not returned — the lifecycle runner does not project per-actor matching events.++Guidance:++- Lifecycle insights only support a single series and do not expose `compareFilter`, so there is no `series` or `compare` selector here.+- Keep the `source` lifecycle query minimal — only include the filters needed to define the same lifecycle population the user is asking about.+- For large buckets, tighten the source query (filters, date range) rather than expecting more rows.diff --git a/services/mcp/definitions/query-wrappers.yaml b/services/mcp/definitions/query-wrappers.yamlindex fe96350e6972..42a806203200 100644--- a/services/mcp/definitions/query-wrappers.yaml+++ b/services/mcp/definitions/query-wrappers.yaml@@ -181,3 +181,23 @@ wrappers:exclude_properties:- response- modifiers++ query-lifecycle-actors:+ schema_ref: AssistantLifecycleActorsQuery+ enabled: true+ scopes:+ - query:read+ - person:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ mcp_version: 2+ title: List persons in a lifecycle bucket+ description_file: ./prompts/query-lifecycle-actors.md+ system_prompt_hint: List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day+ ui_resource_uri: ui://posthog/insight-actors.html+ use_optimized_output: true+ exclude_properties:+ - response+ - modifiersdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6bb9c8b1f35d..0725d59fde06 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3860,6 +3860,22 @@},"system_prompt_hint": "New, returning, resurrecting, dormant user composition"},+ "query-lifecycle-actors": {+ "description": "List the persons in a specific bucket of a lifecycle insight. Use this to answer \"who are the new / returning / resurrecting / dormant users on day Y?\".\n\n`source` is the lifecycle query that defines the population (event, date range, filters). Build it directly when the user's request already names a bucket-day, or reuse one you previously ran via `query-lifecycle` when drilling in from a chart.\n\nSelectors:\n\n- `day` **(required)**: the bucket date as an ISO date string (YYYY-MM-DD), e.g. `\"2024-01-15\"`. Must align with the source's interval (a day boundary for `interval=day`, the start of the week for `interval=week`, etc.).\n- `status` **(required)**: which lifecycle bucket to drill into. One of `new`, `returning`, `resurrecting`, `dormant`.\n - `new` — users performing the event for the first time during the period.\n - `returning` — users active in the previous period and active in this one.\n - `resurrecting` — users inactive for one or more periods and active again now.\n - `dormant` — users active in the previous period but inactive now.\n\nResponse:\n\nEach returned row contains `distinct_id`, `email`, and `name`. Results are limited to the top 100 actors. Matched session recordings are not returned — the lifecycle runner does not project per-actor matching events.\n\nGuidance:\n\n- Lifecycle insights only support a single series and do not expose `compareFilter`, so there is no `series` or `compare` selector here.\n- Keep the `source` lifecycle query minimal — only include the filters needed to define the same lifecycle population the user is asking about.\n- For large buckets, tighten the source query (filters, date range) rather than expecting more rows.",+ "category": "Query wrappers",+ "feature": "insights",+ "summary": "List persons in a lifecycle bucket",+ "title": "List persons in a lifecycle bucket",+ "required_scopes": ["query:read", "person:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day"+ },"query-llm-trace": {"description": "Fetch a single LLM trace by its trace ID for deep inspection. Returns the complete trace with all nested events and their full properties — including inputs, outputs, model parameters, costs, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.\n\nUse cases:\n\n- Inspect the full input/output of each generation in a trace\n- Debug a specific error trace found in the list\n- Examine the agent's decision-making flow across spans\n- Review tool calls and their results within a trace\n- Analyze token usage and costs per generation\n\nCRITICAL: This tool requires a `traceId`. Get the trace ID from `query-llm-traces-list` results first.\n\n# Response shape\n\nThe response contains a single trace in JSON format with:\n\n- `id` — the trace ID\n- `traceName` — name of the trace (if set via SDK)\n- `createdAt` — timestamp of the first event in the trace\n- `distinctId` — the person's distinct ID\n- `aiSessionId` — session ID grouping related traces (e.g., a conversation)\n- `totalLatency` — total latency in seconds\n- `inputTokens` / `outputTokens` — token counts across all generations\n- `inputCost` / `outputCost` / `totalCost` — costs in USD\n- `inputState` / `outputState` — JSON input/output state from the root `$ai_trace` event (e.g., conversation messages)\n- `events` — **all** child events in the trace at every nesting depth (not just direct children). Each event has full `properties`.\n\nUnlike `query-llm-traces-list`, this tool does NOT return `errorCount`, `isSupportTrace`, or `tools` — those are summary fields on the list tool only.\n\n# Event types and their properties\n\nEach event in `events` has an `event` field indicating its type. Key properties vary by type:\n\n- **`$ai_generation`** / **`$ai_embedding`** — an LLM or embedding API call. Properties include `$ai_input` (input prompt JSON), `$ai_output_choices` (output message JSON), `$ai_model`, `$ai_provider`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd`, `$ai_tools_called`, `$ai_is_error`, `$ai_error`.\n- **`$ai_span`** — a unit of work within a trace (e.g., a retrieval step, tool execution). Properties include `$ai_input_state`, `$ai_output_state`, `$ai_latency`, `$ai_span_name`, `$ai_parent_id`.\n- **`$ai_metric`** — a named evaluation metric. Properties include `$ai_metric_name`, `$ai_metric_value`.\n- **`$ai_feedback`** — user-provided feedback. Properties include `$ai_feedback_text`.\n\nNote: `$ai_trace` events are NOT included in the `events` array — their data is surfaced via the trace-level `inputState`, `outputState`, and `traceName` fields.\n\n# Tree structure (IDs and parent-child relationships)\n\nEvents in a trace form a tree. Each event carries three IDs that define its position:\n\n- `$ai_trace_id` — present on every event, identifies which trace it belongs to (same as the trace's `id`)\n- `$ai_span_id` (or `$ai_generation_id` for generations) — the event's own unique identifier\n- `$ai_parent_id` — points to the parent event's `$ai_span_id`\n\nTo reconstruct the tree:\n\n1. Events where `$ai_parent_id` equals `$ai_trace_id` are **root-level children** of the trace\n2. Other events are children of the event whose `$ai_span_id` matches their `$ai_parent_id`\n3. Group events by `$ai_parent_id` and walk from root children downward\n\nGenerations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf nodes. Spans (`$ai_span`) can have children.\n\n# Examples\n\n## Fetch a trace by ID\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\"\n}\n```\n\n## Fetch with a date range hint\n\nIf the trace is old, provide a date range to help the query find it efficiently:\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\",\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Reminders\n\n- Always get the `traceId` from `query-llm-traces-list` results — do not guess or fabricate trace IDs.\n- If no date range is provided, the default lookback window is used. For older traces, provide an explicit `dateRange`.\n- The `events` array contains ALL events in the trace (including deeply nested ones), making this suitable for full tree reconstruction.\n- Use `query-llm-traces-list` first to find traces, then this tool to inspect a specific one.","category": "Query wrappers",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8c85a53d8e73..94d70894e9c9 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4234,6 +4234,22 @@},"system_prompt_hint": "New, returning, resurrecting, dormant user composition"},+ "query-lifecycle-actors": {+ "description": "List the persons in a specific bucket of a lifecycle insight. Use this to answer \"who are the new / returning / resurrecting / dormant users on day Y?\".\n\n`source` is the lifecycle query that defines the population (event, date range, filters). Build it directly when the user's request already names a bucket-day, or reuse one you previously ran via `query-lifecycle` when drilling in from a chart.\n\nSelectors:\n\n- `day` **(required)**: the bucket date as an ISO date string (YYYY-MM-DD), e.g. `\"2024-01-15\"`. Must align with the source's interval (a day boundary for `interval=day`, the start of the week for `interval=week`, etc.).\n- `status` **(required)**: which lifecycle bucket to drill into. One of `new`, `returning`, `resurrecting`, `dormant`.\n - `new` — users performing the event for the first time during the period.\n - `returning` — users active in the previous period and active in this one.\n - `resurrecting` — users inactive for one or more periods and active again now.\n - `dormant` — users active in the previous period but inactive now.\n\nResponse:\n\nEach returned row contains `distinct_id`, `email`, and `name`. Results are limited to the top 100 actors. Matched session recordings are not returned — the lifecycle runner does not project per-actor matching events.\n\nGuidance:\n\n- Lifecycle insights only support a single series and do not expose `compareFilter`, so there is no `series` or `compare` selector here.\n- Keep the `source` lifecycle query minimal — only include the filters needed to define the same lifecycle population the user is asking about.\n- For large buckets, tighten the source query (filters, date range) rather than expecting more rows.",+ "category": "Query wrappers",+ "feature": "insights",+ "summary": "List persons in a lifecycle bucket",+ "title": "List persons in a lifecycle bucket",+ "required_scopes": ["query:read", "person:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day"+ },"query-llm-trace": {"description": "Fetch a single LLM trace by its trace ID for deep inspection. Returns the complete trace with all nested events and their full properties — including inputs, outputs, model parameters, costs, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.\n\nUse cases:\n\n- Inspect the full input/output of each generation in a trace\n- Debug a specific error trace found in the list\n- Examine the agent's decision-making flow across spans\n- Review tool calls and their results within a trace\n- Analyze token usage and costs per generation\n\nCRITICAL: This tool requires a `traceId`. Get the trace ID from `query-llm-traces-list` results first.\n\n# Response shape\n\nThe response contains a single trace in JSON format with:\n\n- `id` — the trace ID\n- `traceName` — name of the trace (if set via SDK)\n- `createdAt` — timestamp of the first event in the trace\n- `distinctId` — the person's distinct ID\n- `aiSessionId` — session ID grouping related traces (e.g., a conversation)\n- `totalLatency` — total latency in seconds\n- `inputTokens` / `outputTokens` — token counts across all generations\n- `inputCost` / `outputCost` / `totalCost` — costs in USD\n- `inputState` / `outputState` — JSON input/output state from the root `$ai_trace` event (e.g., conversation messages)\n- `events` — **all** child events in the trace at every nesting depth (not just direct children). Each event has full `properties`.\n\nUnlike `query-llm-traces-list`, this tool does NOT return `errorCount`, `isSupportTrace`, or `tools` — those are summary fields on the list tool only.\n\n# Event types and their properties\n\nEach event in `events` has an `event` field indicating its type. Key properties vary by type:\n\n- **`$ai_generation`** / **`$ai_embedding`** — an LLM or embedding API call. Properties include `$ai_input` (input prompt JSON), `$ai_output_choices` (output message JSON), `$ai_model`, `$ai_provider`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd`, `$ai_tools_called`, `$ai_is_error`, `$ai_error`.\n- **`$ai_span`** — a unit of work within a trace (e.g., a retrieval step, tool execution). Properties include `$ai_input_state`, `$ai_output_state`, `$ai_latency`, `$ai_span_name`, `$ai_parent_id`.\n- **`$ai_metric`** — a named evaluation metric. Properties include `$ai_metric_name`, `$ai_metric_value`.\n- **`$ai_feedback`** — user-provided feedback. Properties include `$ai_feedback_text`.\n\nNote: `$ai_trace` events are NOT included in the `events` array — their data is surfaced via the trace-level `inputState`, `outputState`, and `traceName` fields.\n\n# Tree structure (IDs and parent-child relationships)\n\nEvents in a trace form a tree. Each event carries three IDs that define its position:\n\n- `$ai_trace_id` — present on every event, identifies which trace it belongs to (same as the trace's `id`)\n- `$ai_span_id` (or `$ai_generation_id` for generations) — the event's own unique identifier\n- `$ai_parent_id` — points to the parent event's `$ai_span_id`\n\nTo reconstruct the tree:\n\n1. Events where `$ai_parent_id` equals `$ai_trace_id` are **root-level children** of the trace\n2. Other events are children of the event whose `$ai_span_id` matches their `$ai_parent_id`\n3. Group events by `$ai_parent_id` and walk from root children downward\n\nGenerations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf nodes. Spans (`$ai_span`) can have children.\n\n# Examples\n\n## Fetch a trace by ID\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\"\n}\n```\n\n## Fetch with a date range hint\n\nIf the trace is old, provide a date range to help the query find it efficiently:\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\",\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Reminders\n\n- Always get the `traceId` from `query-llm-traces-list` results — do not guess or fabricate trace IDs.\n- If no date range is provided, the default lookback window is used. For older traces, provide an explicit `dateRange`.\n- The `events` array contains ALL events in the trace (including deeply nested ones), making this suitable for full tree reconstruction.\n- Use `query-llm-traces-list` first to find traces, then this tool to inspect a specific one.","category": "Query wrappers",diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 0f12f3fd8d39..cc360f42d076 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -1058,6 +1058,81 @@ export class ApiClient {return normalized}+ const runActorsQuery = async (+ query: Record<string, unknown>,+ select: readonly string[],+ orderBy: readonly string[] = []+ ): Promise<{+ query: Record<string, unknown>+ results: { columns: string[]; results: any[][] }+ hasMore: boolean+ offset: number+ }> => {+ const normalized = normalizeQuery(query)+ const includeRecordings = Boolean(normalized.includeRecordings)+ const finalSelect = includeRecordings ? [...select, 'matched_recordings'] : [...select]++ const wrappedQuery = {+ kind: 'ActorsQuery',+ source: normalized,+ select: finalSelect,+ orderBy: [...orderBy],+ limit: 100,+ }++ const response = await this.request<{+ results: any[][]+ hasMore?: boolean+ offset?: number+ }>({+ method: 'POST',+ path: `/api/environments/${projectId}/query/`,+ body: { query: wrappedQuery },+ })++ const baseUrl = this.getProjectBaseUrl(projectId)++ // `actor` → 3 columns, `matched_recordings` → recordings, everything else passes through.+ const columns: string[] = []+ for (const field of finalSelect) {+ if (field === 'actor') {+ columns.push('distinct_id', 'email', 'name')+ } else if (field === 'matched_recordings') {+ columns.push('recordings')+ } else {+ columns.push(field)+ }+ }++ const results = (response.results ?? []).map((row) => {+ const cells: any[] = []+ for (let i = 0; i < finalSelect.length; i++) {+ const field = finalSelect[i]+ const cell = row[i]+ if (field === 'actor') {+ const props = cell?.properties ?? {}+ cells.push(cell?.distinct_ids?.[0] ?? null, props.email, props.name)+ } else if (field === 'matched_recordings') {+ const links = (cell ?? [])+ .map((r: any) => r.session_id)+ .filter(Boolean)+ .map((sessionId: string) => `${baseUrl}/replay/${sessionId}`)+ cells.push(links)+ } else {+ cells.push(cell)+ }+ }+ return cells+ })++ return {+ query: wrappedQuery,+ results: { columns, results },+ hasMore: response.hasMore ?? false,+ offset: response.offset ?? 0,+ }+ }+return {execute: async ({ queryBody }: { queryBody: any }): Promise<Result<{ results: any[] }>> => {return this.fetchJson<{ results: unknown[] }>(queryUrl, {@@ -1078,66 +1153,10 @@ export class ApiClient {})},- trendsActors: async ({- query,- }: {- query: Record<string, unknown>- }): Promise<{- query: Record<string, unknown>- results: { columns: readonly string[]; results: (string | number | null)[][] }- hasMore: boolean- offset: number- }> => {- const normalized = normalizeQuery(query)- const includeRecordings = Boolean(normalized.includeRecordings)- const wrappedQuery = {- kind: 'ActorsQuery',- source: normalized,- select: includeRecordings- ? ['actor', 'event_count', 'matched_recordings']- : ['actor', 'event_count'],- orderBy: ['event_count DESC', 'actor_id DESC'],- limit: 100,- }-- const response = await this.request<{- results: any[][]- hasMore?: boolean- offset?: number- }>({- method: 'POST',- path: `/api/environments/${projectId}/query/`,- body: { query: wrappedQuery },- })+ trendsActors: async ({ query }: { query: Record<string, unknown> }) =>+ runActorsQuery(query, ['actor', 'event_count'], ['event_count DESC', 'actor_id DESC']),- const baseUrl = this.getProjectBaseUrl(projectId)- const results = (response.results ?? []).map((row) => {- const [actor, count] = row- const properties = actor.properties ?? {}- const distinctId = actor.distinct_ids?.[0] ?? null- const base = [distinctId, properties.email, properties.name, count]- if (includeRecordings) {- const recordingLinks = (row[2] ?? [])- .map((r: any) => r.session_id)- .filter(Boolean)- .map((sessionId: string) => `${baseUrl}/replay/${sessionId}`)- return [...base, recordingLinks]- }- return base- })-- return {- query: wrappedQuery,- results: {- columns: includeRecordings- ? ['distinct_id', 'email', 'name', 'event_count', 'recordings']- : ['distinct_id', 'email', 'name', 'event_count'],- results,- },- hasMore: response.hasMore ?? false,- offset: response.offset ?? 0,- }- },+ lifecycleActors: async ({ query }: { query: Record<string, unknown> }) => runActorsQuery(query, ['actor']),}}diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.tsindex 69c22760f23b..642f2c361a12 100644--- a/services/mcp/src/tools/generated/query-wrappers.ts+++ b/services/mcp/src/tools/generated/query-wrappers.ts@@ -1202,6 +1202,19 @@ const AssistantTrendsActorsQuery = z.object({source: AssistantTrendsQuery.describe('The source insight query whose data point we are drilling into.'),})+const AssistantLifecycleStatus = z.enum(['new', 'returning', 'resurrecting', 'dormant'])++const AssistantLifecycleActorsQuery = z.object({+ day: z+ .string()+ .describe("Bucket date for the data point. Must be an ISO date string (YYYY-MM-DD), e.g. '2024-01-15'."),+ kind: z.literal('InsightActorsQuery').default('InsightActorsQuery'),+ source: AssistantLifecycleQuery.describe('The source lifecycle insight query whose bucket we are drilling into.'),+ status: AssistantLifecycleStatus.describe(+ "Lifecycle status to drill into for the given day. Must be one of the bucket names visible in the source's `lifecycleFilter.toggledLifecycles` (defaults to all four when omitted)."+ ),+})+const QueryTrendsSchema = AssistantTrendsQuery.extend({output_format: z.enum(['optimized', 'json'])@@ -1272,6 +1285,16 @@ const QueryTrendsActorsSchema = AssistantTrendsActorsQuery.extend({),})+const QueryLifecycleActorsSchema = AssistantLifecycleActorsQuery.extend({+ output_format: z+ .enum(['optimized', 'json'])+ .default('optimized')+ .optional()+ .describe(+ 'Output format. "optimized" returns a human-readable summary from server-side formatters (recommended for analysis). "json" returns the raw query results as JSON.'+ ),+})+// --- Tool registrations ---export const GENERATED_TOOLS: Record<string, ReturnType<typeof createQueryWrapper<ZodObjectAny>>> = {@@ -1345,4 +1368,12 @@ export const GENERATED_TOOLS: Record<string, ReturnType<typeof createQueryWrappeoutputFormat: 'optimized',mcpVersion: 2,}),+ 'query-lifecycle-actors': createQueryWrapper({+ name: 'query-lifecycle-actors',+ schema: QueryLifecycleActorsSchema,+ kind: 'InsightActorsQuery',+ uiResourceUri: 'ui://posthog/insight-actors.html',+ outputFormat: 'optimized',+ mcpVersion: 2,+ }),}diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex 649750c1124e..3fbb07166803 100644--- a/services/mcp/src/tools/query-wrapper-factory.ts+++ b/services/mcp/src/tools/query-wrapper-factory.ts@@ -56,7 +56,19 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperCconst effectiveOutputFormat = callerOutputFormat ?? config.outputFormatif (config.kind.endsWith('ActorsQuery')) {- const data = await context.api.query({ projectId }).trendsActors({ query })+ const sourceKind = (query.source as Record<string, unknown> | undefined)?.kind+ const queryClient = context.api.query({ projectId })+ let data+ switch (sourceKind) {+ case 'LifecycleQuery':+ data = await queryClient.lifecycleActors({ query })+ break+ case 'TrendsQuery':+ data = await queryClient.trendsActors({ query })+ break+ default:+ throw new Error(`Unsupported source kind for actors query: ${sourceKind}`)+ }return {...data,_posthogUrl: buildInsightUrl('DataTableNode', data.query, baseUrl, config.urlPrefix),diff --git a/services/mcp/tests/tools/query-wrappers.integration.test.ts b/services/mcp/tests/tools/query-wrappers.integration.test.tsindex 2a56d45d4388..19bec128717e 100644--- a/services/mcp/tests/tools/query-wrappers.integration.test.ts+++ b/services/mcp/tests/tools/query-wrappers.integration.test.ts@@ -392,4 +392,73 @@ describe('Query Wrapper Integration Tests', { concurrent: false }, () => {expect(Array.isArray(result.results.results)).toBe(true)})})++ describe('query-lifecycle-actors', () => {+ const lifecycleSource = {+ kind: 'LifecycleQuery',+ series: [{ kind: 'EventsNode', event: '$pageview' }],+ dateRange: { date_from: '-7d' },+ interval: 'day',+ lifecycleFilter: {},+ }++ it('rejects when day is missing', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-lifecycle-actors')+ await expect(tool.handler(context, { source: lifecycleSource, status: 'dormant' })).rejects.toThrow()+ })++ it('rejects when status is missing', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-lifecycle-actors')+ await expect(tool.handler(context, { source: lifecycleSource, day: '2026-03-25' })).rejects.toThrow()+ })++ it('rejects status values outside the lifecycle bucket enum', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-lifecycle-actors')+ await expect(+ tool.handler(context, { source: lifecycleSource, day: '2026-03-25', status: 'churned' })+ ).rejects.toThrow()+ })++ it('returns a flat {columns, rows} table with the actors projection', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-lifecycle-actors')+ const result = (await tool.handler(context, {+ source: lifecycleSource,+ day: '2026-03-25',+ status: 'dormant',+ })) as any++ expect(result).toHaveProperty('query')+ expect(result).toHaveProperty('hasMore')+ expect(result).toHaveProperty('offset')+ expect(result).toHaveProperty('results')+ expect(Array.isArray(result.results.results)).toBe(true)+ })++ it('returns the persons projection', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-lifecycle-actors')+ const result = (await tool.handler(context, {+ source: lifecycleSource,+ day: '2026-03-25',+ status: 'new',+ })) as any++ expect(result.results.columns).toEqual(['distinct_id', 'email', 'name'])+ })++ it('wraps the source query in an outer ActorsQuery with select=["actor"] and no orderBy', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-lifecycle-actors')+ const result = (await tool.handler(context, {+ source: lifecycleSource,+ day: '2026-03-25',+ status: 'returning',+ })) as any++ expect(result.query.kind).toBe('ActorsQuery')+ expect(result.query.select).toEqual(['actor'])+ expect(result.query.orderBy).toEqual([])+ expect(result.query.source.kind).toBe('InsightActorsQuery')+ expect(result.query.source.source.kind).toBe('LifecycleQuery')+ expect(result.query.source.status).toBe('returning')+ })+ })})diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex d1d55501c5b7..8a0c1f1ffe12 100644--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json@@ -15,7 +15,7 @@"properties": {"command": {"type": "string",- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"}},"required": ["command"]diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-lifecycle-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-lifecycle-actors.jsonnew file mode 100644index 000000000000..649ee3703850--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-lifecycle-actors.json@@ -0,0 +1,1752 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "day": {+ "description": "Bucket date for the data point. Must be an ISO date string (YYYY-MM-DD), e.g. '2024-01-15'.",+ "type": "string"+ },+ "kind": {+ "const": "InsightActorsQuery",+ "default": "InsightActorsQuery",+ "type": "string"+ },+ "output_format": {+ "default": "optimized",+ "description": "Output format. \"optimized\" returns a human-readable summary from server-side formatters (recommended for analysis). \"json\" returns the raw query results as JSON.",+ "enum": ["optimized", "json"],+ "type": "string"+ },+ "source": {+ "description": "The source lifecycle insight query whose bucket we are drilling into.",+ "properties": {+ "aggregation_group_type_index": {+ "anyOf": [+ {+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "description": "Groups aggregation"+ },+ "dateRange": {+ "anyOf": [+ {+ "properties": {+ "date_from": {+ "description": "ISO8601 date string.",+ "type": "string"+ },+ "date_to": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "ISO8601 date string."+ }+ },+ "required": ["date_from"],+ "type": "object"+ },+ {+ "properties": {+ "date_from": {+ "description": "Duration in the past. Supported units are: `h` (hour), `d` (day), `w` (week), `m` (month), `y` (year), `all` (all time). Use the `Start` suffix to define the exact left date boundary. Examples: `-1d` last day from now, `-180d` last 180 days from now, `mStart` this month start, `-1dStart` yesterday's start.",+ "type": "string"+ }+ },+ "required": ["date_from"],+ "type": "object"+ }+ ],+ "description": "Date range for the query"+ },+ "filterTestAccounts": {+ "default": false,+ "description": "Exclude internal and test users by applying the respective filters",+ "type": "boolean"+ },+ "interval": {+ "default": "day",+ "description": "Granularity of the response. Can be one of `hour`, `day`, `week` or `month`",+ "enum": ["second", "minute", "hour", "day", "week", "month"],+ "type": "string"+ },+ "kind": {+ "const": "LifecycleQuery",+ "default": "LifecycleQuery",+ "type": "string"+ },+ "lifecycleFilter": {+ "description": "Properties specific to the lifecycle insight",+ "properties": {+ "showLegend": {+ "default": false,+ "description": "Whether to show the legend describing series.",+ "type": "boolean"+ },+ "showValuesOnSeries": {+ "default": false,+ "description": "Whether to show a value on each data point.",+ "type": "boolean"+ },+ "stacked": {+ "default": true,+ "description": "Whether the lifecycle bars should be stacked.",+ "type": "boolean"+ },+ "toggledLifecycles": {+ "description": "Lifecycles that have been removed from display are not included in this array. Available values: `new`, `returning`, `resurrecting`, `dormant`.\n- `new` - users who performed the event for the first time during the period.\n- `returning` - users who were active in the previous period and are active in the current period.\n- `resurrecting` - users who were inactive for one or more periods and became active again.\n- `dormant` - users who were active in the previous period but are inactive in the current period.",+ "items": {+ "enum": ["new", "resurrecting", "returning", "dormant"],+ "type": "string"+ },+ "type": "array"+ }+ },+ "type": "object"+ },+ "properties": {+ "default": [],+ "description": "Property filters for all series",+ "items": {+ "anyOf": [+ {+ "anyOf": [+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["is_date_exact", "is_date_before", "is_date_after"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ }+ },+ "required": ["key", "operator", "type"],+ "type": "object"+ }+ ]+ },+ {+ "anyOf": [+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["group_type_index", "key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["group_type_index", "key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["group_type_index", "key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["is_date_exact", "is_date_before", "is_date_after"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["group_type_index", "key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ }+ },+ "required": ["group_type_index", "key", "operator"],+ "type": "object"+ }+ ]+ },+ {+ "properties": {+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "operator": {+ "const": "in",+ "default": "in",+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "description": "Filter events by cohort membership. Use this to narrow down results to persons belonging to a specific cohort. Example: `{ type: \"cohort\", key: \"id\", value: 42, operator: \"in\" }`",+ "type": "string"+ },+ "value": {+ "description": "The cohort ID to filter by.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ },+ {+ "anyOf": [+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "enum": ["is_date_exact", "is_date_before", "is_date_after"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ }+ ]+ },+ {+ "properties": {+ "key": {+ "description": "A HogQL boolean expression used as a filter condition.\n\nExamples:\n- Filter where a property exceeds a threshold: `toFloat(properties.load_time) > 5.0`\n- Filter with string matching: `properties.$current_url LIKE '%/pricing%'`\n- Filter with multiple conditions: `properties.$browser = 'Chrome' AND toFloat(properties.duration) > 30`",+ "type": "string"+ },+ "type": {+ "const": "hogql",+ "default": "hogql",+ "description": "Filter by a HogQL boolean expression for advanced filtering that can't be expressed with standard property filters.",+ "type": "string"+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The feature flag key.",+ "type": "string"+ },+ "operator": {+ "const": "flag_evaluates_to",+ "default": "flag_evaluates_to",+ "type": "string"+ },+ "type": {+ "const": "flag",+ "default": "flag",+ "description": "Filter events by feature flag state — only include events where a specific flag evaluated to a given value. Examples:\n- Flag enabled: `{ type: \"flag\", key: \"new-onboarding\", operator: \"flag_evaluates_to\", value: true }`\n- Specific variant: `{ type: \"flag\", key: \"checkout-experiment\", operator: \"flag_evaluates_to\", value: \"variant-a\" }`",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "string"+ }+ ],+ "description": "`true`/`false` for boolean flags, or a variant name string for multivariate flags."+ }+ },+ "required": ["key", "value"],+ "type": "object"+ }+ ]+ },+ "type": "array"+ },+ "series": {+ "description": "Event or action to analyze. Lifecycle insights only support a single series.",+ "items": {+ "anyOf": [+ {+ "properties": {+ "custom_name": {+ "type": "string"+ },+ "event": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The event or `null` for all events."+ },+ "kind": {+ "const": "EventsNode",+ "default": "EventsNode",+ "description": "Defines the event series for the lifecycle insight. Lifecycle does not support math aggregations.",+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "properties": {+ "items": {+ "anyOf": [+ {+ "anyOf": [+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": [+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ }+ },+ "required": ["key", "operator", "type"],+ "type": "object"+ }+ ]+ },+ {+ "anyOf": [+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": [+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ }+ },+ "required": ["group_type_index", "key", "operator"],+ "type": "object"+ }+ ]+ },+ {+ "properties": {+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "operator": {+ "const": "in",+ "default": "in",+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "description": "Filter events by cohort membership. Use this to narrow down results to persons belonging to a specific cohort. Example: `{ type: \"cohort\", key: \"id\", value: 42, operator: \"in\" }`",+ "type": "string"+ },+ "value": {+ "description": "The cohort ID to filter by.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ },+ {+ "anyOf": [+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "enum": [+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ }+ ]+ },+ {+ "properties": {+ "key": {+ "description": "A HogQL boolean expression used as a filter condition.\n\nExamples:\n- Filter where a property exceeds a threshold: `toFloat(properties.load_time) > 5.0`\n- Filter with string matching: `properties.$current_url LIKE '%/pricing%'`\n- Filter with multiple conditions: `properties.$browser = 'Chrome' AND toFloat(properties.duration) > 30`",+ "type": "string"+ },+ "type": {+ "const": "hogql",+ "default": "hogql",+ "description": "Filter by a HogQL boolean expression for advanced filtering that can't be expressed with standard property filters.",+ "type": "string"+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The feature flag key.",+ "type": "string"+ },+ "operator": {+ "const": "flag_evaluates_to",+ "default": "flag_evaluates_to",+ "type": "string"+ },+ "type": {+ "const": "flag",+ "default": "flag",+ "description": "Filter events by feature flag state — only include events where a specific flag evaluated to a given value. Examples:\n- Flag enabled: `{ type: \"flag\", key: \"new-onboarding\", operator: \"flag_evaluates_to\", value: true }`\n- Specific variant: `{ type: \"flag\", key: \"checkout-experiment\", operator: \"flag_evaluates_to\", value: \"variant-a\" }`",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "string"+ }+ ],+ "description": "`true`/`false` for boolean flags, or a variant name string for multivariate flags."+ }+ },+ "required": ["key", "value"],+ "type": "object"+ }+ ]+ },+ "type": "array"+ }+ },+ "type": "object"+ },+ {+ "properties": {+ "custom_name": {+ "type": "string"+ },+ "id": {+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "kind": {+ "const": "ActionsNode",+ "default": "ActionsNode",+ "description": "Defines the action series for the lifecycle insight. Lifecycle does not support math aggregations. You must provide the action ID in the `id` field and the name in the `name` field.",+ "type": "string"+ },+ "name": {+ "description": "Action name from the plan.",+ "type": "string"+ },+ "properties": {+ "items": {+ "anyOf": [+ {+ "anyOf": [+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": [+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "type", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "enum": ["event", "person", "session", "feature"],+ "type": "string"+ }+ },+ "required": ["key", "operator", "type"],+ "type": "object"+ }+ ]+ },+ {+ "anyOf": [+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "enum": [+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": [+ "group_type_index",+ "key",+ "operator",+ "value"+ ],+ "type": "object"+ },+ {+ "properties": {+ "group_type_index": {+ "description": "Index of the group type from the group mapping.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "key": {+ "description": "Use one of the properties the user has provided in the plan.",+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "const": "group",+ "default": "group",+ "type": "string"+ }+ },+ "required": ["group_type_index", "key", "operator"],+ "type": "object"+ }+ ]+ },+ {+ "properties": {+ "key": {+ "const": "id",+ "default": "id",+ "type": "string"+ },+ "operator": {+ "const": "in",+ "default": "in",+ "type": "string"+ },+ "type": {+ "const": "cohort",+ "default": "cohort",+ "description": "Filter events by cohort membership. Use this to narrow down results to persons belonging to a specific cohort. Example: `{ type: \"cohort\", key: \"id\", value: 42, operator: \"in\" }`",+ "type": "string"+ },+ "value": {+ "description": "The cohort ID to filter by.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "required": ["value"],+ "type": "object"+ },+ {+ "anyOf": [+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.",+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex"+ ],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "enum": ["exact", "gt", "lt"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`exact` - exact match of any of the values. `is_not` - does not match any of the values.",+ "enum": ["exact", "is_not"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string \"true\" or \"false\".",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "enum": [+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ },+ "value": {+ "description": "Value must be a date in ISO 8601 format.",+ "type": "string"+ }+ },+ "required": ["key", "operator", "value"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).",+ "enum": ["tag_name", "text", "href", "selector"],+ "type": "string"+ },+ "operator": {+ "description": "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected.",+ "enum": ["is_set", "is_not_set"],+ "type": "string"+ },+ "type": {+ "const": "element",+ "default": "element",+ "description": "Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: \"element\", key: \"text\", value: \"Sign Up\", operator: \"exact\" }`",+ "type": "string"+ }+ },+ "required": ["key", "operator"],+ "type": "object"+ }+ ]+ },+ {+ "properties": {+ "key": {+ "description": "A HogQL boolean expression used as a filter condition.\n\nExamples:\n- Filter where a property exceeds a threshold: `toFloat(properties.load_time) > 5.0`\n- Filter with string matching: `properties.$current_url LIKE '%/pricing%'`\n- Filter with multiple conditions: `properties.$browser = 'Chrome' AND toFloat(properties.duration) > 30`",+ "type": "string"+ },+ "type": {+ "const": "hogql",+ "default": "hogql",+ "description": "Filter by a HogQL boolean expression for advanced filtering that can't be expressed with standard property filters.",+ "type": "string"+ }+ },+ "required": ["key"],+ "type": "object"+ },+ {+ "properties": {+ "key": {+ "description": "The feature flag key.",+ "type": "string"+ },+ "operator": {+ "const": "flag_evaluates_to",+ "default": "flag_evaluates_to",+ "type": "string"+ },+ "type": {+ "const": "flag",+ "default": "flag",+ "description": "Filter events by feature flag state — only include events where a specific flag evaluated to a given value. Examples:\n- Flag enabled: `{ type: \"flag\", key: \"new-onboarding\", operator: \"flag_evaluates_to\", value: true }`\n- Specific variant: `{ type: \"flag\", key: \"checkout-experiment\", operator: \"flag_evaluates_to\", value: \"variant-a\" }`",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "string"+ }+ ],+ "description": "`true`/`false` for boolean flags, or a variant name string for multivariate flags."+ }+ },+ "required": ["key", "value"],+ "type": "object"+ }+ ]+ },+ "type": "array"+ }+ },+ "required": ["id", "name"],+ "type": "object"+ }+ ]+ },+ "maxItems": 1,+ "type": "array"+ }+ },+ "required": ["series"],+ "type": "object"+ },+ "status": {+ "description": "Lifecycle status to drill into for the given day. Must be one of the bucket names visible in the source's `lifecycleFilter.toggledLifecycles` (defaults to all four when omitted).",+ "enum": ["new", "returning", "resurrecting", "dormant"],+ "type": "string"+ }+ },+ "required": ["day", "source", "status"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 0ba45d2add1b..5e04df2893b6 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -49,16 +49,18 @@ describe('createQueryWrapper _posthogUrl', () => {baseUrl = 'http://localhost:8010',query: Record<string, unknown> = {}): Context {+ const actorsResponse = {+ query,+ results: { columns: [], results: [] },+ hasMore: false,+ offset: 0,+ }return {api: {query: vi.fn().mockReturnValue({runQuery: vi.fn().mockResolvedValue({ results: [] }),- trendsActors: vi.fn().mockResolvedValue({- query: query,- results: { columns: [], results: [] },- hasMore: false,- offset: 0,- }),+ trendsActors: vi.fn().mockResolvedValue(actorsResponse),+ lifecycleActors: vi.fn().mockResolvedValue(actorsResponse),}),getProjectBaseUrl: vi.fn().mockReturnValue(`${baseUrl}/project/${projectId}`),},@@ -87,22 +89,54 @@ describe('createQueryWrapper _posthogUrl', () => {})- it('wraps trends-actors in DataTableNode with the ActorsQuery as source', async () => {- const context = createMockContext('1', 'http://localhost:8010', {- kind: 'ActorsQuery',- source: { kind: 'InsightActorsQuery', day: '2024-01-15' },- })- const factory = createQueryWrapper({ name: 'test', schema, kind: 'InsightActorsQuery' })- const tool = factory()+ function createActorsDispatchContext(): {+ context: Context+ trendsActors: ReturnType<typeof vi.fn>+ lifecycleActors: ReturnType<typeof vi.fn>+ } {+ const actorsResponse = {+ query: { kind: 'ActorsQuery', source: { kind: 'InsightActorsQuery' } },+ results: { columns: [], results: [] },+ hasMore: false,+ offset: 0,+ }+ const trendsActors = vi.fn().mockResolvedValue(actorsResponse)+ const lifecycleActors = vi.fn().mockResolvedValue(actorsResponse)+ const context = {+ api: {+ query: vi.fn().mockReturnValue({ trendsActors, lifecycleActors }),+ getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),+ },+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },+ } as unknown as Context+ return { context, trendsActors, lifecycleActors }+ }- const result = (await tool.handler(context, {- series: [{ kind: 'EventsNode', event: '$pageview' }],- })) as any+ const actorsSchema = z.object({+ day: z.string().optional(),+ source: z.looseObject({ kind: z.string() }),+ })- const hash = result._posthogUrl.split('#q=')[1]- const parsed = JSON.parse(decodeURIComponent(hash))- expect(parsed.kind).toBe('DataTableNode')- expect(parsed.source.kind).toBe('ActorsQuery')+ it('dispatches TrendsQuery source to trendsActors', async () => {+ const { context, trendsActors, lifecycleActors } = createActorsDispatchContext()+ const tool = createQueryWrapper({ name: 'test', schema: actorsSchema, kind: 'InsightActorsQuery' })()++ const result = (await tool.handler(context, { source: { kind: 'TrendsQuery' } })) as any++ expect(trendsActors).toHaveBeenCalledOnce()+ expect(lifecycleActors).not.toHaveBeenCalled()+ expect(result._posthogUrl).toContain('DataTableNode')+ })++ it('dispatches LifecycleQuery source to lifecycleActors', async () => {+ const { context, trendsActors, lifecycleActors } = createActorsDispatchContext()+ const tool = createQueryWrapper({ name: 'test', schema: actorsSchema, kind: 'InsightActorsQuery' })()++ const result = (await tool.handler(context, { source: { kind: 'LifecycleQuery' } })) as any++ expect(lifecycleActors).toHaveBeenCalledOnce()+ expect(trendsActors).not.toHaveBeenCalled()+ expect(result._posthogUrl).toContain('DataTableNode')})it('uses hash param not query param', async () => {@@ -165,6 +199,7 @@ describe('createQueryWrapper output_format handling', () => {query: vi.fn().mockReturnValue({runQuery: runQueryMock,trendsActors: vi.fn(),+ lifecycleActors: vi.fn(),}),getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),},@@ -249,3 +284,32 @@ describe('createQueryWrapper output_format handling', () => {expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBe('formatted-text')})})++describe('createQueryWrapper actors dispatch', () => {+ function createMockContext(): Context {+ return {+ api: {+ query: vi.fn().mockReturnValue({+ runQuery: vi.fn(),+ trendsActors: vi.fn(),+ lifecycleActors: vi.fn(),+ }),+ getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),+ },+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },+ } as unknown as Context+ }++ it('throws when actors source kind is not supported', async () => {+ const context = createMockContext()+ const actorsSchema = z.object({+ source: z.looseObject({ kind: z.string() }),+ })+ const factory = createQueryWrapper({ name: 'test', schema: actorsSchema, kind: 'InsightActorsQuery' })+ const tool = factory()++ await expect(tool.handler(context, { source: { kind: 'PathsQuery' } })).rejects.toThrow(+ 'Unsupported source kind for actors query: PathsQuery'+ )+ })+})