: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-paths-actors with point-level drilldown (#61183)
Georgis Andonis87aed59d46dc
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 6362d5d768d5..39bae745cb8c 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -2917,6 +2917,27 @@"required": ["alias", "regex"],"type": "object"},+ "AssistantPathsActorsQuery": {+ "additionalProperties": false,+ "description": "Drills into a paths insight to list the persons behind it. Returned rows are `distinct_id`, `name`, `email`, `event_count`, and optionally matched session recordings.\n\nThere are no per-cell selectors like `day` or `series` — everything is configured on the `source` paths query. Two modes:\n- Whole path: set `pathsFilter.startPoint` / `endPoint` (plus `includeEventTypes`, date range, property filters) to return every actor on that path.\n- Specific node/edge: set `pathsFilter.pathEndKey` (arrived at a node), `pathStartKey` (departed from a node), both together (a single `source → target` edge), or `pathDropoffKey` (dropped off). The key value is `<stepIndex>_<value>`, taken verbatim from a `query-paths` result row's `target` / `source`.",+ "properties": {+ "includeRecordings": {+ "default": true,+ "description": "Whether to include matched session recordings for each actor.",+ "type": "boolean"+ },+ "kind": {+ "const": "InsightActorsQuery",+ "type": "string"+ },+ "source": {+ "$ref": "#/definitions/AssistantPathsQuery",+ "description": "The source paths insight query whose actors we are listing."+ }+ },+ "required": ["kind", "source"],+ "type": "object"+ },"AssistantPathsFilter": {"additionalProperties": false,"properties": {@@ -2960,6 +2981,14 @@"$ref": "#/definitions/integer","description": "Minimum number of users who traversed an edge for it to be displayed. Filters out low-traffic paths to reduce visual noise."},+ "pathDropoffKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **dropped off** at a specific node (reached it but did not continue). Format is `<stepIndex>_<value>`. Mutually exclusive with `pathStartKey` / `pathEndKey`. Ignored by non-actors paths queries.",+ "type": "string"+ },+ "pathEndKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **arrived at** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `\"3_https://example.com/checkout\"`. Take the value verbatim from a `target` field of a `query-paths` result row. Combine with `pathStartKey` to pin a single edge. Leave unset to return every actor on the path. Ignored by non-actors paths queries.",+ "type": "string"+ },"pathGroupings": {"default": [],"description": "Glob-like patterns to group multiple path items into a single step. Use `*` as a wildcard. The patterns are auto-escaped, so only `*` has special meaning. For example, `/product/*` to group all product pages into one node.",@@ -2968,6 +2997,10 @@},"type": "array"},+ "pathStartKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **departed from** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `\"2_https://example.com/pricing\"`. Take the value verbatim from a `source` field of a `query-paths` result row. Combine with `pathEndKey` to pin a single edge (source → target). Leave unset to return every actor on the path (constrained only by `startPoint` / `endPoint`). Ignored by non-actors paths queries.",+ "type": "string"+ },"pathsHogQLExpression": {"description": "A HogQL expression to use as the path item. Required when `hogql` is included in `includeEventTypes`. For example, `properties.$current_url` to use the current URL as the path item.","type": "string"diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.tsindex 0d06fdef5419..eb2400f00340 100644--- a/frontend/src/queries/schema/schema-assistant-queries.ts+++ b/frontend/src/queries/schema/schema-assistant-queries.ts@@ -1143,6 +1143,28 @@ export interface AssistantPathsFilter {* Filters out high-traffic paths to focus on less common journeys.*/maxEdgeWeight?: integer+ /**+ * Actors drilldown only. Restrict the returned persons to those who **departed from** a specific+ * node in the path graph. Format is `<stepIndex>_<value>`, e.g. `"2_https://example.com/pricing"`.+ * Take the value verbatim from a `source` field of a `query-paths` result row. Combine with+ * `pathEndKey` to pin a single edge (source → target). Leave unset to return every actor on the+ * path (constrained only by `startPoint` / `endPoint`). Ignored by non-actors paths queries.+ */+ pathStartKey?: string+ /**+ * Actors drilldown only. Restrict the returned persons to those who **arrived at** a specific+ * node in the path graph. Format is `<stepIndex>_<value>`, e.g. `"3_https://example.com/checkout"`.+ * Take the value verbatim from a `target` field of a `query-paths` result row. Combine with+ * `pathStartKey` to pin a single edge. Leave unset to return every actor on the path. Ignored by+ * non-actors paths queries.+ */+ pathEndKey?: string+ /**+ * Actors drilldown only. Restrict the returned persons to those who **dropped off** at a specific+ * node (reached it but did not continue). Format is `<stepIndex>_<value>`. Mutually exclusive with+ * `pathStartKey` / `pathEndKey`. Ignored by non-actors paths queries.+ */+ pathDropoffKey?: string}export interface AssistantPathsQuery extends AssistantInsightsQueryBase {@@ -1293,6 +1315,32 @@ export interface AssistantLifecycleActorsQuery {status: AssistantLifecycleStatus}+/**+ * Drills into a paths insight to list the persons behind it. Returned rows are `distinct_id`,+ * `name`, `email`, `event_count`, and optionally matched session recordings.+ *+ * There are no per-cell selectors like `day` or `series` — everything is configured on the `source`+ * paths query. Two modes:+ * - Whole path: set `pathsFilter.startPoint` / `endPoint` (plus `includeEventTypes`, date range,+ * property filters) to return every actor on that path.+ * - Specific node/edge: set `pathsFilter.pathEndKey` (arrived at a node), `pathStartKey` (departed+ * from a node), both together (a single `source → target` edge), or `pathDropoffKey` (dropped off).+ * The key value is `<stepIndex>_<value>`, taken verbatim from a `query-paths` result row's+ * `target` / `source`.+ */+export interface AssistantPathsActorsQuery {+ kind: NodeKind.InsightActorsQuery++ /** The source paths insight query whose actors we are listing. */+ source: AssistantPathsQuery++ /**+ * Whether to include matched session recordings for each actor.+ * @default true+ */+ includeRecordings?: boolean+}+/*** 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 b9f7d3227935..33c97df00c4f 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6247,6 +6247,26 @@ class AssistantPathsFilter(BaseModel):" Filters out low-traffic paths to reduce visual noise."),)+ pathDropoffKey: str | None = Field(+ default=None,+ description=(+ "Actors drilldown only. Restrict the returned persons to those who"+ " **dropped off** at a specific node (reached it but did not continue)."+ " Format is `<stepIndex>_<value>`. Mutually exclusive with `pathStartKey` /"+ " `pathEndKey`. Ignored by non-actors paths queries."+ ),+ )+ pathEndKey: str | None = Field(+ default=None,+ description=(+ "Actors drilldown only. Restrict the returned persons to those who"+ " **arrived at** a specific node in the path graph. Format is"+ ' `<stepIndex>_<value>`, e.g. `"3_https://example.com/checkout"`. Take the'+ " value verbatim from a `target` field of a `query-paths` result row."+ " Combine with `pathStartKey` to pin a single edge. Leave unset to return"+ " every actor on the path. Ignored by non-actors paths queries."+ ),+ )pathGroupings: list[str] | None = Field(default=[],description=(@@ -6256,6 +6276,18 @@ class AssistantPathsFilter(BaseModel):" node."),)+ pathStartKey: str | None = Field(+ default=None,+ description=(+ "Actors drilldown only. Restrict the returned persons to those who"+ " **departed from** a specific node in the path graph. Format is"+ ' `<stepIndex>_<value>`, e.g. `"2_https://example.com/pricing"`. Take the'+ " value verbatim from a `source` field of a `query-paths` result row."+ " Combine with `pathEndKey` to pin a single edge (source → target). Leave"+ " unset to return every actor on the path (constrained only by `startPoint`"+ " / `endPoint`). Ignored by non-actors paths queries."+ ),+ )pathsHogQLExpression: str | None = Field(default=None,description=(@@ -22182,6 +22214,18 @@ class AssistantLifecycleQuery(BaseModel):)+class AssistantPathsActorsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ includeRecordings: bool | None = Field(+ default=True,+ description="Whether to include matched session recordings for each actor.",+ )+ kind: Literal["InsightActorsQuery"] = "InsightActorsQuery"+ source: AssistantPathsQuery = Field(..., description="The source paths insight query whose actors we are listing.")++class AssistantTrendsActorsQuery(BaseModel):model_config = ConfigDict(extra="forbid",diff --git a/services/mcp/definitions/prompts/query-paths-actors.md b/services/mcp/definitions/prompts/query-paths-actors.mdnew file mode 100644index 000000000000..cc18611628b2--- /dev/null+++ b/services/mcp/definitions/prompts/query-paths-actors.md@@ -0,0 +1,29 @@+List the persons behind a paths insight — either everyone who traversed the path, or those at one specific node/edge.++Pair this with `query-paths`: first run the paths query to see the flows (each result row is an edge `source → target` with a user count), then call this tool with the **same** paths query as `source`.++Two modes:++**1. Everyone on the path (A → B).** Set `startPoint` / `endPoint` on the source `pathsFilter` and leave the path keys unset. Returns every actor whose journey matches that start/end constraint. Use this for "who went from a.com to b.com?".++**2. Actors at a specific point.** Each node in the path graph has a key of the form `<stepIndex>_<value>` (e.g. `"3_https://example.com/checkout"`). The `source` and `target` fields of a `query-paths` result row **are** these keys — copy them verbatim. Set on the source `pathsFilter`:++- `pathEndKey` — persons who **arrived at** that node (use a row's `target`).+- `pathStartKey` — persons who **departed from** that node (use a row's `source`).+- Set **both** `pathStartKey` + `pathEndKey` to pin a single edge (the actors behind one `source → target` count).+- `pathDropoffKey` — persons who **dropped off** at that node. Mutually exclusive with the other two.++Selectors:++- `includeRecordings`: defaults to `true`. Set to `false` to skip fetching matched session recordings (faster if recordings are not needed).++Response:++Each returned row contains `distinct_id`, `name`, `email`, and `event_count` (number of matching events for that actor). When `includeRecordings` is `true` (the default), a `recordings` column is also returned with PostHog replay URLs. Results are limited to the top 100 actors ordered by event count.++Guidance:++- Keep the `source` paths query minimal — only include the filters needed to define the same population the user is asking about.+- The path keys come straight from a `query-paths` result row's `source` / `target`; do not hand-construct them.+- `pathReplacements` and `showFullUrls` are not exposed — they don't change which actors are returned (`showFullUrls` is display-only; `pathReplacements` is covered by `localPathCleaningFilters`).+- For large result sets, narrow the source (start/end point, date range, filters) rather than expecting more rows.diff --git a/services/mcp/definitions/query-wrappers.yaml b/services/mcp/definitions/query-wrappers.yamlindex 482414c72592..1148371a674f 100644--- a/services/mcp/definitions/query-wrappers.yaml+++ b/services/mcp/definitions/query-wrappers.yaml@@ -191,3 +191,22 @@ wrappers:exclude_properties:- response- modifiers++ query-paths-actors:+ schema_ref: AssistantPathsActorsQuery+ enabled: true+ scopes:+ - query:read+ - person:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List persons on a paths insight+ description_file: ./prompts/query-paths-actors.md+ system_prompt_hint: List persons who traversed the paths defined by a paths insight+ 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 ed6628954725..01ed05ae93fb 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4212,6 +4212,21 @@},"system_prompt_hint": "User navigation flows and sequences"},+ "query-paths-actors": {+ "description": "List the persons behind a paths insight — either everyone who traversed the path, or those at one specific node/edge.\n\nPair this with `query-paths`: first run the paths query to see the flows (each result row is an edge `source → target` with a user count), then call this tool with the **same** paths query as `source`.\n\nTwo modes:\n\n**1. Everyone on the path (A → B).** Set `startPoint` / `endPoint` on the source `pathsFilter` and leave the path keys unset. Returns every actor whose journey matches that start/end constraint. Use this for \"who went from a.com to b.com?\".\n\n**2. Actors at a specific point.** Each node in the path graph has a key of the form `<stepIndex>_<value>` (e.g. `\"3_https://example.com/checkout\"`). The `source` and `target` fields of a `query-paths` result row **are** these keys — copy them verbatim. Set on the source `pathsFilter`:\n\n- `pathEndKey` — persons who **arrived at** that node (use a row's `target`).\n- `pathStartKey` — persons who **departed from** that node (use a row's `source`).\n- Set **both** `pathStartKey` + `pathEndKey` to pin a single edge (the actors behind one `source → target` count).\n- `pathDropoffKey` — persons who **dropped off** at that node. Mutually exclusive with the other two.\n\nSelectors:\n\n- `includeRecordings`: defaults to `true`. Set to `false` to skip fetching matched session recordings (faster if recordings are not needed).\n\nResponse:\n\nEach returned row contains `distinct_id`, `name`, `email`, and `event_count` (number of matching events for that actor). When `includeRecordings` is `true` (the default), a `recordings` column is also returned with PostHog replay URLs. Results are limited to the top 100 actors ordered by event count.\n\nGuidance:\n\n- Keep the `source` paths query minimal — only include the filters needed to define the same population the user is asking about.\n- The path keys come straight from a `query-paths` result row's `source` / `target`; do not hand-construct them.\n- `pathReplacements` and `showFullUrls` are not exposed — they don't change which actors are returned (`showFullUrls` is display-only; `pathReplacements` is covered by `localPathCleaningFilters`).\n- For large result sets, narrow the source (start/end point, date range, filters) rather than expecting more rows.",+ "category": "Query wrappers",+ "feature": "insights",+ "summary": "List persons on a paths insight",+ "title": "List persons on a paths insight",+ "required_scopes": ["query:read", "person:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "List persons who traversed the paths defined by a paths insight"+ },"query-retention": {"description": "Run a retention query to analyze how many users return over time after performing an initial action. Retention insights show you how many users return during subsequent periods. They're useful for understanding user engagement and stickiness.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nExamples of use cases include:\n\n- Are new sign ups coming back to use your product after trying it?\n- Have recent changes improved retention?\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\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `paidCustomer` or `icp_score`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n- You set logical operators to combine multiple properties of a single series: AND or OR.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 30 days as a default time period.\n\n# Retention guidelines\n\nRetention insights always require two entities:\n\n- The activation event (targetEntity) – determines if the user is a part of a cohort (when they \"start\").\n- The retention event (returningEntity) – determines whether a user has been retained (when they \"return\").\n\nFor activation and retention events, use the `$pageview` event by default or the equivalent for mobile apps `$screen`. Avoid infrequent or inconsistent events like `signed in` unless asked explicitly, as they skew the data.\n\nThe activation and retention events can be the same (e.g., both `$pageview` to see if users who viewed pages come back to view pages again) or different (e.g., activation is `signed up` and retention is `completed purchase` to see if sign-ups convert to purchases over time).\n\n# Examples\n\n## Weekly retention of users who created an insight\n\n```json\n{\n \"kind\": \"RetentionQuery\",\n \"retentionFilter\": {\n \"period\": \"Week\",\n \"totalIntervals\": 9,\n \"targetEntity\": { \"id\": \"insight created\", \"name\": \"insight created\", \"type\": \"events\" },\n \"returningEntity\": { \"id\": \"insight created\", \"name\": \"insight created\", \"type\": \"events\" },\n \"retentionType\": \"retention_first_time\",\n \"retentionReference\": \"total\",\n \"cumulative\": false\n },\n \"filterTestAccounts\": true\n}\n```\n\n## Do users who sign up come back to view pages?\n\n```json\n{\n \"kind\": \"RetentionQuery\",\n \"retentionFilter\": {\n \"period\": \"Week\",\n \"totalIntervals\": 8,\n \"targetEntity\": { \"id\": \"user signed up\", \"name\": \"user signed up\", \"type\": \"events\" },\n \"returningEntity\": { \"id\": \"$pageview\", \"name\": \"$pageview\", \"type\": \"events\" },\n \"retentionType\": \"retention_first_time\",\n \"retentionReference\": \"total\",\n \"cumulative\": false\n },\n \"dateRange\": { \"date_from\": \"-60d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Daily retention of pageviews for mobile users only\n\n```json\n{\n \"kind\": \"RetentionQuery\",\n \"retentionFilter\": {\n \"period\": \"Day\",\n \"totalIntervals\": 14,\n \"targetEntity\": { \"id\": \"$pageview\", \"name\": \"$pageview\", \"type\": \"events\" },\n \"returningEntity\": { \"id\": \"$pageview\", \"name\": \"$pageview\", \"type\": \"events\" },\n \"retentionType\": \"retention_first_time\",\n \"retentionReference\": \"total\",\n \"cumulative\": false\n },\n \"properties\": [{ \"key\": \"$os\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"iOS\", \"Android\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.","category": "Query wrappers",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f715917662da..9015b5b88456 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4495,6 +4495,21 @@},"system_prompt_hint": "User navigation flows and sequences"},+ "query-paths-actors": {+ "description": "List the persons behind a paths insight — either everyone who traversed the path, or those at one specific node/edge.\n\nPair this with `query-paths`: first run the paths query to see the flows (each result row is an edge `source → target` with a user count), then call this tool with the **same** paths query as `source`.\n\nTwo modes:\n\n**1. Everyone on the path (A → B).** Set `startPoint` / `endPoint` on the source `pathsFilter` and leave the path keys unset. Returns every actor whose journey matches that start/end constraint. Use this for \"who went from a.com to b.com?\".\n\n**2. Actors at a specific point.** Each node in the path graph has a key of the form `<stepIndex>_<value>` (e.g. `\"3_https://example.com/checkout\"`). The `source` and `target` fields of a `query-paths` result row **are** these keys — copy them verbatim. Set on the source `pathsFilter`:\n\n- `pathEndKey` — persons who **arrived at** that node (use a row's `target`).\n- `pathStartKey` — persons who **departed from** that node (use a row's `source`).\n- Set **both** `pathStartKey` + `pathEndKey` to pin a single edge (the actors behind one `source → target` count).\n- `pathDropoffKey` — persons who **dropped off** at that node. Mutually exclusive with the other two.\n\nSelectors:\n\n- `includeRecordings`: defaults to `true`. Set to `false` to skip fetching matched session recordings (faster if recordings are not needed).\n\nResponse:\n\nEach returned row contains `distinct_id`, `name`, `email`, and `event_count` (number of matching events for that actor). When `includeRecordings` is `true` (the default), a `recordings` column is also returned with PostHog replay URLs. Results are limited to the top 100 actors ordered by event count.\n\nGuidance:\n\n- Keep the `source` paths query minimal — only include the filters needed to define the same population the user is asking about.\n- The path keys come straight from a `query-paths` result row's `source` / `target`; do not hand-construct them.\n- `pathReplacements` and `showFullUrls` are not exposed — they don't change which actors are returned (`showFullUrls` is display-only; `pathReplacements` is covered by `localPathCleaningFilters`).\n- For large result sets, narrow the source (start/end point, date range, filters) rather than expecting more rows.",+ "category": "Query wrappers",+ "feature": "insights",+ "summary": "List persons on a paths insight",+ "title": "List persons on a paths insight",+ "required_scopes": ["query:read", "person:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "system_prompt_hint": "List persons who traversed the paths defined by a paths insight"+ },"query-retention": {"description": "Run a retention query to analyze how many users return over time after performing an initial action. Retention insights show you how many users return during subsequent periods. They're useful for understanding user engagement and stickiness.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters.\n\nExamples of use cases include:\n\n- Are new sign ups coming back to use your product after trying it?\n- Have recent changes improved retention?\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\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Avoid using properties for identification like IDs. Instead, prioritize filtering based on general properties like `paidCustomer` or `icp_score`.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n- You set logical operators to combine multiple properties of a single series: AND or OR.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 30 days as a default time period.\n\n# Retention guidelines\n\nRetention insights always require two entities:\n\n- The activation event (targetEntity) – determines if the user is a part of a cohort (when they \"start\").\n- The retention event (returningEntity) – determines whether a user has been retained (when they \"return\").\n\nFor activation and retention events, use the `$pageview` event by default or the equivalent for mobile apps `$screen`. Avoid infrequent or inconsistent events like `signed in` unless asked explicitly, as they skew the data.\n\nThe activation and retention events can be the same (e.g., both `$pageview` to see if users who viewed pages come back to view pages again) or different (e.g., activation is `signed up` and retention is `completed purchase` to see if sign-ups convert to purchases over time).\n\n# Examples\n\n## Weekly retention of users who created an insight\n\n```json\n{\n \"kind\": \"RetentionQuery\",\n \"retentionFilter\": {\n \"period\": \"Week\",\n \"totalIntervals\": 9,\n \"targetEntity\": { \"id\": \"insight created\", \"name\": \"insight created\", \"type\": \"events\" },\n \"returningEntity\": { \"id\": \"insight created\", \"name\": \"insight created\", \"type\": \"events\" },\n \"retentionType\": \"retention_first_time\",\n \"retentionReference\": \"total\",\n \"cumulative\": false\n },\n \"filterTestAccounts\": true\n}\n```\n\n## Do users who sign up come back to view pages?\n\n```json\n{\n \"kind\": \"RetentionQuery\",\n \"retentionFilter\": {\n \"period\": \"Week\",\n \"totalIntervals\": 8,\n \"targetEntity\": { \"id\": \"user signed up\", \"name\": \"user signed up\", \"type\": \"events\" },\n \"returningEntity\": { \"id\": \"$pageview\", \"name\": \"$pageview\", \"type\": \"events\" },\n \"retentionType\": \"retention_first_time\",\n \"retentionReference\": \"total\",\n \"cumulative\": false\n },\n \"dateRange\": { \"date_from\": \"-60d\" },\n \"filterTestAccounts\": true\n}\n```\n\n## Daily retention of pageviews for mobile users only\n\n```json\n{\n \"kind\": \"RetentionQuery\",\n \"retentionFilter\": {\n \"period\": \"Day\",\n \"totalIntervals\": 14,\n \"targetEntity\": { \"id\": \"$pageview\", \"name\": \"$pageview\", \"type\": \"events\" },\n \"returningEntity\": { \"id\": \"$pageview\", \"name\": \"$pageview\", \"type\": \"events\" },\n \"retentionType\": \"retention_first_time\",\n \"retentionReference\": \"total\",\n \"cumulative\": false\n },\n \"properties\": [{ \"key\": \"$os\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"iOS\", \"Android\"] }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true\n}\n```\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.","category": "Query wrappers",diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 97b85ceb319b..27263d913ef4 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -1204,6 +1204,9 @@ export class ApiClient {runActorsQuery(query, ['actor', 'event_count'], ['event_count DESC', 'actor_id DESC']),lifecycleActors: async ({ query }: { query: Record<string, unknown> }) => runActorsQuery(query, ['actor']),++ pathsActors: async ({ query }: { query: Record<string, unknown> }) =>+ runActorsQuery(query, ['actor', 'event_count'], ['event_count DESC', 'actor_id DESC']),}}diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.tsindex f801c44f8500..4f8240a24e2b 100644--- a/services/mcp/src/tools/generated/query-wrappers.ts+++ b/services/mcp/src/tools/generated/query-wrappers.ts@@ -1031,6 +1031,18 @@ const AssistantPathsFilter = z.object({'Minimum number of users who traversed an edge for it to be displayed. Filters out low-traffic paths to reduce visual noise.').optional(),+ pathDropoffKey: z+ .string()+ .describe(+ 'Actors drilldown only. Restrict the returned persons to those who **dropped off** at a specific node (reached it but did not continue). Format is `<stepIndex>_<value>`. Mutually exclusive with `pathStartKey` / `pathEndKey`. Ignored by non-actors paths queries.'+ )+ .optional(),+ pathEndKey: z+ .string()+ .describe(+ 'Actors drilldown only. Restrict the returned persons to those who **arrived at** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `"3_https://example.com/checkout"`. Take the value verbatim from a `target` field of a `query-paths` result row. Combine with `pathStartKey` to pin a single edge. Leave unset to return every actor on the path. Ignored by non-actors paths queries.'+ )+ .optional(),pathGroupings: z.array(z.string()).describe(@@ -1038,6 +1050,12 @@ const AssistantPathsFilter = z.object({).default([]).optional(),+ pathStartKey: z+ .string()+ .describe(+ 'Actors drilldown only. Restrict the returned persons to those who **departed from** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `"2_https://example.com/pricing"`. Take the value verbatim from a `source` field of a `query-paths` result row. Combine with `pathEndKey` to pin a single edge (source → target). Leave unset to return every actor on the path (constrained only by `startPoint` / `endPoint`). Ignored by non-actors paths queries.'+ )+ .optional(),pathsHogQLExpression: z.string().describe(@@ -1217,6 +1235,16 @@ const AssistantLifecycleActorsQuery = z.object({),})+const AssistantPathsActorsQuery = z.object({+ includeRecordings: z.coerce+ .boolean()+ .describe('Whether to include matched session recordings for each actor.')+ .default(true)+ .optional(),+ kind: z.literal('InsightActorsQuery').default('InsightActorsQuery'),+ source: AssistantPathsQuery.describe('The source paths insight query whose actors we are listing.'),+})+const QueryTrendsSchema = AssistantTrendsQuery.extend({output_format: z.enum(['optimized', 'json'])@@ -1297,6 +1325,16 @@ const QueryLifecycleActorsSchema = AssistantLifecycleActorsQuery.extend({),})+const QueryPathsActorsSchema = AssistantPathsActorsQuery.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>>> = {@@ -1368,4 +1406,11 @@ export const GENERATED_TOOLS: Record<string, ReturnType<typeof createQueryWrappeuiResourceUri: 'ui://posthog/insight-actors.html',outputFormat: 'optimized',}),+ 'query-paths-actors': createQueryWrapper({+ name: 'query-paths-actors',+ schema: QueryPathsActorsSchema,+ kind: 'InsightActorsQuery',+ uiResourceUri: 'ui://posthog/insight-actors.html',+ outputFormat: 'optimized',+ }),}diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex dacff8495dcc..ac8ddad81fac 100644--- a/services/mcp/src/tools/query-wrapper-factory.ts+++ b/services/mcp/src/tools/query-wrapper-factory.ts@@ -63,6 +63,9 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperCcase 'TrendsQuery':data = await queryClient.trendsActors({ query })break+ case 'PathsQuery':+ data = await queryClient.pathsActors({ query })+ breakdefault:throw new Error(`Unsupported source kind for actors query: ${sourceKind}`)}diff --git a/services/mcp/tests/tools/query-wrappers.integration.test.ts b/services/mcp/tests/tools/query-wrappers.integration.test.tsindex 19bec128717e..88641fecb589 100644--- a/services/mcp/tests/tools/query-wrappers.integration.test.ts+++ b/services/mcp/tests/tools/query-wrappers.integration.test.ts@@ -461,4 +461,72 @@ describe('Query Wrapper Integration Tests', { concurrent: false }, () => {expect(result.query.source.status).toBe('returning')})})++ describe('query-paths-actors', () => {+ const pathsSource = {+ kind: 'PathsQuery',+ pathsFilter: {+ includeEventTypes: ['$pageview'],+ stepLimit: 5,+ },+ dateRange: { date_from: '-7d' },+ }++ it('returns a flat {columns, rows} table with the actors projection', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-paths-actors')+ const result = (await tool.handler(context, { source: pathsSource })) 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('wraps the source in an outer ActorsQuery with the event-count projection and ordering', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-paths-actors')+ const result = (await tool.handler(context, {+ source: pathsSource,+ includeRecordings: false,+ })) as any++ expect(result.query.kind).toBe('ActorsQuery')+ expect(result.query.select).toEqual(['actor', 'event_count'])+ expect(result.query.orderBy).toEqual(['event_count DESC', 'actor_id DESC'])+ expect(result.query.source.kind).toBe('InsightActorsQuery')+ expect(result.query.source.source.kind).toBe('PathsQuery')+ expect(result.results.columns).toEqual(['distinct_id', 'email', 'name', 'event_count'])+ })++ it('appends matched_recordings to the projection when includeRecordings is true', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-paths-actors')+ const result = (await tool.handler(context, {+ source: pathsSource,+ includeRecordings: true,+ })) as any++ expect(result.query.select).toEqual(['actor', 'event_count', 'matched_recordings'])+ expect(result.results.columns).toEqual(['distinct_id', 'email', 'name', 'event_count', 'recordings'])+ })++ it('forwards the point-level drilldown keys into source.source.pathsFilter', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-paths-actors')+ const result = (await tool.handler(context, {+ source: {+ ...pathsSource,+ pathsFilter: {+ ...pathsSource.pathsFilter,+ startPoint: 'https://posthog.com/',+ endPoint: 'https://us.posthog.com/',+ pathEndKey: '3_https://us.posthog.com',+ },+ },+ })) as any++ const sourcePathsFilter = result.query.source.source.pathsFilter+ expect(sourcePathsFilter.pathEndKey).toBe('3_https://us.posthog.com')+ expect(sourcePathsFilter.startPoint).toBe('https://posthog.com/')+ expect(sourcePathsFilter.endPoint).toBe('https://us.posthog.com/')+ })+ })})diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex 4c16c02f74ed..fa4f574507a4 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 with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill 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> series.properties` — to see property filter structure of series\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: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\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-export\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-reports\n- inbox-source-configs\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-personal-spend\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\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- signals-scout-emit-signal\n- signals-scout-runs\n- signals-scout-scratchpad-forget\n- signals-scout-scratchpad-remember\n- signals-scout-scratchpad-search\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 for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\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>"+ "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 with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill 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> series.properties` — to see property filter structure of series\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: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\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-export\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-reports\n- inbox-source-configs\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-personal-spend\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\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- signals-scout-emit-signal\n- signals-scout-runs\n- signals-scout-scratchpad-forget\n- signals-scout-scratchpad-remember\n- signals-scout-scratchpad-search\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 for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\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-paths-actors` — List persons who traversed the paths defined by a paths insight\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/query-paths-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths-actors.jsonnew file mode 100644index 000000000000..f214463cd686--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths-actors.json@@ -0,0 +1,689 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "includeRecordings": {+ "default": true,+ "description": "Whether to include matched session recordings for each actor.",+ "type": "boolean"+ },+ "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 paths insight query whose actors we are listing.",+ "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"+ },+ "kind": {+ "const": "PathsQuery",+ "default": "PathsQuery",+ "type": "string"+ },+ "pathsFilter": {+ "description": "Properties specific to the paths insight. Paths show the most common sequences of events or pages that users navigate through, helping identify popular user flows and drop-off points.",+ "properties": {+ "edgeLimit": {+ "default": 50,+ "description": "Maximum number of path edges (connections between steps) to return. Higher values show more detail but can make the visualization harder to read.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "endPoint": {+ "description": "Filter to only show paths that end at this specific step. Same format as `startPoint`.",+ "type": "string"+ },+ "excludeEvents": {+ "default": [],+ "description": "Event names or URLs to exclude from the path analysis entirely. Excluded events are filtered out before building the path visualization. Useful for removing noise from common but uninteresting events.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "includeEventTypes": {+ "description": "Which event types to include in the path analysis. Available values: `$pageview` - web page views. Path values are page URLs (from `$current_url`), with trailing slashes stripped. `$screen` - mobile screen views. Path values are screen names (from `$screen_name`). `custom_event` - custom events (any event not starting with `$`). Path values are event names. `hogql` - custom HogQL expression defined in `pathsHogQLExpression`. Path values come from evaluating the expression. You can combine multiple types. If not specified, all events are included without type filtering.",+ "items": {+ "enum": ["$pageview", "$screen", "custom_event", "hogql"],+ "type": "string"+ },+ "type": "array"+ },+ "localPathCleaningFilters": {+ "default": [],+ "description": "ClickHouse regex-based rules to clean and normalize path values at the query level. Each rule applies `replaceRegexpAll(path, regex, alias)` in sequence. Useful for removing dynamic IDs or parameters from URLs.",+ "items": {+ "properties": {+ "alias": {+ "description": "A human-readable alias that replaces matched path patterns in the visualization. For example, `/user/:id/profile` to replace `/user/123/profile`. Uses ClickHouse `replaceRegexpAll` replacement syntax — use `\\\\1` for capture group back-references.",+ "type": "string"+ },+ "regex": {+ "description": "A ClickHouse regex pattern to match against path values. Matched paths will be replaced with the alias. For example, `\\/user\\/\\d+\\/profile` to match any user profile URL.",+ "type": "string"+ }+ },+ "required": ["alias", "regex"],+ "type": "object"+ },+ "type": "array"+ },+ "maxEdgeWeight": {+ "description": "Maximum number of users who traversed an edge for it to be displayed. Filters out high-traffic paths to focus on less common journeys.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "minEdgeWeight": {+ "description": "Minimum number of users who traversed an edge for it to be displayed. Filters out low-traffic paths to reduce visual noise.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "pathDropoffKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **dropped off** at a specific node (reached it but did not continue). Format is `<stepIndex>_<value>`. Mutually exclusive with `pathStartKey` / `pathEndKey`. Ignored by non-actors paths queries.",+ "type": "string"+ },+ "pathEndKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **arrived at** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `\"3_https://example.com/checkout\"`. Take the value verbatim from a `target` field of a `query-paths` result row. Combine with `pathStartKey` to pin a single edge. Leave unset to return every actor on the path. Ignored by non-actors paths queries.",+ "type": "string"+ },+ "pathGroupings": {+ "default": [],+ "description": "Glob-like patterns to group multiple path items into a single step. Use `*` as a wildcard. The patterns are auto-escaped, so only `*` has special meaning. For example, `/product/*` to group all product pages into one node.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "pathsHogQLExpression": {+ "description": "A HogQL expression to use as the path item. Required when `hogql` is included in `includeEventTypes`. For example, `properties.$current_url` to use the current URL as the path item.",+ "type": "string"+ },+ "pathStartKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **departed from** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `\"2_https://example.com/pricing\"`. Take the value verbatim from a `source` field of a `query-paths` result row. Combine with `pathEndKey` to pin a single edge (source → target). Leave unset to return every actor on the path (constrained only by `startPoint` / `endPoint`). Ignored by non-actors paths queries.",+ "type": "string"+ },+ "startPoint": {+ "description": "Filter to only show paths that start from this specific step. The value format depends on the included event types: For `$pageview` paths, use page URLs like `/login` or `/dashboard`. For `$screen` paths, use screen names. For `custom_event` paths, use event names.",+ "type": "string"+ },+ "stepLimit": {+ "default": 5,+ "description": "Maximum number of steps (path depth) to show in the visualization. Controls how deep the path analysis goes from the start.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ }+ },+ "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": {+ "default": "in",+ "enum": ["in", "not_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. Use `operator: \"in\"` to include cohort members, or `operator: \"not_in\"` to exclude them. Examples:\n- Include: `{ type: \"cohort\", key: \"id\", value: 42, operator: \"in\" }`\n- Exclude: `{ type: \"cohort\", key: \"id\", value: 42, operator: \"not_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": ["pathsFilter"],+ "type": "object"+ }+ },+ "required": ["source"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.jsonindex ff14b1b37058..dd976a240bd2 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-paths.json@@ -127,6 +127,14 @@"minimum": -9007199254740991,"type": "integer"},+ "pathDropoffKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **dropped off** at a specific node (reached it but did not continue). Format is `<stepIndex>_<value>`. Mutually exclusive with `pathStartKey` / `pathEndKey`. Ignored by non-actors paths queries.",+ "type": "string"+ },+ "pathEndKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **arrived at** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `\"3_https://example.com/checkout\"`. Take the value verbatim from a `target` field of a `query-paths` result row. Combine with `pathStartKey` to pin a single edge. Leave unset to return every actor on the path. Ignored by non-actors paths queries.",+ "type": "string"+ },"pathGroupings": {"default": [],"description": "Glob-like patterns to group multiple path items into a single step. Use `*` as a wildcard. The patterns are auto-escaped, so only `*` has special meaning. For example, `/product/*` to group all product pages into one node.",@@ -139,6 +147,10 @@"description": "A HogQL expression to use as the path item. Required when `hogql` is included in `includeEventTypes`. For example, `properties.$current_url` to use the current URL as the path item.","type": "string"},+ "pathStartKey": {+ "description": "Actors drilldown only. Restrict the returned persons to those who **departed from** a specific node in the path graph. Format is `<stepIndex>_<value>`, e.g. `\"2_https://example.com/pricing\"`. Take the value verbatim from a `source` field of a `query-paths` result row. Combine with `pathEndKey` to pin a single edge (source → target). Leave unset to return every actor on the path (constrained only by `startPoint` / `endPoint`). Ignored by non-actors paths queries.",+ "type": "string"+ },"startPoint": {"description": "Filter to only show paths that start from this specific step. The value format depends on the included event types: For `$pageview` paths, use page URLs like `/login` or `/dashboard`. For `$screen` paths, use screen names. For `custom_event` paths, use event names.","type": "string"diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 5e04df2893b6..469d513e829b 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -93,6 +93,7 @@ describe('createQueryWrapper _posthogUrl', () => {context: ContexttrendsActors: ReturnType<typeof vi.fn>lifecycleActors: ReturnType<typeof vi.fn>+ pathsActors: ReturnType<typeof vi.fn>} {const actorsResponse = {query: { kind: 'ActorsQuery', source: { kind: 'InsightActorsQuery' } },@@ -102,14 +103,15 @@ describe('createQueryWrapper _posthogUrl', () => {}const trendsActors = vi.fn().mockResolvedValue(actorsResponse)const lifecycleActors = vi.fn().mockResolvedValue(actorsResponse)+ const pathsActors = vi.fn().mockResolvedValue(actorsResponse)const context = {api: {- query: vi.fn().mockReturnValue({ trendsActors, lifecycleActors }),+ query: vi.fn().mockReturnValue({ trendsActors, lifecycleActors, pathsActors }),getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),},stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },} as unknown as Context- return { context, trendsActors, lifecycleActors }+ return { context, trendsActors, lifecycleActors, pathsActors }}const actorsSchema = z.object({@@ -139,6 +141,18 @@ describe('createQueryWrapper _posthogUrl', () => {expect(result._posthogUrl).toContain('DataTableNode')})+ it('dispatches PathsQuery source to pathsActors', async () => {+ const { context, trendsActors, lifecycleActors, pathsActors } = createActorsDispatchContext()+ const tool = createQueryWrapper({ name: 'test', schema: actorsSchema, kind: 'InsightActorsQuery' })()++ const result = (await tool.handler(context, { source: { kind: 'PathsQuery' } })) as any++ expect(pathsActors).toHaveBeenCalledOnce()+ expect(trendsActors).not.toHaveBeenCalled()+ expect(lifecycleActors).not.toHaveBeenCalled()+ expect(result._posthogUrl).toContain('DataTableNode')+ })+it('uses hash param not query param', async () => {const context = createMockContext()const factory = createQueryWrapper({ name: 'test', schema, kind: 'TrendsQuery' })@@ -293,6 +307,7 @@ describe('createQueryWrapper actors dispatch', () => {runQuery: vi.fn(),trendsActors: vi.fn(),lifecycleActors: vi.fn(),+ pathsActors: vi.fn(),}),getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),},@@ -308,8 +323,8 @@ describe('createQueryWrapper actors dispatch', () => {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'+ await expect(tool.handler(context, { source: { kind: 'RetentionQuery' } })).rejects.toThrow(+ 'Unsupported source kind for actors query: RetentionQuery')})})