Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp): make query-trends guidance match the input it accepts (#96459)

posthog[bot]9361f5f3f9d7
diff --git a/services/mcp/definitions/prompts/query-trends.md b/services/mcp/definitions/prompts/query-trends.md
index aa82bf7ad4de..36a94c462034 100644
--- a/services/mcp/definitions/prompts/query-trends.md
+++ b/services/mcp/definitions/prompts/query-trends.md
@@ -18,6 +18,34 @@ Examples of use cases include:
- How the properties of events vary using aggregation (sum, average, etc).
- Users can also visualize the same data points in a variety of ways.
+# 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`.
+
+`series` is the only required field. Every other field is optional.
+
+## One series
+
+```json
+{
+ "series": [{ "kind": "EventsNode", "event": "$pageview" }],
+ "dateRange": { "date_from": "-7d" }
+}
+```
+
+## Two series
+
+```json
+{
+ "series": [
+ { "kind": "EventsNode", "event": "$pageview", "math": "dau" },
+ { "kind": "EventsNode", "event": "user signed up", "math": "dau" }
+ ],
+ "dateRange": { "date_from": "-30d" },
+ "interval": "day"
+}
+```
+
CRITICAL: 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.
# Data narrowing
@@ -35,7 +63,7 @@ When using a property filter, you should:
- After selecting a property, **validate that the property value accurately reflects the intended criteria**.
- **Find the suitable operator for type** (e.g., `contains`, `is set`).
- If the operator requires a value, use the `read-data-schema` tool to find the property values.
-- You set logical operators to combine multiple properties of a single series: AND or OR.
+- `properties` is a flat list of filters, combined with AND. There is no group object and no OR operator here.
Infer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.
@@ -148,7 +176,6 @@ Examples of using aggregation types:
```json
{
- "kind": "TrendsQuery",
"series": [
{
"kind": "GroupNode",
@@ -227,7 +254,6 @@ A period summary gets the `Metric` display: the headline plus how it moved again
```json
{
- "kind": "TrendsQuery",
"series": [{ "kind": "EventsNode", "event": "user signed up", "math": "total" }],
"dateRange": { "date_from": "-30d" },
"interval": "day",
@@ -240,7 +266,6 @@ A period summary gets the `Metric` display: the headline plus how it moved again
```json
{
- "kind": "TrendsQuery",
"series": [{ "kind": "EventsNode", "event": "$pageview", "math": "total" }],
"dateRange": { "date_from": "-30d" },
"interval": "day",
@@ -254,24 +279,19 @@ A period summary gets the `Metric` display: the headline plus how it moved again
```json
{
- "kind": "TrendsQuery",
"series": [
{ "kind": "EventsNode", "event": "$pageview", "math": "dau" },
{ "kind": "EventsNode", "event": "$pageview", "math": "monthly_active" }
],
"dateRange": { "date_from": "-7d" },
"interval": "day",
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [{ "key": "$geoip_country_name", "operator": "exact", "type": "event", "value": ["United States"] }]
- }
- ]
- },
+ "properties": [{ "key": "$geoip_country_name", "operator": "exact", "type": "event", "value": ["United States"] }],
"compareFilter": { "compare": true },
- "trendsFilter": { "display": "ActionsLineGraph", "formula": "A/B", "aggregationAxisFormat": "percentage_scaled" }
+ "trendsFilter": {
+ "display": "ActionsLineGraph",
+ "formulaNodes": [{ "formula": "A/B" }],
+ "aggregationAxisFormat": "percentage_scaled"
+ }
}
```
@@ -279,7 +299,6 @@ A period summary gets the `Metric` display: the headline plus how it moved again
```json
{
- "kind": "TrendsQuery",
"series": [
{ "kind": "EventsNode", "event": "insight created", "math": "dau" },
{ "kind": "EventsNode", "event": "insight created", "math": "first_time_for_user" }
@@ -295,7 +314,6 @@ A period summary gets the `Metric` display: the headline plus how it moved again
```json
{
- "kind": "TrendsQuery",
"series": [
{ "kind": "EventsNode", "event": "viewed dashboard", "math": "p99", "math_property": "refreshAge" },
{ "kind": "EventsNode", "event": "viewed dashboard", "math": "p95", "math_property": "refreshAge" },
@@ -312,7 +330,6 @@ A period summary gets the `Metric` display: the headline plus how it moved again
```json
{
- "kind": "TrendsQuery",
"series": [
{
"kind": "EventsNode",
@@ -324,15 +341,7 @@ A period summary gets the `Metric` display: the headline plus how it moved again
],
"dateRange": { "date_from": "-30d" },
"interval": "day",
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "OR",
- "values": [{ "key": "$initial_utm_source", "operator": "exact", "type": "person", "value": ["google"] }]
- }
- ]
- },
+ "properties": [{ "key": "$initial_utm_source", "operator": "exact", "type": "person", "value": ["google"] }],
"trendsFilter": { "display": "ActionsLineGraph" }
}
```
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index d75cd3c50866..90b8f04594d0 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9307,7 +9307,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 '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\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- 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# 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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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\": {\n \"type\": \"AND\",\n \"values\": [\n {\n \"type\": \"AND\",\n \"values\": [{ \"key\": \"$geoip_country_name\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"United States\"] }]\n }\n ]\n },\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\", \"formula\": \"A/B\", \"aggregationAxisFormat\": \"percentage_scaled\" }\n}\n```\n\n## Unique users and first-time users for \"insight created\" over the last 12 months\n\n```json\n{\n \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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\": {\n \"type\": \"AND\",\n \"values\": [\n {\n \"type\": \"OR\",\n \"values\": [{ \"key\": \"$initial_utm_source\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"google\"] }]\n }\n ]\n },\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 '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.",
"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.json
index 205af90e5aa2..f2b466a12ccd 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9865,7 +9865,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 '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\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- 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# 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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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\": {\n \"type\": \"AND\",\n \"values\": [\n {\n \"type\": \"AND\",\n \"values\": [{ \"key\": \"$geoip_country_name\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"United States\"] }]\n }\n ]\n },\n \"compareFilter\": { \"compare\": true },\n \"trendsFilter\": { \"display\": \"ActionsLineGraph\", \"formula\": \"A/B\", \"aggregationAxisFormat\": \"percentage_scaled\" }\n}\n```\n\n## Unique users and first-time users for \"insight created\" over the last 12 months\n\n```json\n{\n \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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 \"kind\": \"TrendsQuery\",\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\": {\n \"type\": \"AND\",\n \"values\": [\n {\n \"type\": \"OR\",\n \"values\": [{ \"key\": \"$initial_utm_source\", \"operator\": \"exact\", \"type\": \"person\", \"value\": [\"google\"] }]\n }\n ]\n },\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 '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.",
"category": "Query wrappers",
"feature": "insights",
"summary": "Run a trends query",
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index abeec631aec6..3c90ca6434ba 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -509,6 +509,58 @@ function looksLikeUnwrappedPayload(
return wrapped.error.issues.every((issue) => issue.path.length > 1 && String(issue.path[0]) === key)
}
+/** Bound on how many stray object keys the check tries, because each try costs a
+ * full parse of the tool's schema. A wrapped payload sits under a single key, so
+ * a call carrying more stray objects than this made a different mistake and falls
+ * through to the dropped-keys message. */
+const MAX_WRAPPER_CANDIDATES = 3
+
+/**
+ * The mirror of `looksLikeUnwrappedPayload`: the caller nested a whole valid
+ * payload under one key, for a tool that takes those fields at the top level.
+ * Zod strips the undeclared wrapper, so the rejection names a field the caller
+ * did send, one level down, and the caller has nothing to correct.
+ *
+ * Confident when the unwrapped value parses, or fails only on fields the wrapper
+ * holds, because both mean the schema read the contents.
+ */
+function overWrappedPayloadKey(input: unknown, schema: ZodObjectAny | undefined): string | undefined {
+ if (!schema || !isRecord(input)) {
+ return undefined
+ }
+ const declared = topLevelFieldNames(schema)
+ let tried = 0
+ for (const [key, value] of Object.entries(input)) {
+ if (declared.has(key) || !isRecord(value) || Object.keys(value).length === 0) {
+ continue
+ }
+ if (tried === MAX_WRAPPER_CANDIDATES) {
+ return undefined
+ }
+ tried += 1
+ const unwrapped = schema.safeParse(value)
+ if (unwrapped.success) {
+ return key
+ }
+ const readsTheContents = unwrapped.error.issues.every(
+ (issue) => issue.path.length > 0 && String(issue.path[0]) in value
+ )
+ if (readsTheContents) {
+ return key
+ }
+ }
+ return undefined
+}
+
+function acceptedTopLevelShape(nested: unknown, schema: ZodObjectAny | undefined): string {
+ if (!schema || !isRecord(nested)) {
+ return '{...}'
+ }
+ const declared = topLevelFieldNames(schema)
+ const named = Object.keys(nested).filter((name) => declared.has(name))
+ return named.length > 0 ? renderFieldShape(named) : '{...}'
+}
+
/**
* Rebuilds a flattened payload under the wrapper the schema wanted, so the call the caller meant runs.
*
@@ -595,6 +647,16 @@ function wrapperFieldNames(schema: ZodObjectAny, key: string): ReadonlySet<strin
return names
}
+/** An object shape written from field names alone, capped, with every value
+ * elided, so the message carries the tool's vocabulary and no caller input. */
+function renderFieldShape(names: readonly string[]): string {
+ const shown = names.slice(0, MAX_WRAPPER_KEYS_NAMED).map((name) => `"${name}": ...`)
+ if (names.length > MAX_WRAPPER_KEYS_NAMED) {
+ shown.push('...')
+ }
+ return `{${shown.join(', ')}}`
+}
+
function variantsOf(node: Record<string, unknown>): Record<string, unknown>[] {
return ['anyOf', 'oneOf', 'allOf']
.flatMap((keyword) => (Array.isArray(node[keyword]) ? (node[keyword] as unknown[]) : []))
@@ -624,11 +686,7 @@ function acceptedWrapperShape(key: string, input: unknown, schema: ZodObjectAny
if (named.length === 0) {
return `{"${key}": {...}}`
}
- const shown = named.slice(0, MAX_WRAPPER_KEYS_NAMED).map((name) => `"${name}": ...`)
- if (named.length > MAX_WRAPPER_KEYS_NAMED) {
- shown.push('...')
- }
- return `{"${key}": {${shown.join(', ')}}}`
+ return `{"${key}": ${renderFieldShape(named)}}`
}
/**
@@ -705,6 +763,180 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
+/** Bounds on how much of a union failure the message unpacks, so one bad array
+ * entry cannot inflate the message or the analytics error string.
+ *
+ * Four levels is what the deepest generated query schema needs: a property
+ * filter inside a grouped series sits under the series union, the group's
+ * `nodes` union, the filter union, and the generic filter's own union. A
+ * shallower cap leaves that filter with the bare `Invalid input` this unpacking
+ * exists to remove.
+ */
+const MAX_UNION_ISSUES_NAMED = 3
+const MAX_UNION_VALUES_NAMED = 10
+const MAX_UNION_DEPTH = 4
+
+/** The keys a branch rejects because the schema fixes their value, looking
+ * through a branch that is itself a union: a key one inner variant accepts stays
+ * reachable through that branch. */
+function rejectedValueKeys(branch: readonly z.core.$ZodIssue[], depth = 0): Set<string> {
+ const keys = new Set<string>()
+ for (const issue of branch) {
+ if (issue.code === 'invalid_value' && issue.path.length === 1) {
+ keys.add(String(issue.path[0]))
+ } else if (issue.code === 'invalid_union' && issue.path.length === 0 && depth < MAX_UNION_DEPTH) {
+ const nested = issue.errors.map((inner) => rejectedValueKeys(inner, depth + 1))
+ for (const key of nested[0] ?? []) {
+ if (nested.every((set) => set.has(key))) {
+ keys.add(key)
+ }
+ }
+ }
+ }
+ return keys
+}
+
+/** The keys a branch fixes to one value, so `{key: value}` picks it out of the
+ * union. A branch that is itself a union pins what all of its own variants pin —
+ * every variant of a group property filter pins `type` to `group`. */
+function pinnedValues(branch: readonly z.core.$ZodIssue[], depth = 0): Map<string, string> {
+ const pins = new Map<string, string>()
+ for (const issue of branch) {
+ if (issue.code === 'invalid_value' && issue.path.length === 1 && issue.values.length === 1) {
+ pins.set(String(issue.path[0]), String(issue.values[0]))
+ } else if (issue.code === 'invalid_union' && issue.path.length === 0 && depth < MAX_UNION_DEPTH) {
+ const nested = issue.errors.map((inner) => pinnedValues(inner, depth + 1))
+ for (const [key, value] of nested[0] ?? []) {
+ if (nested.every((map) => map.get(key) === value)) {
+ pins.set(key, value)
+ }
+ }
+ }
+ }
+ return pins
+}
+
+/**
+ * The key the union switches on, read across the branches: each variant fixes the
+ * discriminator to a different value, so one key pinned to several values is the
+ * signature of the key that selected between them.
+ *
+ * Derived across branches rather than taken from one, because a variant can fix a
+ * second key to a single value without that key selecting anything: a flag
+ * property filter pins `operator` to `flag_evaluates_to`, and a cohort filter pins
+ * `key` to `id`. Reading either as the selector drops the variant the caller meant
+ * and reports its `type` as the field to rewrite.
+ */
+function discriminatorKey(branches: readonly (readonly z.core.$ZodIssue[])[]): string | undefined {
+ const pinned = new Map<string, Set<string>>()
+ for (const branch of branches) {
+ for (const [key, value] of pinnedValues(branch)) {
+ const values = pinned.get(key) ?? new Set<string>()
+ values.add(value)
+ pinned.set(key, values)
+ }
+ }
+ let selector: string | undefined
+ let widest = 1
+ for (const [key, values] of pinned) {
+ if (values.size > widest) {
+ selector = key
+ widest = values.size
+ }
+ }
+ return selector
+}
+
+/**
+ * The union branch that best matches the input: the variant the caller named, or
+ * failing that the one that raised the fewest complaints.
+ *
+ * A series entry keyed `kind: "ActionsNode"` and missing `name` fails every
+ * branch with one complaint each, so the shortest list alone would pick
+ * `EventsNode` and advise rewriting the `kind` the caller meant.
+ */
+function bestUnionBranch(branches: readonly (readonly z.core.$ZodIssue[])[]): readonly z.core.$ZodIssue[] | undefined {
+ const populated = branches.filter((branch) => branch.length > 0)
+ const selector = discriminatorKey(populated)
+ // Once the selector is known, the caller's own value for it picks the
+ // variant. Where no key selects anything, keep the variants that pin nothing
+ // the caller contradicted, so a `breakdowns` entry still hears the whole type
+ // list its generic variant takes rather than the one its group variant pins.
+ const named =
+ selector === undefined
+ ? populated.filter((branch) => pinnedValues(branch).size === 0)
+ : populated.filter((branch) => !rejectedValueKeys(branch).has(selector))
+ let best: readonly z.core.$ZodIssue[] | undefined
+ for (const branch of named.length > 0 ? named : populated) {
+ if (best === undefined || branch.length < best.length) {
+ best = branch
+ }
+ }
+ return best
+}
+
+/** The accepted values, when every branch of a union rejects the same enum
+ * value because the options are split across several enums. */
+function unionValueOptions(branches: readonly (readonly z.core.$ZodIssue[])[]): string[] | undefined {
+ const values: string[] = []
+ for (const branch of branches) {
+ const issue = branch.length === 1 ? branch[0] : undefined
+ if (!issue || issue.code !== 'invalid_value' || issue.path.length > 0) {
+ return undefined
+ }
+ for (const value of issue.values) {
+ values.push(String(value))
+ }
+ }
+ return values.length > 0 ? [...new Set(values)] : undefined
+}
+
+/**
+ * Unpacks a union rejection into the field that actually failed.
+ *
+ * Zod reports a union miss as one `Invalid input` at the union itself, so a
+ * malformed series entry arrives as `parameter "series.0": Invalid input`, which
+ * names the entry but never the key to change. Descending into the
+ * closest-matching branch names the offending field instead.
+ *
+ * Reports field names and schema-declared values only, never caller input.
+ */
+function describeUnionIssue(
+ branches: readonly (readonly z.core.$ZodIssue[])[],
+ path: ReadonlyArray<PropertyKey>,
+ depth = 0
+): string | undefined {
+ if (depth >= MAX_UNION_DEPTH) {
+ return undefined
+ }
+ const name = path.map(String).join('.')
+ const options = unionValueOptions(branches)
+ if (options) {
+ const shown = options.slice(0, MAX_UNION_VALUES_NAMED).join(', ')
+ const rest = options.length > MAX_UNION_VALUES_NAMED ? `, ... (${options.length} accepted values)` : ''
+ return `parameter "${name}" must be one of: ${shown}${rest}`
+ }
+ const branch = bestUnionBranch(branches)
+ if (!branch) {
+ return undefined
+ }
+ const parts = branch.slice(0, MAX_UNION_ISSUES_NAMED).map((issue) => {
+ const nestedPath = [...path, ...issue.path]
+ if (issue.code === 'invalid_union') {
+ const nested = describeUnionIssue(issue.errors, nestedPath, depth + 1)
+ if (nested) {
+ return nested
+ }
+ }
+ const nestedName = nestedPath.map(String).join('.')
+ return nestedName ? `parameter "${nestedName}": ${issue.message}` : issue.message
+ })
+ if (branch.length > MAX_UNION_ISSUES_NAMED) {
+ parts.push('...')
+ }
+ return [...new Set(parts)].join('; ')
+}
+
/** Turns a Zod validation failure into a short, field-named message the model
* can act on. Without it, a missing/`undefined` path segment slips through to
* the HTTP layer and the API returns a generic 404 that reads as "entity does
@@ -725,6 +957,20 @@ export function formatInputValidationError(
// A strict schema rejects unknown keys instead of dropping them, and the
// `unrecognized_keys` branch below already names them.
const keysWereRejected = error.issues.some((issue) => issue.code === 'unrecognized_keys')
+ // Resolved once, and on first need: the answer reads only `input` and
+ // `schema`, so it is the same for every issue, while it costs a schema parse
+ // per stray object key. Most rejections never reach the branch that asks.
+ //
+ // Top-level misses only, like its sibling: wrapping the payload can leave a
+ // whole parameter unfilled, but never a field inside one the caller reached.
+ let wrapper: { key: string | undefined } | undefined
+ const overWrappedKey = (issuePath: ReadonlyArray<PropertyKey>): string | undefined => {
+ if (issuePath.length !== 1) {
+ return undefined
+ }
+ wrapper ??= { key: overWrappedPayloadKey(input, schema) }
+ return wrapper.key
+ }
const parts = error.issues.map((issue) => {
const path = issue.path.map(String).join('.')
if (issue.code === 'invalid_type') {
@@ -734,6 +980,11 @@ export function formatInputValidationError(
const shape = acceptedWrapperShape(path, input, schema)
return `missing required parameter: ${path}${hint}; the fields you sent belong inside it, so resend them as ${shape}`
}
+ const overWrapped = overWrappedKey(issue.path)
+ if (overWrapped !== undefined) {
+ const shape = acceptedTopLevelShape((input as Record<string, unknown>)[overWrapped], schema)
+ return `missing required parameter: ${path}${hint}; this tool takes these fields at the top level, not nested under "${overWrapped}", so resend them as ${shape}`
+ }
const dropped = keysWereRejected ? [] : undeclaredKeys(input, schema)
if (dropped.length) {
const named = dropped
@@ -746,6 +997,12 @@ export function formatInputValidationError(
}
return `parameter "${path}" must be of type ${issue.expected}`
}
+ if (issue.code === 'invalid_union') {
+ const expanded = describeUnionIssue(issue.errors, issue.path)
+ if (expanded) {
+ return expanded
+ }
+ }
if (issue.code === 'unrecognized_keys') {
return `unexpected ${issue.keys.length > 1 ? 'properties' : 'property'}: ${issue.keys.join(', ')}`
}
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index a88541879742..bbc23c947cbf 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -2106,5 +2106,138 @@ describe('exec tool', () => {
)
})
})
+
+ // Zod drops the wrapper, so a wrapped payload and an empty call arrive as
+ // the same missing-parameter message.
+ describe('a top-level payload the caller wrapped', () => {
+ const formatFor = (input: unknown): string => {
+ const tool = GENERATED_TOOL_MAP['query-trends']!()
+ const result = tool.schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+ return formatInputValidationError('query-trends', result.error!, input, tool.schema)
+ }
+
+ it('names the wrapper and echoes the fields back at the top level', () => {
+ const message = formatFor({
+ query: { series: [{ kind: 'EventsNode', event: '$pageview' }], dateRange: { date_from: '-7d' } },
+ })
+
+ expect(message).toContain('not nested under "query"')
+ expect(message).toContain('resend them as {"series": ..., "dateRange": ...}')
+ })
+
+ it('identifies the wrapping under any key, and when the fields have their own errors', () => {
+ const message = formatFor({ source: { series: [{ kind: 'EventsNode', event: 3 }] } })
+
+ expect(message).toContain('not nested under "source"')
+ })
+
+ it('leaves an unrelated stray key as a dropped key, not a wrapper', () => {
+ const message = formatFor({ events: ['$pageview'] })
+
+ expect(message).toContain('this tool ignored these keys it does not accept: "events"')
+ })
+
+ // Wrapping leaves a whole parameter unfilled, never a field inside one
+ // the caller reached, so a stray payload must not claim a nested miss.
+ it('leaves a field missing inside a parameter to the caller', () => {
+ const message = formatFor({
+ series: [{ kind: 'EventsNode', event: '$pageview' }],
+ breakdownFilter: {},
+ query: { series: [{ kind: 'EventsNode', event: '$pageview' }] },
+ })
+
+ expect(message).toContain('missing required parameter: breakdownFilter.breakdowns')
+ expect(message).not.toContain('not nested under')
+ })
+ })
+
+ // A union member is reported as one `Invalid input` at the array entry,
+ // which never names the key to change.
+ describe('a union member the caller got wrong', () => {
+ const formatFor = (input: unknown): string => {
+ const tool = GENERATED_TOOL_MAP['query-trends']!()
+ const result = tool.schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+ return formatInputValidationError('query-trends', result.error!, input, tool.schema)
+ }
+
+ it('names the field inside the entry rather than the entry alone', () => {
+ const message = formatFor({
+ series: [
+ { kind: 'EventsNode', event: '$pageview' },
+ { kind: 'ActionsNode', id: 3 },
+ ],
+ })
+
+ expect(message).toContain('parameter "series.1.name"')
+ })
+
+ it('lists the accepted values for a rejected enum, capped', () => {
+ const message = formatFor({
+ series: [{ kind: 'EventsNode', event: '$pageview', math: 'unique_users' }],
+ })
+
+ expect(message).toContain('parameter "series.0.math" must be one of: total, dau')
+ expect(message).toMatch(/\.\.\. \(\d+ accepted values\)/)
+ })
+
+ // A variant can pin a second field to one value without that field
+ // selecting the variant, so the shortest-branch guess reported the
+ // `type` the caller got right as the field to rewrite.
+ it.each([
+ [
+ 'a flag filter with the wrong operator',
+ { type: 'flag', key: 'new-onboarding', operator: 'exact', value: true },
+ 'parameter "properties.0.operator"',
+ ],
+ [
+ 'a cohort filter with the wrong key',
+ { type: 'cohort', key: 'cohort_id', operator: 'in', value: 42 },
+ 'parameter "properties.0.key"',
+ ],
+ ])('names the field to change on %s, not its type', (_label, filter, expected) => {
+ const message = formatFor({ series: [{ event: '$pageview' }], properties: [filter] })
+
+ expect(message).toContain(expected)
+ expect(message).not.toContain('parameter "properties.0.type"')
+ })
+
+ it('descends through a nested union to the field that failed', () => {
+ const message = formatFor({
+ series: [
+ {
+ kind: 'EventsNode',
+ event: '$pageview',
+ properties: [{ key: 'plan', operator: 'exact', type: 'event' }],
+ },
+ ],
+ })
+
+ expect(message).toContain('parameter "series.0.properties.0.value"')
+ })
+
+ // The deepest path the generated schemas hold: the series union, the
+ // group's `nodes` union, the filter union, and the generic filter's own.
+ it('descends into a filter on a series the caller grouped', () => {
+ const message = formatFor({
+ series: [
+ {
+ kind: 'GroupNode',
+ nodes: [
+ {
+ kind: 'EventsNode',
+ event: '$pageview',
+ properties: [{ key: 'plan', operator: 'exact', type: 'event' }],
+ },
+ { kind: 'EventsNode', event: '$pageleave' },
+ ],
+ },
+ ],
+ })
+
+ expect(message).toContain('parameter "series.0.nodes.0.properties.0.value"')
+ })
+ })
})
})
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.ts
new file mode 100644
index 000000000000..b3ebfbef14e9
--- /dev/null
+++ b/services/mcp/tests/unit/top-level-query-input-example.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+
+import { createExecTool } from '@/tools/exec'
+import { GENERATED_TOOL_MAP } from '@/tools/generated'
+import { getToolDefinitions } from '@/tools/toolDefinitions'
+import type { Context, Tool, ToolBase, ZodObjectAny } from '@/tools/types'
+
+/**
+ * The mirror of `nested-query-input-example.test.ts`: a query wrapper takes the
+ * query fields as its own top-level parameters, so an example written as a query
+ * document teaches a call the tool rejects.
+ *
+ * Every documented example is checked through both routes a caller reaches the
+ * tool by: the schema directly, and the `exec` CLI behind `call <tool> <json>`.
+ */
+
+const TOP_LEVEL_QUERY_TOOLS = [
+ 'query-trends',
+ 'query-funnel',
+ 'query-retention',
+ 'query-stickiness',
+ 'query-paths',
+ 'query-lifecycle',
+] as const
+
+const definitions = getToolDefinitions()
+
+/** Every fenced ```json block in a description, parsed; unparseable blocks are
+ * skipped because a description may show a fragment rather than a whole call. */
+function jsonExamples(description: string): unknown[] {
+ const examples: unknown[] = []
+ for (const match of description.matchAll(/```json\n([\s\S]*?)```/g)) {
+ try {
+ examples.push(JSON.parse(match[1]!))
+ } catch {
+ continue
+ }
+ }
+ return examples
+}
+
+/** Every field the example sets that the parsed input no longer carries. */
+function droppedFields(sent: unknown, accepted: unknown, trail = ''): string[] {
+ if (Array.isArray(sent)) {
+ return Array.isArray(accepted)
+ ? sent.flatMap((item, index) => droppedFields(item, accepted[index], `${trail}[${index}]`))
+ : [trail]
+ }
+ if (typeof sent !== 'object' || sent === null) {
+ return []
+ }
+ if (typeof accepted !== 'object' || accepted === null) {
+ return [trail]
+ }
+ return Object.entries(sent).flatMap(([key, value]) => {
+ const path = trail ? `${trail}.${key}` : key
+ const held = accepted as Record<string, unknown>
+ return key in held ? droppedFields(value, held[key], path) : [path]
+ })
+}
+
+const mockContext = { getDistinctId: async () => 'test-distinct-id' } as unknown as Context
+
+/** The generated tool with its handler replaced, so a `call` exercises the
+ * validation gate without reaching the API. */
+function asExecutableTool(name: string, base: ToolBase<ZodObjectAny>): Tool<ZodObjectAny> {
+ return {
+ ...base,
+ title: name,
+ description: definitions[name]?.description ?? '',
+ scopes: [],
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false, readOnlyHint: true },
+ handler: async () => ({ results: [] }),
+ }
+}
+
+describe('tools that take their query fields at the top level', () => {
+ it.each(TOP_LEVEL_QUERY_TOOLS)('%s takes no nested query parameter', (name) => {
+ // Guards the premise: were one of these to grow a `query` wrapper, its
+ // examples would have to nest, and the cases below would be backwards.
+ const schema = z.toJSONSchema(GENERATED_TOOL_MAP[name]!().schema, { io: 'input' }) as Record<string, unknown>
+ const properties = schema['properties'] as Record<string, unknown> | undefined
+
+ expect(properties && 'query' in properties).toBeFalsy()
+ })
+
+ it.each(TOP_LEVEL_QUERY_TOOLS)('%s documents examples its own schema accepts', (name) => {
+ const tool = GENERATED_TOOL_MAP[name]!()
+ const examples = jsonExamples(definitions[name]?.description ?? '')
+
+ expect(examples.length, `${name} needs at least one \`\`\`json example`).toBeGreaterThan(0)
+ for (const example of examples) {
+ const result = tool.schema.safeParse(example)
+ expect(result.success, `${name} documents an example it rejects: ${JSON.stringify(result)}`).toBe(true)
+ }
+ })
+
+ it.each(TOP_LEVEL_QUERY_TOOLS)('%s accepts its documented examples through the exec CLI', async (name) => {
+ const exec = createExecTool(
+ [asExecutableTool(name, GENERATED_TOOL_MAP[name]!())],
+ mockContext,
+ 'test description',
+ 'test command reference',
+ undefined
+ )
+
+ for (const example of jsonExamples(definitions[name]?.description ?? '')) {
+ const output = await exec
+ .handler(mockContext, { command: `call ${name} ${JSON.stringify(example)}` })
+ .catch((error: Error) => `rejected: ${error.message}`)
+
+ expect(String(output)).not.toContain('Invalid input')
+ }
+ })
+
+ // 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
+ // step's inner nodes, and its schema drops that.
+ it('query-trends documents examples that keep every field they set', () => {
+ const tool = GENERATED_TOOL_MAP['query-trends']!()
+
+ for (const example of jsonExamples(definitions['query-trends']?.description ?? '')) {
+ const result = tool.schema.safeParse(example)
+
+ expect(result.success).toBe(true)
+ expect(droppedFields(example, result.data)).toEqual([])
+ }
+ })
+
+ it('documents both a single-series and a multi-series trends example', () => {
+ const series = jsonExamples(definitions['query-trends']?.description ?? '')
+ .filter((example): example is { series: unknown[] } => Array.isArray((example as any)?.series))
+ .map((example) => example.series.length)
+
+ expect(series).toContain(1)
+ expect(series.some((count) => count > 1)).toBe(true)
+ })
+})