:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): accept a query wrapper payload nested under query (#107426)
posthog[bot]c96f68da2e81
diff --git a/services/mcp/definitions/prompts/query-trends.md b/services/mcp/definitions/prompts/query-trends.mdindex c67deaaa91f0..b231028ab964 100644--- a/services/mcp/definitions/prompts/query-trends.md+++ b/services/mcp/definitions/prompts/query-trends.md@@ -22,7 +22,7 @@ Examples of use cases include:# Input shape-Send the query fields as the call arguments, at the top level. Do not wrap them in a `query`, `source`, or `events` object: this tool takes no such parameter, and a wrapped payload is rejected for a missing `series`.+Send the query fields as the call arguments, at the top level. Do not wrap them in a `query`, `source`, or `events` object: this tool takes no such parameter.`series` is the only required field. Every other field is optional.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c65f7f1b4225..cd8aa46f6700 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9816,7 +9816,7 @@"system_prompt_hint": "List persons who were active in a given number of intervals (one stickiness bar)"},"query-trends": {- "description": "Run a trends query to analyze metrics over time. Trends insights visualize events over time using time series. They're useful for finding patterns in historical data.\n\nUse this tool for native trends with supported aggregations, series, breakdowns, formulas, and period comparisons. Use `execute-sql` for record inspection or custom SQL calculations. When both tools preserve the requested calculation and output, prefer this tool for a new query, including simple aggregates. Keep valid existing queries when they fit the task.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.\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 previous period and sample data.\n- Apply various aggregation types, like sum, average, etc., and chart types.\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# Input shape\n\nSend the query fields as the call arguments, at the top level. Do not wrap them in a `query`, `source`, or `events` object: this tool takes no such parameter, and a wrapped payload is rejected for a missing `series`.\n\n`series` is the only required field. Every other field is optional.\n\n## One series\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\" }],\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n## Two series\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"dau\" }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\nCRITICAL: Be minimalist. Only include filters, breakdowns, 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- `properties` is a flat list of filters, combined with AND. There is no group object and no OR operator here.\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# Trends guidelines\n\nTrends insights enable users to plot data from people, events, and properties however they want. They're useful for finding patterns in data, as well as monitoring product usage. Users can use multiple independent series in a single query to see trends. They can also use a formula to calculate a metric. Each series has its own set of property filters. Trends insights do not require breakdowns or filters by default.\n\n## Aggregation\n\nDetermine the math aggregation the user is asking for, such as totals, averages, ratios, or custom formulas. If not specified, choose a reasonable default based on the event type (e.g., total count). By default, the total count should be used. You can aggregate data by events, event's property values, groups, or users. If you're aggregating by users or groups, there's no need to check for their existence.\n\nAvailable math aggregation types for the event count are:\n\n- total count\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n- unique users\n- unique sessions\n- weekly active users\n- daily active users\n- first time for a user\n- unique groups (requires `math_group_type_index` to be set to the group type index from the group mapping)\n\nAvailable math aggregation types for event's property values are:\n\n- average\n- sum\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nAvailable math aggregation types counting number of events completed per user (intensity of usage) are:\n\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nExamples of using aggregation types:\n\n- `unique users` to find how many distinct users have logged the event per a day.\n- `average` by the `$session_duration` property to find out what was the average session duration of an event.\n- `99th percentile by users` to find out what was the 99th percentile of the event count by users.\n\n## Combining multiple events into a single series (`GroupNode`)\n\n**Use a `GroupNode`** when the user says \"X OR Y\" (or \"any of these events\") and wants **one line / one number** as the result. Different filters per event are fine — put them on the inner nodes. Use separate top-level series instead when the user wants the events compared side by side. Only `OR` is supported.\n\n**Where things live:**\n\n- On the group: `math` / `math_property` / `math_property_type` / `math_multiplier` / `math_group_type_index` / `math_hogql`, plus `name`. The engine reads aggregation from here.\n- On each inner node: `event` (or action `id`), `properties`, `name` — all respected normally; `properties` applies only to that node. Mirror the group's `math*` values on each inner node for UI round-trip, but they're ignored at execution time.\n\n### Example — different filter per event\n\n\"Pageviews on Safari OR pageleaves on Chrome, as one line.\" Each inner node carries its own `properties`; the group ORs them and aggregates as one series.\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"GroupNode\",\n \"operator\": \"OR\",\n \"name\": \"Pageviews on Safari, Pageleaves on Chrome\",\n \"math\": \"total\",\n \"nodes\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"name\": \"Pageview\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Safari\"] }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageleave\",\n \"name\": \"Pageleave\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n }\n ]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\n## Math formulas\n\nIf the math aggregation is more complex or not listed above, use custom formulas to perform mathematical operations like calculating percentages or metrics. If you use a formula, you should use the following syntax: `A/B`, where `A` and `B` are the names of the series. You can combine math aggregations and formulas.\n\nWhen using a formula, you should:\n\n- Identify and specify **all** events and actions needed to solve the formula.\n- Carefully review the list of available events and actions to find appropriate entities for each part of the formula.\n- Ensure that you find events and actions corresponding to both the numerator and denominator in ratio calculations.\n\nExamples of using math formulas:\n\n- If you want to calculate the percentage of users who have completed onboarding, you need to find and use events or actions similar to `$identify` and `onboarding complete`, so the formula will be `A / B * 100`, where `A` is `onboarding complete` (unique users) and `B` is `$identify` (unique users).\n- To calculate conversion rate: `A / B * 100` where A is conversions and B is total events.\n- To calculate average value: `A / B` where A is sum of property and B is count.\n\n## Time interval\n\nSpecify the time interval (group by time) using the `interval` field. Available intervals are: `hour`, `day`, `week`, `month`.\nUnless the user has specified otherwise, use the following default interval:\n\n- If the time period is less than two days, use the `hour` interval.\n- If the time period is less than a month, use the `day` interval.\n- If the time period is less than three months, use the `week` interval.\n- Otherwise, use the `month` interval.\n\n## Breakdowns\n\nBreakdowns are used to segment data by property values of maximum three properties. They divide all defined trends series into multiple subseries based on the values of the property. Include breakdowns **only when they are essential to directly answer the user's question**. You should not add breakdowns if the question can be addressed without additional segmentation. Always use the minimum set of breakdowns needed.\n\nWhen using breakdowns, you should:\n\n- **Identify the property group** and name for each breakdown.\n- **Provide the property name** for each breakdown.\n- **Validate that the property value accurately reflects the intended criteria**.\n\nExamples of using breakdowns:\n\n- page views trend by country: you need to find a property such as `$geoip_country_code` and set it as a breakdown.\n- number of users who have completed onboarding by an organization: you need to find a property such as `organization name` and set it as a breakdown.\n\n# Examples\n\n## How many signups were there in the last 30 days?\n\nA period summary gets the `Metric` display: the headline plus how it moved against the previous period. Use a line chart instead when the question asks about change over time or a cadence.\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": { \"display\": \"Metric\" }\n}\n```\n\n## Page views by referring domain for the last month\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"breakdownFilter\": {\n \"breakdowns\": [{ \"property\": \"$referring_domain\", \"type\": \"event\" }]\n }\n}\n```\n\n## DAU to MAU ratio for users from the US, compared to the previous period\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"monthly_active\" }\n ],\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$geoip_country_name\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"United States\"] }],\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": {\n \"display\": \"ActionsLineGraph\",\n \"formulaNodes\": [{ \"formula\": \"A/B\" }],\n \"aggregationAxisFormat\": \"percentage_scaled\"\n }\n}\n```\n\n## Unique users and first-time users for \"insight created\" over the last 12 months\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"first_time_for_user\" }\n ],\n \"dateRange\": { \"date_from\": \"-12m\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\n}\n```\n\n## P99, P95, and median of a \"refreshAge\" property on \"viewed dashboard\" events\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p99\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p95\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"median\", \"math_property\": \"refreshAge\" }\n ],\n \"dateRange\": { \"date_from\": \"yStart\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\", \"aggregationAxisFormat\": \"duration\" }\n}\n```\n\n## Organizations that signed up from Google in the last 30 days (group aggregation)\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"user signed up\",\n \"math\": \"unique_group\",\n \"math_group_type_index\": 0,\n \"properties\": [{ \"key\": \"is_organization_first_user\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"true\"] }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$initial_utm_source\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"google\"] }],\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\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.\n- When using group aggregations (unique groups), always set `math_group_type_index` to the appropriate group type index from the group mapping.\n- Visualization settings (display type, axis format, etc.) should only be specified when explicitly requested or when they significantly improve the answer. For a period summary or an explicit current-versus-previous-period comparison, set `trendsFilter.display` to `Metric` and `compareFilter.compare` to `true`. Keep `ActionsLineGraph` for change over time, a cadence, or a pattern. Use `BoldNumber` only when a trend is meaningless.",+ "description": "Run a trends query to analyze metrics over time. Trends insights visualize events over time using time series. They're useful for finding patterns in historical data.\n\nUse this tool for native trends with supported aggregations, series, breakdowns, formulas, and period comparisons. Use `execute-sql` for record inspection or custom SQL calculations. When both tools preserve the requested calculation and output, prefer this tool for a new query, including simple aggregates. Keep valid existing queries when they fit the task.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.\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 previous period and sample data.\n- Apply various aggregation types, like sum, average, etc., and chart types.\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# Input shape\n\nSend the query fields as the call arguments, at the top level. Do not wrap them in a `query`, `source`, or `events` object: this tool takes no such parameter.\n\n`series` is the only required field. Every other field is optional.\n\n## One series\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\" }],\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n## Two series\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"dau\" }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\nCRITICAL: Be minimalist. Only include filters, breakdowns, 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- `properties` is a flat list of filters, combined with AND. There is no group object and no OR operator here.\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# Trends guidelines\n\nTrends insights enable users to plot data from people, events, and properties however they want. They're useful for finding patterns in data, as well as monitoring product usage. Users can use multiple independent series in a single query to see trends. They can also use a formula to calculate a metric. Each series has its own set of property filters. Trends insights do not require breakdowns or filters by default.\n\n## Aggregation\n\nDetermine the math aggregation the user is asking for, such as totals, averages, ratios, or custom formulas. If not specified, choose a reasonable default based on the event type (e.g., total count). By default, the total count should be used. You can aggregate data by events, event's property values, groups, or users. If you're aggregating by users or groups, there's no need to check for their existence.\n\nAvailable math aggregation types for the event count are:\n\n- total count\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n- unique users\n- unique sessions\n- weekly active users\n- daily active users\n- first time for a user\n- unique groups (requires `math_group_type_index` to be set to the group type index from the group mapping)\n\nAvailable math aggregation types for event's property values are:\n\n- average\n- sum\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nAvailable math aggregation types counting number of events completed per user (intensity of usage) are:\n\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nExamples of using aggregation types:\n\n- `unique users` to find how many distinct users have logged the event per a day.\n- `average` by the `$session_duration` property to find out what was the average session duration of an event.\n- `99th percentile by users` to find out what was the 99th percentile of the event count by users.\n\n## Combining multiple events into a single series (`GroupNode`)\n\n**Use a `GroupNode`** when the user says \"X OR Y\" (or \"any of these events\") and wants **one line / one number** as the result. Different filters per event are fine — put them on the inner nodes. Use separate top-level series instead when the user wants the events compared side by side. Only `OR` is supported.\n\n**Where things live:**\n\n- On the group: `math` / `math_property` / `math_property_type` / `math_multiplier` / `math_group_type_index` / `math_hogql`, plus `name`. The engine reads aggregation from here.\n- On each inner node: `event` (or action `id`), `properties`, `name` — all respected normally; `properties` applies only to that node. Mirror the group's `math*` values on each inner node for UI round-trip, but they're ignored at execution time.\n\n### Example — different filter per event\n\n\"Pageviews on Safari OR pageleaves on Chrome, as one line.\" Each inner node carries its own `properties`; the group ORs them and aggregates as one series.\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"GroupNode\",\n \"operator\": \"OR\",\n \"name\": \"Pageviews on Safari, Pageleaves on Chrome\",\n \"math\": \"total\",\n \"nodes\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"name\": \"Pageview\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Safari\"] }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageleave\",\n \"name\": \"Pageleave\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n }\n ]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\n## Math formulas\n\nIf the math aggregation is more complex or not listed above, use custom formulas to perform mathematical operations like calculating percentages or metrics. If you use a formula, you should use the following syntax: `A/B`, where `A` and `B` are the names of the series. You can combine math aggregations and formulas.\n\nWhen using a formula, you should:\n\n- Identify and specify **all** events and actions needed to solve the formula.\n- Carefully review the list of available events and actions to find appropriate entities for each part of the formula.\n- Ensure that you find events and actions corresponding to both the numerator and denominator in ratio calculations.\n\nExamples of using math formulas:\n\n- If you want to calculate the percentage of users who have completed onboarding, you need to find and use events or actions similar to `$identify` and `onboarding complete`, so the formula will be `A / B * 100`, where `A` is `onboarding complete` (unique users) and `B` is `$identify` (unique users).\n- To calculate conversion rate: `A / B * 100` where A is conversions and B is total events.\n- To calculate average value: `A / B` where A is sum of property and B is count.\n\n## Time interval\n\nSpecify the time interval (group by time) using the `interval` field. Available intervals are: `hour`, `day`, `week`, `month`.\nUnless the user has specified otherwise, use the following default interval:\n\n- If the time period is less than two days, use the `hour` interval.\n- If the time period is less than a month, use the `day` interval.\n- If the time period is less than three months, use the `week` interval.\n- Otherwise, use the `month` interval.\n\n## Breakdowns\n\nBreakdowns are used to segment data by property values of maximum three properties. They divide all defined trends series into multiple subseries based on the values of the property. Include breakdowns **only when they are essential to directly answer the user's question**. You should not add breakdowns if the question can be addressed without additional segmentation. Always use the minimum set of breakdowns needed.\n\nWhen using breakdowns, you should:\n\n- **Identify the property group** and name for each breakdown.\n- **Provide the property name** for each breakdown.\n- **Validate that the property value accurately reflects the intended criteria**.\n\nExamples of using breakdowns:\n\n- page views trend by country: you need to find a property such as `$geoip_country_code` and set it as a breakdown.\n- number of users who have completed onboarding by an organization: you need to find a property such as `organization name` and set it as a breakdown.\n\n# Examples\n\n## How many signups were there in the last 30 days?\n\nA period summary gets the `Metric` display: the headline plus how it moved against the previous period. Use a line chart instead when the question asks about change over time or a cadence.\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": { \"display\": \"Metric\" }\n}\n```\n\n## Page views by referring domain for the last month\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"breakdownFilter\": {\n \"breakdowns\": [{ \"property\": \"$referring_domain\", \"type\": \"event\" }]\n }\n}\n```\n\n## DAU to MAU ratio for users from the US, compared to the previous period\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"monthly_active\" }\n ],\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$geoip_country_name\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"United States\"] }],\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": {\n \"display\": \"ActionsLineGraph\",\n \"formulaNodes\": [{ \"formula\": \"A/B\" }],\n \"aggregationAxisFormat\": \"percentage_scaled\"\n }\n}\n```\n\n## Unique users and first-time users for \"insight created\" over the last 12 months\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"first_time_for_user\" }\n ],\n \"dateRange\": { \"date_from\": \"-12m\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\n}\n```\n\n## P99, P95, and median of a \"refreshAge\" property on \"viewed dashboard\" events\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p99\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p95\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"median\", \"math_property\": \"refreshAge\" }\n ],\n \"dateRange\": { \"date_from\": \"yStart\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\", \"aggregationAxisFormat\": \"duration\" }\n}\n```\n\n## Organizations that signed up from Google in the last 30 days (group aggregation)\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"user signed up\",\n \"math\": \"unique_group\",\n \"math_group_type_index\": 0,\n \"properties\": [{ \"key\": \"is_organization_first_user\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"true\"] }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$initial_utm_source\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"google\"] }],\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\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.\n- When using group aggregations (unique groups), always set `math_group_type_index` to the appropriate group type index from the group mapping.\n- Visualization settings (display type, axis format, etc.) should only be specified when explicitly requested or when they significantly improve the answer. For a period summary or an explicit current-versus-previous-period comparison, set `trendsFilter.display` to `Metric` and `compareFilter.compare` to `true`. Keep `ActionsLineGraph` for change over time, a cadence, or a pattern. Use `BoldNumber` only when a trend is meaningless.","category": "Query wrappers","feature": "insights","summary": "Run a trends query",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 480fca445099..cbd2dd8deca9 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -10374,7 +10374,7 @@"system_prompt_hint": "List persons who were active in a given number of intervals (one stickiness bar)"},"query-trends": {- "description": "Run a trends query to analyze metrics over time. Trends insights visualize events over time using time series. They're useful for finding patterns in historical data.\n\nUse this tool for native trends with supported aggregations, series, breakdowns, formulas, and period comparisons. Use `execute-sql` for record inspection or custom SQL calculations. When both tools preserve the requested calculation and output, prefer this tool for a new query, including simple aggregates. Keep valid existing queries when they fit the task.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.\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 previous period and sample data.\n- Apply various aggregation types, like sum, average, etc., and chart types.\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# Input shape\n\nSend the query fields as the call arguments, at the top level. Do not wrap them in a `query`, `source`, or `events` object: this tool takes no such parameter, and a wrapped payload is rejected for a missing `series`.\n\n`series` is the only required field. Every other field is optional.\n\n## One series\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\" }],\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n## Two series\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"dau\" }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\nCRITICAL: Be minimalist. Only include filters, breakdowns, 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- `properties` is a flat list of filters, combined with AND. There is no group object and no OR operator here.\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# Trends guidelines\n\nTrends insights enable users to plot data from people, events, and properties however they want. They're useful for finding patterns in data, as well as monitoring product usage. Users can use multiple independent series in a single query to see trends. They can also use a formula to calculate a metric. Each series has its own set of property filters. Trends insights do not require breakdowns or filters by default.\n\n## Aggregation\n\nDetermine the math aggregation the user is asking for, such as totals, averages, ratios, or custom formulas. If not specified, choose a reasonable default based on the event type (e.g., total count). By default, the total count should be used. You can aggregate data by events, event's property values, groups, or users. If you're aggregating by users or groups, there's no need to check for their existence.\n\nAvailable math aggregation types for the event count are:\n\n- total count\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n- unique users\n- unique sessions\n- weekly active users\n- daily active users\n- first time for a user\n- unique groups (requires `math_group_type_index` to be set to the group type index from the group mapping)\n\nAvailable math aggregation types for event's property values are:\n\n- average\n- sum\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nAvailable math aggregation types counting number of events completed per user (intensity of usage) are:\n\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nExamples of using aggregation types:\n\n- `unique users` to find how many distinct users have logged the event per a day.\n- `average` by the `$session_duration` property to find out what was the average session duration of an event.\n- `99th percentile by users` to find out what was the 99th percentile of the event count by users.\n\n## Combining multiple events into a single series (`GroupNode`)\n\n**Use a `GroupNode`** when the user says \"X OR Y\" (or \"any of these events\") and wants **one line / one number** as the result. Different filters per event are fine — put them on the inner nodes. Use separate top-level series instead when the user wants the events compared side by side. Only `OR` is supported.\n\n**Where things live:**\n\n- On the group: `math` / `math_property` / `math_property_type` / `math_multiplier` / `math_group_type_index` / `math_hogql`, plus `name`. The engine reads aggregation from here.\n- On each inner node: `event` (or action `id`), `properties`, `name` — all respected normally; `properties` applies only to that node. Mirror the group's `math*` values on each inner node for UI round-trip, but they're ignored at execution time.\n\n### Example — different filter per event\n\n\"Pageviews on Safari OR pageleaves on Chrome, as one line.\" Each inner node carries its own `properties`; the group ORs them and aggregates as one series.\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"GroupNode\",\n \"operator\": \"OR\",\n \"name\": \"Pageviews on Safari, Pageleaves on Chrome\",\n \"math\": \"total\",\n \"nodes\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"name\": \"Pageview\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Safari\"] }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageleave\",\n \"name\": \"Pageleave\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n }\n ]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\n## Math formulas\n\nIf the math aggregation is more complex or not listed above, use custom formulas to perform mathematical operations like calculating percentages or metrics. If you use a formula, you should use the following syntax: `A/B`, where `A` and `B` are the names of the series. You can combine math aggregations and formulas.\n\nWhen using a formula, you should:\n\n- Identify and specify **all** events and actions needed to solve the formula.\n- Carefully review the list of available events and actions to find appropriate entities for each part of the formula.\n- Ensure that you find events and actions corresponding to both the numerator and denominator in ratio calculations.\n\nExamples of using math formulas:\n\n- If you want to calculate the percentage of users who have completed onboarding, you need to find and use events or actions similar to `$identify` and `onboarding complete`, so the formula will be `A / B * 100`, where `A` is `onboarding complete` (unique users) and `B` is `$identify` (unique users).\n- To calculate conversion rate: `A / B * 100` where A is conversions and B is total events.\n- To calculate average value: `A / B` where A is sum of property and B is count.\n\n## Time interval\n\nSpecify the time interval (group by time) using the `interval` field. Available intervals are: `hour`, `day`, `week`, `month`.\nUnless the user has specified otherwise, use the following default interval:\n\n- If the time period is less than two days, use the `hour` interval.\n- If the time period is less than a month, use the `day` interval.\n- If the time period is less than three months, use the `week` interval.\n- Otherwise, use the `month` interval.\n\n## Breakdowns\n\nBreakdowns are used to segment data by property values of maximum three properties. They divide all defined trends series into multiple subseries based on the values of the property. Include breakdowns **only when they are essential to directly answer the user's question**. You should not add breakdowns if the question can be addressed without additional segmentation. Always use the minimum set of breakdowns needed.\n\nWhen using breakdowns, you should:\n\n- **Identify the property group** and name for each breakdown.\n- **Provide the property name** for each breakdown.\n- **Validate that the property value accurately reflects the intended criteria**.\n\nExamples of using breakdowns:\n\n- page views trend by country: you need to find a property such as `$geoip_country_code` and set it as a breakdown.\n- number of users who have completed onboarding by an organization: you need to find a property such as `organization name` and set it as a breakdown.\n\n# Examples\n\n## How many signups were there in the last 30 days?\n\nA period summary gets the `Metric` display: the headline plus how it moved against the previous period. Use a line chart instead when the question asks about change over time or a cadence.\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": { \"display\": \"Metric\" }\n}\n```\n\n## Page views by referring domain for the last month\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"breakdownFilter\": {\n \"breakdowns\": [{ \"property\": \"$referring_domain\", \"type\": \"event\" }]\n }\n}\n```\n\n## DAU to MAU ratio for users from the US, compared to the previous period\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"monthly_active\" }\n ],\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$geoip_country_name\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"United States\"] }],\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": {\n \"display\": \"ActionsLineGraph\",\n \"formulaNodes\": [{ \"formula\": \"A/B\" }],\n \"aggregationAxisFormat\": \"percentage_scaled\"\n }\n}\n```\n\n## Unique users and first-time users for \"insight created\" over the last 12 months\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"first_time_for_user\" }\n ],\n \"dateRange\": { \"date_from\": \"-12m\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\n}\n```\n\n## P99, P95, and median of a \"refreshAge\" property on \"viewed dashboard\" events\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p99\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p95\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"median\", \"math_property\": \"refreshAge\" }\n ],\n \"dateRange\": { \"date_from\": \"yStart\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\", \"aggregationAxisFormat\": \"duration\" }\n}\n```\n\n## Organizations that signed up from Google in the last 30 days (group aggregation)\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"user signed up\",\n \"math\": \"unique_group\",\n \"math_group_type_index\": 0,\n \"properties\": [{ \"key\": \"is_organization_first_user\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"true\"] }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$initial_utm_source\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"google\"] }],\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\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.\n- When using group aggregations (unique groups), always set `math_group_type_index` to the appropriate group type index from the group mapping.\n- Visualization settings (display type, axis format, etc.) should only be specified when explicitly requested or when they significantly improve the answer. For a period summary or an explicit current-versus-previous-period comparison, set `trendsFilter.display` to `Metric` and `compareFilter.compare` to `true`. Keep `ActionsLineGraph` for change over time, a cadence, or a pattern. Use `BoldNumber` only when a trend is meaningless.",+ "description": "Run a trends query to analyze metrics over time. Trends insights visualize events over time using time series. They're useful for finding patterns in historical data.\n\nUse this tool for native trends with supported aggregations, series, breakdowns, formulas, and period comparisons. Use `execute-sql` for record inspection or custom SQL calculations. When both tools preserve the requested calculation and output, prefer this tool for a new query, including simple aggregates. Keep valid existing queries when they fit the task.\n\nUse 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.\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 previous period and sample data.\n- Apply various aggregation types, like sum, average, etc., and chart types.\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# Input shape\n\nSend the query fields as the call arguments, at the top level. Do not wrap them in a `query`, `source`, or `events` object: this tool takes no such parameter.\n\n`series` is the only required field. Every other field is optional.\n\n## One series\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\" }],\n \"dateRange\": { \"date_from\": \"-7d\" }\n}\n```\n\n## Two series\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"dau\" }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\nCRITICAL: Be minimalist. Only include filters, breakdowns, 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- `properties` is a flat list of filters, combined with AND. There is no group object and no OR operator here.\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# Trends guidelines\n\nTrends insights enable users to plot data from people, events, and properties however they want. They're useful for finding patterns in data, as well as monitoring product usage. Users can use multiple independent series in a single query to see trends. They can also use a formula to calculate a metric. Each series has its own set of property filters. Trends insights do not require breakdowns or filters by default.\n\n## Aggregation\n\nDetermine the math aggregation the user is asking for, such as totals, averages, ratios, or custom formulas. If not specified, choose a reasonable default based on the event type (e.g., total count). By default, the total count should be used. You can aggregate data by events, event's property values, groups, or users. If you're aggregating by users or groups, there's no need to check for their existence.\n\nAvailable math aggregation types for the event count are:\n\n- total count\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n- unique users\n- unique sessions\n- weekly active users\n- daily active users\n- first time for a user\n- unique groups (requires `math_group_type_index` to be set to the group type index from the group mapping)\n\nAvailable math aggregation types for event's property values are:\n\n- average\n- sum\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nAvailable math aggregation types counting number of events completed per user (intensity of usage) are:\n\n- average\n- minimum\n- maximum\n- median\n- 90th percentile\n- 95th percentile\n- 99th percentile\n\nExamples of using aggregation types:\n\n- `unique users` to find how many distinct users have logged the event per a day.\n- `average` by the `$session_duration` property to find out what was the average session duration of an event.\n- `99th percentile by users` to find out what was the 99th percentile of the event count by users.\n\n## Combining multiple events into a single series (`GroupNode`)\n\n**Use a `GroupNode`** when the user says \"X OR Y\" (or \"any of these events\") and wants **one line / one number** as the result. Different filters per event are fine — put them on the inner nodes. Use separate top-level series instead when the user wants the events compared side by side. Only `OR` is supported.\n\n**Where things live:**\n\n- On the group: `math` / `math_property` / `math_property_type` / `math_multiplier` / `math_group_type_index` / `math_hogql`, plus `name`. The engine reads aggregation from here.\n- On each inner node: `event` (or action `id`), `properties`, `name` — all respected normally; `properties` applies only to that node. Mirror the group's `math*` values on each inner node for UI round-trip, but they're ignored at execution time.\n\n### Example — different filter per event\n\n\"Pageviews on Safari OR pageleaves on Chrome, as one line.\" Each inner node carries its own `properties`; the group ORs them and aggregates as one series.\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"GroupNode\",\n \"operator\": \"OR\",\n \"name\": \"Pageviews on Safari, Pageleaves on Chrome\",\n \"math\": \"total\",\n \"nodes\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageview\",\n \"name\": \"Pageview\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Safari\"] }]\n },\n {\n \"kind\": \"EventsNode\",\n \"event\": \"$pageleave\",\n \"name\": \"Pageleave\",\n \"math\": \"total\",\n \"properties\": [{ \"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Chrome\"] }]\n }\n ]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\"\n}\n```\n\n## Math formulas\n\nIf the math aggregation is more complex or not listed above, use custom formulas to perform mathematical operations like calculating percentages or metrics. If you use a formula, you should use the following syntax: `A/B`, where `A` and `B` are the names of the series. You can combine math aggregations and formulas.\n\nWhen using a formula, you should:\n\n- Identify and specify **all** events and actions needed to solve the formula.\n- Carefully review the list of available events and actions to find appropriate entities for each part of the formula.\n- Ensure that you find events and actions corresponding to both the numerator and denominator in ratio calculations.\n\nExamples of using math formulas:\n\n- If you want to calculate the percentage of users who have completed onboarding, you need to find and use events or actions similar to `$identify` and `onboarding complete`, so the formula will be `A / B * 100`, where `A` is `onboarding complete` (unique users) and `B` is `$identify` (unique users).\n- To calculate conversion rate: `A / B * 100` where A is conversions and B is total events.\n- To calculate average value: `A / B` where A is sum of property and B is count.\n\n## Time interval\n\nSpecify the time interval (group by time) using the `interval` field. Available intervals are: `hour`, `day`, `week`, `month`.\nUnless the user has specified otherwise, use the following default interval:\n\n- If the time period is less than two days, use the `hour` interval.\n- If the time period is less than a month, use the `day` interval.\n- If the time period is less than three months, use the `week` interval.\n- Otherwise, use the `month` interval.\n\n## Breakdowns\n\nBreakdowns are used to segment data by property values of maximum three properties. They divide all defined trends series into multiple subseries based on the values of the property. Include breakdowns **only when they are essential to directly answer the user's question**. You should not add breakdowns if the question can be addressed without additional segmentation. Always use the minimum set of breakdowns needed.\n\nWhen using breakdowns, you should:\n\n- **Identify the property group** and name for each breakdown.\n- **Provide the property name** for each breakdown.\n- **Validate that the property value accurately reflects the intended criteria**.\n\nExamples of using breakdowns:\n\n- page views trend by country: you need to find a property such as `$geoip_country_code` and set it as a breakdown.\n- number of users who have completed onboarding by an organization: you need to find a property such as `organization name` and set it as a breakdown.\n\n# Examples\n\n## How many signups were there in the last 30 days?\n\nA period summary gets the `Metric` display: the headline plus how it moved against the previous period. Use a line chart instead when the question asks about change over time or a cadence.\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"user signed up\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": { \"display\": \"Metric\" }\n}\n```\n\n## Page views by referring domain for the last month\n\n```json\n{\n \"series\": [{ \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"total\" }],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"breakdownFilter\": {\n \"breakdowns\": [{ \"property\": \"$referring_domain\", \"type\": \"event\" }]\n }\n}\n```\n\n## DAU to MAU ratio for users from the US, compared to the previous period\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"$pageview\", \"math\": \"monthly_active\" }\n ],\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$geoip_country_name\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"United States\"] }],\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": {\n \"display\": \"ActionsLineGraph\",\n \"formulaNodes\": [{ \"formula\": \"A/B\" }],\n \"aggregationAxisFormat\": \"percentage_scaled\"\n }\n}\n```\n\n## Unique users and first-time users for \"insight created\" over the last 12 months\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"dau\" },\n { \"kind\": \"EventsNode\", \"event\": \"insight created\", \"math\": \"first_time_for_user\" }\n ],\n \"dateRange\": { \"date_from\": \"-12m\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\n}\n```\n\n## P99, P95, and median of a \"refreshAge\" property on \"viewed dashboard\" events\n\n```json\n{\n \"series\": [\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p99\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"p95\", \"math_property\": \"refreshAge\" },\n { \"kind\": \"EventsNode\", \"event\": \"viewed dashboard\", \"math\": \"median\", \"math_property\": \"refreshAge\" }\n ],\n \"dateRange\": { \"date_from\": \"yStart\" },\n \"interval\": \"month\",\n \"filterTestAccounts\": true,\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\", \"aggregationAxisFormat\": \"duration\" }\n}\n```\n\n## Organizations that signed up from Google in the last 30 days (group aggregation)\n\n```json\n{\n \"series\": [\n {\n \"kind\": \"EventsNode\",\n \"event\": \"user signed up\",\n \"math\": \"unique_group\",\n \"math_group_type_index\": 0,\n \"properties\": [{ \"key\": \"is_organization_first_user\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"true\"] }]\n }\n ],\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"interval\": \"day\",\n \"properties\": [{ \"key\": \"$initial_utm_source\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"google\"] }],\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\" }\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.\n- When using group aggregations (unique groups), always set `math_group_type_index` to the appropriate group type index from the group mapping.\n- Visualization settings (display type, axis format, etc.) should only be specified when explicitly requested or when they significantly improve the answer. For a period summary or an explicit current-versus-previous-period comparison, set `trendsFilter.display` to `Metric` and `compareFilter.compare` to `true`. Keep `ActionsLineGraph` for change over time, a cadence, or a pattern. Use `BoldNumber` only when a trend is meaningless.","category": "Query wrappers","feature": "insights","summary": "Run a trends query",diff --git a/services/mcp/src/cli/index.ts b/services/mcp/src/cli/index.tsindex 77eedb0d981a..e544b4017dc9 100644--- a/services/mcp/src/cli/index.ts+++ b/services/mcp/src/cli/index.ts@@ -1,6 +1,6 @@#!/usr/bin/env nodeimport { AnalyticsEvent } from '@/lib/posthog/analytics'-import { createExecTool, formatInputValidationError, rewrapFlattenedArguments } from '@/tools/exec'+import { createExecTool, formatInputValidationError, repairArgumentNesting } from '@/tools/exec'import type { Context, Tool, ZodObjectAny } from '@/tools/types'import { buildAgentHelp } from './agent-help'@@ -147,7 +147,7 @@ async function runDryCall(args: string[]): Promise<void> {// The same rewrap the MCP paths apply, so a dry run reports what a real call would do.const firstPass = tool.schema.safeParse(parsed, { reportInput: true })- const rewrapped = firstPass.success ? undefined : rewrapFlattenedArguments(firstPass.error, parsed, tool.schema)+ const rewrapped = firstPass.success ? undefined : repairArgumentNesting(firstPass.error, parsed, tool.schema)const validation = rewrapped ? tool.schema.safeParse(rewrapped, { reportInput: true }) : firstPassprintResult({dryRun: true,diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 1fa4a58af711..ade2870ae2c6 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -32,7 +32,7 @@ import {markNoncanonicalMetricRun,parseExecCallInnerArgs,parseExecCallInnerToolName,- rewrapFlattenedArguments,+ repairArgumentNesting,type ExecCommandMeta,type ExecInnerCallTracker,} from '@/tools/exec'@@ -343,7 +343,7 @@ export class ToolExecutor {const firstPass = tool.schema.safeParse(rawToolArgs, { reportInput: true })const rewrapped = firstPass.success? undefined- : rewrapFlattenedArguments(firstPass.error, rawToolArgs, tool.schema)+ : repairArgumentNesting(firstPass.error, rawToolArgs, tool.schema)const toolArgs = rewrapped ?? rawToolArgsconst validation = rewrapped ? tool.schema.safeParse(toolArgs, { reportInput: true }) : firstPassif (!validation.success) {diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex f90a7aaa451b..eb64b8a0af42 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -829,6 +829,47 @@ export function rewrapFlattenedArguments(return schema.safeParse(rebuilt).success ? rebuilt : undefined}+/**+ * The mirror of `rewrapFlattenedArguments`: lifts a payload the caller nested under one+ * undeclared key, such as `{query: {series}}`, back to the top level the schema declares.+ *+ * A nested `query` object is the natural shape for a query tool, and callers keep sending+ * it even when the description says not to, so the rejection alone costs a round trip.+ *+ * Returns undefined when the wrapper or its siblings carry a key the schema does not+ * declare, because the parse would drop that key without a word, or when the lifted+ * payload does not parse.+ */+export function unwrapOverWrappedArguments(+ input: unknown,+ schema: ZodObjectAny | undefined+): Record<string, unknown> | undefined {+ const key = overWrappedPayloadKey(input, schema)+ if (!schema || !key || !isRecord(input)) {+ return undefined+ }+ const inner = input[key] as Record<string, unknown>+ const siblings = Object.fromEntries(Object.entries(input).filter(([name]) => name !== key))+ const declared = topLevelFieldNames(schema)+ if (Object.keys(siblings).some((name) => !declared.has(name))) {+ return undefined+ }+ if (Object.keys(inner).some((name) => !declared.has(name) || name in siblings)) {+ return undefined+ }+ const unwrapped = { ...siblings, ...inner }+ return schema.safeParse(unwrapped).success ? unwrapped : undefined+}++/** Repairs a call whose payload sits one level off from where the schema wants it, in either direction. */+export function repairArgumentNesting(+ error: z.ZodError,+ input: unknown,+ schema: ZodObjectAny | undefined+): Record<string, unknown> | undefined {+ return rewrapFlattenedArguments(error, input, schema) ?? unwrapOverWrappedArguments(input, schema)+}+function topLevelFieldNames(schema: ZodObjectAny): ReadonlySet<string> {const root = inputJsonSchema(schema)const properties = isRecord(root) ? root['properties'] : undefined@@ -1872,7 +1913,7 @@ export function createExecTool(// field. Dispatch the parsed output so coerced values and defaults apply.let validation = toolSchema.safeParse(input, { reportInput: true })if (!validation.success) {- const rewrapped = rewrapFlattenedArguments(validation.error, input, toolSchema)+ const rewrapped = repairArgumentNesting(validation.error, input, toolSchema)if (rewrapped) {input = rewrappedvalidation = toolSchema.safeParse(input, { reportInput: true })diff --git a/services/mcp/src/tools/posthogConnections/call.ts b/services/mcp/src/tools/posthogConnections/call.tsindex 5c912aa94e2b..afedb014a041 100644--- a/services/mcp/src/tools/posthogConnections/call.ts+++ b/services/mcp/src/tools/posthogConnections/call.ts@@ -2,7 +2,7 @@ import { z } from 'zod'import { buildForwardedContext, resolveConnectionTarget, seedForwardedContext } from '@/lib/connection-forwarding'import { ExecCommandError } from '@/lib/errors'-import { formatInputValidationError, rewrapFlattenedArguments } from '@/tools/exec'+import { formatInputValidationError, repairArgumentNesting } from '@/tools/exec'import { getToolDefinition } from '@/tools/toolDefinitions'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -101,7 +101,7 @@ export function createConnectionCallTool(const firstPass = target.schema.safeParse(rawArguments, { reportInput: true })const rewrapped = firstPass.success? undefined- : rewrapFlattenedArguments(firstPass.error, rawArguments, target.schema)+ : repairArgumentNesting(firstPass.error, rawArguments, target.schema)const parsedArguments = rewrapped ? target.schema.safeParse(rewrapped, { reportInput: true }) : firstPassif (!parsedArguments.success) {throw new ExecCommandError(diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 4768dac55b43..4f913529ba66 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -22,6 +22,7 @@ import { PostHogApiError } from '@/lib/errors'import { buildToolDomainsCompact } from '@/lib/instructions'import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'+import { GENERATED_TOOL_MAP } from '@/tools/generated'import { getToolDefinition } from '@/tools/toolDefinitions'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'@@ -739,6 +740,38 @@ describe('ToolExecutor', () => {})})+ describe('a query wrapper called with its payload nested under `query`', () => {+ let getToolByNameSpy: MockInstance | undefined++ afterEach(() => {+ getToolByNameSpy?.mockRestore()+ getToolByNameSpy = undefined+ })++ it('runs query-trends with the payload lifted to the top level', async () => {+ const received: unknown[] = []+ const { schema } = GENERATED_TOOL_MAP['query-trends']!()+ getToolByNameSpy = vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ build() {+ return this.base+ },+ base: {+ schema,+ handler: async (_context: unknown, params: unknown) => (received.push(params), { results: [] }),+ },+ } as any)+ const payload = { series: [{ kind: 'EventsNode', event: '$pageview' }], dateRange: { date_from: '-7d' } }++ const result = (await executor.handleToolCall(+ { name: 'query-trends', arguments: { query: payload } },+ makeToolExecutorState([{ name: 'query-trends' }], { useSingleExec: false })+ )) as any++ expect(result.isError).toBeFalsy()+ expect(received).toEqual([schema.parse(payload)])+ })+ })+// A tools-mode client calls the metric-run tool directly, bypassing the exec// dispatcher that marks the result. Both paths have to agree, or whether an agent// is warned off an unapproved metric depends on the client it runs in.diff --git a/services/mcp/tests/unit/top-level-query-input-example.test.ts b/services/mcp/tests/unit/top-level-query-input-example.test.tsindex b3ebfbef14e9..54e37af2a1c3 100644--- a/services/mcp/tests/unit/top-level-query-input-example.test.ts+++ b/services/mcp/tests/unit/top-level-query-input-example.test.ts@@ -114,6 +114,31 @@ describe('tools that take their query fields at the top level', () => {}})+ it.each(TOP_LEVEL_QUERY_TOOLS)(+ '%s runs its documented example nested under `query` through the exec CLI',+ async (name) => {+ // Callers keep sending the natural `{query: {...}}` shape whatever the description+ // says, so the executor lifts it to the top level instead of rejecting it.+ const received: unknown[] = []+ const tool = asExecutableTool(name, GENERATED_TOOL_MAP[name]!())+ const exec = createExecTool(+ [{ ...tool, handler: async (_context, params) => (received.push(params), { results: [] }) }],+ mockContext,+ 'test description',+ 'test command reference',+ undefined+ )+ const example = jsonExamples(definitions[name]?.description ?? '')[0] as Record<string, unknown>++ const output = await exec.handler(mockContext, {+ command: `call ${name} ${JSON.stringify({ query: example })}`,+ })++ expect(String(output)).not.toContain('Invalid input')+ expect(received).toEqual([tool.schema.parse(example)])+ }+ )+// Parsing alone does not prove an example works: these schemas drop fields// they do not declare, so an example naming one is accepted and then quietly// loses it. Scoped to trends — `query-funnel` documents `name` on a grouped