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.

chore(mcp): balance typed query and sql guidance (#90985)

Daniel Parkerb784ea87c893
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index c31cc61acd21..dc98c9758228 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -75,6 +75,9 @@ which unlocks flexibility in data retrieval, search, and manipulation.
Additionally, the consumer has access to a skill that provides schema references and example patterns,
giving it richer context about PostHog's data model.
+Here, "SQL-first" describes entity retrieval, not a preference for every analytics task.
+Choose typed queries or SQL from the required calculation and output, as described in [query selection guidance](./writing-skills.md#query-selection-guidance).
+
Primarily oriented toward coding agents (PostHog Desktop, PostHog AI, Claude Code).
## Claude web and desktop exec schema budget
diff --git a/docs/published/handbook/engineering/ai/writing-skills.md b/docs/published/handbook/engineering/ai/writing-skills.md
index 7343a7019290..765925897841 100644
--- a/docs/published/handbook/engineering/ai/writing-skills.md
+++ b/docs/published/handbook/engineering/ai/writing-skills.md
@@ -74,6 +74,19 @@ and describe the desired outcome for the customer.
This separation matters because agents are good at composing simple tools
but need guidance on _which_ tools to use, in _what order_, with _what constraints_.
+### Query selection guidance
+
+Query skills should choose methods from the requested calculation and output, not require typed queries or SQL for every task.
+Reuse matching approved metrics or saved queries when they define the requested measure.
+Use typed queries when standard PostHog calculation rules or native insight controls matter.
+Use SQL for record inspection, custom calculations, joins, existing SQL, or requests for SQL.
+For a new event-analytics query, prefer a typed query when both methods preserve the requested calculation and output, including simple aggregates.
+Keep valid existing SQL when it fits the task. A task that needs SQL does not require a failed typed-query attempt first.
+Reassess when the task changes. Neither the previous tool call nor a request for a chart determines the next method.
+
+Tool descriptions should state capabilities and limits. Skill examples should show direct inputs for the method they teach.
+Keep SQL examples for SQL tasks rather than requiring agents to reconstruct typed inputs from generated SQL.
+
### When to write a skill
The decision flow:
diff --git a/products/ai_observability/skills/exploring-llm-costs/SKILL.md b/products/ai_observability/skills/exploring-llm-costs/SKILL.md
index 91e5181ed873..ae7091de70cd 100644
--- a/products/ai_observability/skills/exploring-llm-costs/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-costs/SKILL.md
@@ -24,6 +24,7 @@ regression debugging, and materializing results as insights, dashboards, or aler
| Tool | Purpose |
| ------------------------------- | ------------------------------------------------------------------- |
+| `posthog:query-trends` | Native cost trends with supported sums, breakdowns, and comparisons |
| `posthog:execute-sql` | Ad-hoc HogQL for any cost aggregation — the workhorse of this skill |
| `posthog:query-llm-traces-list` | List traces with rolled-up cost, token, and error metrics |
| `posthog:query-llm-trace` | Cost breakdown of a single trace across all its events |
diff --git a/products/posthog_ai/skills/README.md b/products/posthog_ai/skills/README.md
index 04062fd42abd..b62356d74972 100644
--- a/products/posthog_ai/skills/README.md
+++ b/products/posthog_ai/skills/README.md
@@ -8,7 +8,7 @@ This directory also happens to host the build pipeline for _every_ product's ski
## Skills
-- **querying-posthog-data** — required reading before writing any HogQL/SQL. Indexes ~60 references covering the `system.*` table schemas, HogQL's differences from ClickHouse SQL, available functions, and the semantic layer (canonical metrics in `system.information_schema.metrics`).
+- **querying-posthog-data** — explains how to choose typed queries or SQL from the requested calculation and output. It covers schema discovery, query examples, rendering, and canonical metrics in `system.information_schema.metrics`.
- **managing-subscriptions** — scheduled email, Slack, and webhook deliveries of insight or dashboard snapshots, optionally with an AI-written summary. Covers subscriptions vs alerts, prompt subscriptions, and the AI-consent and quota gates.
- **auditing-experiments-flags** — health-checks experiments and feature flags for configuration issues, staleness, and best-practice violations, with severity-badged findings.
- **writing-simplified-technical-english** — writes English a reader cannot misread, based on ASD-STE100. Used at runtime by Signals and Review Hog for any prose an agent produces that someone else acts on.
diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
index 64390e37f3c2..e10e52e0e192 100644
--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md
+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
@@ -1,11 +1,64 @@
---
name: querying-posthog-data
-description: 'Required reading before writing any HogQL/SQL or calling execute-sql against PostHog. Use whenever the user wants to search, find, or do complex aggregations PostHog entities (insights, dashboards, cohorts, feature flags, experiments, surveys, hog flows, data warehouse, persons, etc.) and query analytics data (trends, funnels, retention, lifecycle, paths, stickiness, web analytics, error tracking, logs, sessions, LLM traces). Also the first stop for a governed business or telemetry measure (MRR, activation, billable usage, active organizations, failure rates): check the semantic layer (canonical metrics in system.information_schema.metrics) before deriving from raw events or a typed domain tool. Covers HogQL syntax differences from ClickHouse SQL, system table schemas (system.*), available functions, query examples, and the schema-discovery workflow.'
+description: >
+ Explains how to choose typed queries or SQL for PostHog data.
+ Read it before you write HogQL/SQL.
+ Also read it before you call execute-sql against PostHog.
+ Use it to find or aggregate PostHog entities.
+ These entities include insights, dashboards, cohorts, feature flags, experiments,
+ surveys, hog flows, warehouse data, and persons.
+ Use it for trends, funnels, retention, lifecycle, paths, stickiness,
+ web analytics, error tracking, logs, sessions, and LLM traces.
+ Before you calculate a governed business or telemetry measure, check
+ system.information_schema.metrics for an approved definition.
+ Examples include MRR, activation, billable usage, active organizations, and failure rates.
+ Use the approved definition before you derive a measure from raw events or use a typed domain tool.
+ It also covers HogQL differences, system table schemas, functions, query examples, and schema discovery.
---
# Querying data in PostHog
-The [guidelines](./references/guidelines.md) contain the same instructions as `posthog:execute-sql`. If you've already read `posthog:execute-sql`, you don't need to read them again.
+The [guidelines](./references/guidelines.md) explain SQL syntax and schema discovery. Read them when you choose `posthog:execute-sql`. You do not need them for typed queries.
+
+## Choose the query path
+
+Choose the method from the requested calculation and output. Do not choose a method from the tool name. No method fits all tasks.
+
+For governed measures, follow the semantic-layer workflow below before deriving a query. Reuse a matching approved metric or saved query when it defines the requested measure.
+
+### Typed query tools
+
+Use a typed query when the task needs standard PostHog calculation rules or native insight controls:
+
+- `posthog:query-trends` for native trends with series, breakdowns, formulas, and period comparisons.
+- `posthog:query-funnel` for conversion rates, drop-off, and step completion.
+- `posthog:query-retention` for users returning over time.
+- `posthog:query-stickiness` for engagement frequency.
+- `posthog:query-paths` for navigation flows.
+- `posthog:query-lifecycle` for new, returning, resurrecting, and dormant users.
+
+Do not approximate these analyses with SQL when the user expects PostHog's standard definitions. Confirm that the selected tool supports the required calculation and output.
+
+### SQL queries
+
+Use `posthog:execute-sql` when:
+
+- The request searches `system.*` tables for PostHog entities.
+- The user requests SQL, record inspection, or changes to an existing SQL query.
+- The analysis needs custom joins, CTEs, window functions, or warehouse SQL.
+- SQL results must inform how you construct a later typed query. Typed query tools cannot accept SQL results as input.
+
+### When either method fits
+
+For a new event-analytics query, prefer a typed query when both methods preserve the requested calculation and output. This includes simple counts, sums, and other supported aggregates. Use SQL directly when the task calls for it. You do not need to try a typed query first.
+
+Keep a valid existing query when it fits the task. Choose the method again when the task changes. The previous tool call does not determine the method. Do not choose a method only because the user requests a chart or table. Both methods can support saved visualizations.
+
+## Render query results
+
+Use the UI resource returned by the selected query tool. For example, `posthog:query-trends` returns the `query-results` UI resource. Do not call `posthog:render-ui` for the same result.
+
+Keep a written summary with the visualization. If the query tool does not return a UI, follow the client's rendering instructions.
## When to use this skill
@@ -21,7 +74,7 @@ Don't try to reconstruct the entity from SQL — `execute-sql` is for discovery,
### Querying analytics data
-When the user wants analytics data (trends, funnels, retention, paths, sessions, LLM traces, web analytics, errors, logs, etc.) and the existing insight schemas don't fit the request:
+When SQL is the selected method for an analytics request:
1. Look for a matching example under Analytics Query Examples. The list is not exhaustive — there may not be an example for every scenario. If one is a close fit (same domain, similar aggregation), read it; otherwise skip this step.
2. Adapt the example query (if one was found) to the user's request and run it via `posthog:execute-sql`. If no example fit, compose the query from scratch using the Data Schema and HogQL References.
@@ -99,7 +152,7 @@ Every column table below is generated from the live HogQL catalog, so it lists e
## Analytics Query Examples
-Use the examples below to create optimized analytical queries.
+These references include a direct typed-query example and SQL examples for analytics and data inspection. Choose the method before adapting an example. An example's format does not require you to use that method for every similar question.
- [Trends (unique users, specific time range, single series)](./references/example-trends-unique-users.md)
- [Trends (total count with multiple breakdowns)](./references/example-trends-breakdowns.md)
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/example-trends-unique-users.md.j2 b/products/posthog_ai/skills/querying-posthog-data/references/example-trends-unique-users.md.j2
index e4577a1773c6..d9d7133b2857 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/example-trends-unique-users.md.j2
+++ b/products/posthog_ai/skills/querying-posthog-data/references/example-trends-unique-users.md.j2
@@ -1,5 +1,45 @@
-# Trends (unique users, for specific 90 days)
+# Daily unique users over the last 30 days
+
+## Native trends insight
+
+First, check the event with `posthog:read-data-schema`. Then call `posthog:query-trends` with this input for a native daily trends insight:
+
+```json
+{
+ "kind": "TrendsQuery",
+ "series": [{ "kind": "EventsNode", "event": "chat with ai", "math": "dau" }],
+ "dateRange": { "date_from": "-30d" },
+ "interval": "day"
+}
+```
+
+The omitted `filterTestAccounts` field follows the project's "Filter out internal and test users" setting. Set it only when the request explicitly asks to override that setting.
+
+Use the native insight controls for breakdowns or period comparisons. Do not generate SQL only to render this insight.
+
+## SQL representation
+
+This build-time SQL represents the same aggregation and time range. It cannot inherit the project's test-account setting. Before running or adapting it, apply the project's test-account filters when "Filter out internal and test users" is enabled.
```sql
-{{ render_hogql_example({"kind": "TrendsQuery", "filterTestAccounts": false, "series": [{"kind": "EventsNode", "event": "chat with ai", "math": "dau"}], "dateRange": {"date_from": "-30d"}, "interval": "day"}) }}
+{{ render_hogql_example({"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "chat with ai", "math": "dau"}], "dateRange": {"date_from": "-30d"}, "interval": "day"}) }}
```
+
+## Simple aggregate: prefer a typed query when both fit
+
+For "Count `chat with ai` events in the last seven days", either a typed total or SQL can answer the question.
+Prefer the typed query for a new analysis when both methods preserve the requested calculation and output.
+Use `posthog:query-trends` with `math: "total"`, `compareFilter.compare: true`, `trendsFilter.display: "Metric"`, `trendsFilter.metricSummary: "total"`, and the requested time bounds.
+Resolve both rolling bounds to ISO 8601 timestamps and pass them as `date_from` and `date_to` when matching the SQL window below.
+
+The SQL form remains valid when the user requests SQL or an existing SQL query already fits:
+
+```sql
+SELECT count() AS event_count
+FROM events
+WHERE event = 'chat with ai'
+ AND timestamp >= now() - INTERVAL 7 DAY
+ AND timestamp <= now()
+```
+
+Keep test-account filtering consistent. Reuse either valid form when it already fits the task. A single number does not require a method change.
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md b/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md
index 1d755ba65631..154ff9206814 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md
+++ b/products/posthog_ai/skills/querying-posthog-data/references/guidelines.md
@@ -2,7 +2,7 @@
Use the `posthog:execute-sql` MCP tool to execute HogQL queries. HogQL is PostHog's variant of SQL that supports most of ClickHouse SQL. We use terms "HogQL" and "SQL" interchangeably. More info is available in the `querying-posthog-data` skill.
-Do not assume that data exists. Use the SQL tool proactively to find the right data.
+Do not assume that data exists. Use `read-data-schema` to verify events and properties. For SQL tables, use `system.information_schema` as described below. Schema discovery does not determine which tool should run the analysis.
#### Search types
diff --git a/products/product_analytics/skills/investigate-metric/SKILL.md b/products/product_analytics/skills/investigate-metric/SKILL.md
index c393348550ad..a83b06ad8e8d 100644
--- a/products/product_analytics/skills/investigate-metric/SKILL.md
+++ b/products/product_analytics/skills/investigate-metric/SKILL.md
@@ -28,7 +28,7 @@ Targets PostHog MCP v2. Typed query tools accept the query body directly — pas
| `posthog:query-lifecycle` | Lifecycle (new/returning/resurrecting/dormant) |
| `posthog:query-paths` | Paths (navigation flow) |
| `posthog:query-trends-actors` | Users behind a trend bucket (trends source only) |
-| `posthog:execute-sql` | HogQL — when no typed tool fits |
+| `posthog:execute-sql` | Existing SQL insights and custom analysis |
| `posthog:read-data-schema` | Discover events, properties, sample values |
| `posthog:insight-get` / `-query` | Fetch a saved insight's metadata / data |
diff --git a/products/signals/skills/signals-scout-ai-observability/SKILL.md b/products/signals/skills/signals-scout-ai-observability/SKILL.md
index cb446390abe8..05b27f1774d8 100644
--- a/products/signals/skills/signals-scout-ai-observability/SKILL.md
+++ b/products/signals/skills/signals-scout-ai-observability/SKILL.md
@@ -123,6 +123,7 @@ Telemetry & cost:
- `query-llm-traces-list` — recent traces, filterable by user / model / cost / error / tool.
- `query-llm-trace` — drill into a single trace (full request/response, tool calls, spans).
- `get-llm-total-costs-for-project` — top-level cost surface.
+- `query-trends` — native trends, breakdowns, and comparisons over `$ai_*` events when its aggregations preserve the required calculation.
- `execute-sql` — the workhorse for trends and breakdowns over `$ai_*` events (read `posthog:querying-posthog-data` for HogQL discipline).
Evals & enrichment config:
diff --git a/services/mcp/definitions/prompts/query-trends.md b/services/mcp/definitions/prompts/query-trends.md
index 36a94c462034..c67deaaa91f0 100644
--- a/services/mcp/definitions/prompts/query-trends.md
+++ b/services/mcp/definitions/prompts/query-trends.md
@@ -1,5 +1,7 @@
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.
+Use 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.
+
Use 'read-data-schema' to discover available events, actions, and properties for filters and breakdowns.
The trends insights have the following features:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index f6134500af13..8d1ef8517ff3 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9454,7 +9454,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\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, 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 5d04c3356173..bfc4cad1db51 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10012,7 +10012,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\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, 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/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.md
index 242be0d5677a..e57500f253d7 100644
--- a/services/mcp/src/templates/execute-sql-prompt.md
+++ b/services/mcp/src/templates/execute-sql-prompt.md
@@ -1,18 +1,22 @@
Executes HogQL — PostHog's variant of SQL that supports most of ClickHouse SQL. "HogQL" and "SQL" are used interchangeably.
-{guidelines}
-
### When to use `execute-sql`
-**Use `query-*` tools whenever the question maps to a supported insight type.** These tools produce typed, saveable insights; SQL forfeits that.
-Reach for `execute-sql` only when no `query-*` tool can express the question:
+Use SQL for record inspection, custom calculations, joins, existing SQL, or requests for SQL. SQL results can inform how you construct a later typed query. Typed query tools cannot accept SQL results as input. SQL cases include:
+
+- **Searching or listing existing PostHog entities** — insights, dashboards, cohorts, feature flags, experiments, surveys. No typed query tool covers these; query the `system.*` tables.
+- **Multi-event joins or aggregations across event types** that do not fit a single series.
+- **Sophisticated queries beyond typed query schemas** — custom grouping, window functions, non-trivial CTEs, data warehouse joins.
+
+For governed measures, check for a matching approved metric before deriving a new calculation.
-- **Searching or listing existing PostHog entities** — insights, dashboards, cohorts, feature flags, experiments, surveys. No `query-*` tool covers these; query the `system.*` tables.
-- **Multi-event joins or aggregations across event types** that don't fit a single series.
-- **Sophisticated queries beyond `query-*` schemas** — custom grouping, window functions, non-trivial CTEs, data warehouse joins.
-- **Pre-filtering or shaping** a large dataset before running a `query-*` call.
+Use typed queries when standard PostHog calculation rules or native insight controls matter. Do not approximate standard funnels or retention with SQL.
-If a `query-*` tool fits, use it. Default to `query-*`; SQL is the escape hatch, not the starting point.
+For a new event-analytics query, prefer a typed query when both methods preserve the requested calculation and output, including simple aggregates. Use SQL directly when the task calls for it, without requiring a failed typed-query attempt. Keep valid existing SQL when it fits the task, and reassess when the task changes.
+
+Both typed queries and SQL can support saved visualizations. A chart or table alone does not determine the method.
+
+{guidelines}
{schema_discovery}
diff --git a/services/mcp/src/templates/sections/examples.md b/services/mcp/src/templates/sections/examples.md
index 9aff8593a30f..75321592b9ac 100644
--- a/services/mcp/src/templates/sections/examples.md
+++ b/services/mcp/src/templates/sections/examples.md
@@ -1,7 +1,5 @@
### Examples
-Before writing any queries, read the `querying-posthog-data` skill when it is installed in your environment, and follow any relevant query examples. It is a built-in PostHog skill, not a team skill in the skills store, so do not fetch it with `skill-get`. When it is not installed, the `execute-sql` tool description carries the same core guidance.
-
#### Creating an insight with segmentation
<example>
diff --git a/services/mcp/src/templates/sections/retrieving-data.md b/services/mcp/src/templates/sections/retrieving-data.md
index b206526800af..e474d6809b36 100644
--- a/services/mcp/src/templates/sections/retrieving-data.md
+++ b/services/mcp/src/templates/sections/retrieving-data.md
@@ -1,14 +1,14 @@
### Retrieving data
-**Use `query-*` tools when the question maps to a supported insight type** (after any metric-routing rules above, when present). These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: "Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?" If yes, prefer the `query-*` tool — see `Choosing the right query tool` below for prompt-to-field patterns.
+Choose the query method from the requested result and calculation rules, after any metric-routing rules above. Reuse a matching approved metric or saved query when it defines the requested measure.
-Reach for `execute-sql` only when no `query-*` tool can express the question:
+- Use a typed query when standard PostHog calculation rules or native insight controls matter. Do not replace standard funnels or retention with approximate SQL.
+- Use `execute-sql` for record inspection, custom calculations, joins, existing SQL, or requests for SQL. It also supports entity search through `system.*` tables.
+- For a new event-analytics query, prefer a typed query when both methods preserve the requested calculation and output, including simple aggregates.
-- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.
-- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.
-- Pre-filtering or shaping data before running a `query-*` call.
+SQL results can inform how you construct a later typed query. Typed query tools cannot accept SQL results as input. Reassess the method when the task changes, regardless of the previous tool call. A chart or table alone does not determine the method: both typed queries and SQL can support saved visualizations.
-When you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.
+Read the selected tool's description and schema when they are not already in context. You do not need to inspect every alternative before using SQL.
{entity_schema_discovery}
@@ -20,7 +20,7 @@ When you do use `execute-sql`, run `info execute-sql` first for the full discove
Bare "retention" and "customers" are catalog terms that may have several approved definitions. Consult the catalog and clarify materially different matches instead of routing directly to an insight query.
-By insight type:
+For tasks that need these native analyses:
- "Count / rate / latency / cost of a named thing" -> `metric-list` first; run a matching governed metric before any insight query
- "How many / how much / over time / compare periods" -> `metric-list` first, then `query-trends` if no approved metric matches
@@ -29,6 +29,6 @@ By insight type:
- "How frequently / how many days per week / power users" -> `query-stickiness`
- "What do users do after X / before X / navigation flow" -> `query-paths`
- "New vs returning vs dormant / user composition" -> `query-lifecycle`
-- "LLM traces / AI generations / token usage" -> `query-llm-traces-list`
+- "List LLM traces with cost, token, or error metrics" -> `query-llm-traces-list`
Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation — read it (e.g. `info query-trends`) before constructing the query.
diff --git a/services/mcp/src/templates/sections/schema-workflow.md b/services/mcp/src/templates/sections/schema-workflow.md
index c928d9713f71..5f8a072cc4e1 100644
--- a/services/mcp/src/templates/sections/schema-workflow.md
+++ b/services/mcp/src/templates/sections/schema-workflow.md
@@ -1,3 +1,7 @@
+#### Read the query guidance
+
+Before selecting a query method, read the `querying-posthog-data` skill once if it is installed. Follow its query-selection guidance and relevant examples. It is a built-in PostHog skill, not a team skill: do not fetch it with `skill-get`. If it is not installed, use the available tool descriptions.
+
#### Schema-first workflow
After the metric-discovery check, verify the data schema before constructing any insight
@@ -10,12 +14,12 @@ Every `read-data-schema` call takes one `query` object, so send the whole payloa
1. **Discover events** - `{"query": {"kind": "events"}}` to find events matching the user's intent.
2. **Discover properties** - `{"query": {"kind": "event_properties", "event_name": "<event>"}}` for an event, or `{"query": {"kind": "entity_properties", "entity": "<entity>"}}` for a person, session, or group type (use the group type name for a group).
3. **Verify property values** - `{"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<property>"}}` when the value must match (e.g., "US" vs "United States").
-4. **Then construct the query** using the appropriate `query-*` tool.
+4. **Then construct the query** using the selected method. For SQL table schemas, also follow the `execute-sql` schema-discovery guidance.
If the required events or properties don't exist, tell the user instead of running an empty query.
#### Insight query workflow
-After the schema-first steps, choose the `query-*` tool matching the question, construct a minimal query (only the filters, breakdowns, and settings essential to the answer — each tool's description documents its schema with examples), execute, and analyze. Optionally save as an insight with `insight-create` or add to a dashboard.
+After schema verification, construct a minimal query with the selected tool. Include only the filters, breakdowns, and settings required for the answer. Execute the query and analyze the result. Save an insight or add it to a dashboard when the user requests it.
For complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 0c6154000bbe..5e743609735e 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -170,15 +170,15 @@ Example tool names: execute-sql, experiment-create, feature-flag-get-all.
### Retrieving data
-**Use `query-*` tools when the question maps to a supported insight type** (after any metric-routing rules above, when present). These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: "Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?" If yes, prefer the `query-*` tool — see `Choosing the right query tool` below for prompt-to-field patterns.
+Choose the query method from the requested result and calculation rules, after any metric-routing rules above. Reuse a matching approved metric or saved query when it defines the requested measure.
-Reach for `execute-sql` only when no `query-*` tool can express the question:
+- Use a typed query when standard PostHog calculation rules or native insight controls matter. Do not replace standard funnels or retention with approximate SQL.
+- Use `execute-sql` for record inspection, custom calculations, joins, existing SQL, or requests for SQL. It also supports entity search through `system.*` tables.
+- For a new event-analytics query, prefer a typed query when both methods preserve the requested calculation and output, including simple aggregates.
-- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.
-- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.
-- Pre-filtering or shaping data before running a `query-*` call.
+SQL results can inform how you construct a later typed query. Typed query tools cannot accept SQL results as input. Reassess the method when the task changes, regardless of the previous tool call. A chart or table alone does not determine the method: both typed queries and SQL can support saved visualizations.
-When you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.
+Read the selected tool's description and schema when they are not already in context. You do not need to inspect every alternative before using SQL.
#### Searching for existing entities
@@ -207,7 +207,7 @@ WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL
Bare "retention" and "customers" are catalog terms that may have several approved definitions. Consult the catalog and clarify materially different matches instead of routing directly to an insight query.
-By insight type:
+For tasks that need these native analyses:
- "Count / rate / latency / cost of a named thing" -> `metric-list` first; run a matching governed metric before any insight query
- "How many / how much / over time / compare periods" -> `metric-list` first, then `query-trends` if no approved metric matches
@@ -216,10 +216,14 @@ By insight type:
- "How frequently / how many days per week / power users" -> `query-stickiness`
- "What do users do after X / before X / navigation flow" -> `query-paths`
- "New vs returning vs dormant / user composition" -> `query-lifecycle`
-- "LLM traces / AI generations / token usage" -> `query-llm-traces-list`
+- "List LLM traces with cost, token, or error metrics" -> `query-llm-traces-list`
Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation — read it (e.g. `info query-trends`) before constructing the query.
+#### Read the query guidance
+
+Before selecting a query method, read the `querying-posthog-data` skill once if it is installed. Follow its query-selection guidance and relevant examples. It is a built-in PostHog skill, not a team skill: do not fetch it with `skill-get`. If it is not installed, use the available tool descriptions.
+
#### Schema-first workflow
After the metric-discovery check, verify the data schema before constructing any insight
@@ -232,13 +236,13 @@ Every `read-data-schema` call takes one `query` object, so send the whole payloa
1. **Discover events** - `{"query": {"kind": "events"}}` to find events matching the user's intent.
2. **Discover properties** - `{"query": {"kind": "event_properties", "event_name": "<event>"}}` for an event, or `{"query": {"kind": "entity_properties", "entity": "<entity>"}}` for a person, session, or group type (use the group type name for a group).
3. **Verify property values** - `{"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<property>"}}` when the value must match (e.g., "US" vs "United States").
-4. **Then construct the query** using the appropriate `query-*` tool.
+4. **Then construct the query** using the selected method. For SQL table schemas, also follow the `execute-sql` schema-discovery guidance.
If the required events or properties don't exist, tell the user instead of running an empty query.
#### Insight query workflow
-After the schema-first steps, choose the `query-*` tool matching the question, construct a minimal query (only the filters, breakdowns, and settings essential to the answer — each tool's description documents its schema with examples), execute, and analyze. Optionally save as an insight with `insight-create` or add to a dashboard.
+After schema verification, construct a minimal query with the selected tool. Include only the filters, breakdowns, and settings required for the answer. Execute the query and analyze the result. Save an insight or add it to a dashboard when the user requests it.
For complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.
@@ -302,8 +306,6 @@ Submitting feedback is **not** a way to end your turn or skip work. It's a side
### Examples
-Before writing any queries, read the `querying-posthog-data` skill when it is installed in your environment, and follow any relevant query examples. It is a built-in PostHog skill, not a team skill in the skills store, so do not fetch it with `skill-get`. When it is not installed, the `execute-sql` tool description carries the same core guidance.
-
#### Creating an insight with segmentation
<example>
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
index 31884d194688..8836031b65e0 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
@@ -54,15 +54,15 @@ The first call for that shape is `metric-list`; `read-data-schema`, `info query-
### Retrieving data
-**Use `query-*` tools when the question maps to a supported insight type** (after any metric-routing rules above, when present). These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: "Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?" If yes, prefer the `query-*` tool — see `Choosing the right query tool` below for prompt-to-field patterns.
+Choose the query method from the requested result and calculation rules, after any metric-routing rules above. Reuse a matching approved metric or saved query when it defines the requested measure.
-Reach for `execute-sql` only when no `query-*` tool can express the question:
+- Use a typed query when standard PostHog calculation rules or native insight controls matter. Do not replace standard funnels or retention with approximate SQL.
+- Use `execute-sql` for record inspection, custom calculations, joins, existing SQL, or requests for SQL. It also supports entity search through `system.*` tables.
+- For a new event-analytics query, prefer a typed query when both methods preserve the requested calculation and output, including simple aggregates.
-- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.
-- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.
-- Pre-filtering or shaping data before running a `query-*` call.
+SQL results can inform how you construct a later typed query. Typed query tools cannot accept SQL results as input. Reassess the method when the task changes, regardless of the previous tool call. A chart or table alone does not determine the method: both typed queries and SQL can support saved visualizations.
-When you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.
+Read the selected tool's description and schema when they are not already in context. You do not need to inspect every alternative before using SQL.
#### Searching for existing entities
@@ -91,7 +91,7 @@ WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL
Bare "retention" and "customers" are catalog terms that may have several approved definitions. Consult the catalog and clarify materially different matches instead of routing directly to an insight query.
-By insight type:
+For tasks that need these native analyses:
- "Count / rate / latency / cost of a named thing" -> `metric-list` first; run a matching governed metric before any insight query
- "How many / how much / over time / compare periods" -> `metric-list` first, then `query-trends` if no approved metric matches
@@ -100,10 +100,14 @@ By insight type:
- "How frequently / how many days per week / power users" -> `query-stickiness`
- "What do users do after X / before X / navigation flow" -> `query-paths`
- "New vs returning vs dormant / user composition" -> `query-lifecycle`
-- "LLM traces / AI generations / token usage" -> `query-llm-traces-list`
+- "List LLM traces with cost, token, or error metrics" -> `query-llm-traces-list`
Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation — read it (e.g. `info query-trends`) before constructing the query.
+#### Read the query guidance
+
+Before selecting a query method, read the `querying-posthog-data` skill once if it is installed. Follow its query-selection guidance and relevant examples. It is a built-in PostHog skill, not a team skill: do not fetch it with `skill-get`. If it is not installed, use the available tool descriptions.
+
#### Schema-first workflow
After the metric-discovery check, verify the data schema before constructing any insight
@@ -116,13 +120,13 @@ Every `read-data-schema` call takes one `query` object, so send the whole payloa
1. **Discover events** - `{"query": {"kind": "events"}}` to find events matching the user's intent.
2. **Discover properties** - `{"query": {"kind": "event_properties", "event_name": "<event>"}}` for an event, or `{"query": {"kind": "entity_properties", "entity": "<entity>"}}` for a person, session, or group type (use the group type name for a group).
3. **Verify property values** - `{"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<property>"}}` when the value must match (e.g., "US" vs "United States").
-4. **Then construct the query** using the appropriate `query-*` tool.
+4. **Then construct the query** using the selected method. For SQL table schemas, also follow the `execute-sql` schema-discovery guidance.
If the required events or properties don't exist, tell the user instead of running an empty query.
#### Insight query workflow
-After the schema-first steps, choose the `query-*` tool matching the question, construct a minimal query (only the filters, breakdowns, and settings essential to the answer — each tool's description documents its schema with examples), execute, and analyze. Optionally save as an insight with `insight-create` or add to a dashboard.
+After schema verification, construct a minimal query with the selected tool. Include only the filters, breakdowns, and settings required for the answer. Execute the query and analyze the result. Save an insight or add it to a dashboard when the user requests it.
For complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.
@@ -186,8 +190,6 @@ Submitting feedback is **not** a way to end your turn or skip work. It's a side
### Examples
-Before writing any queries, read the `querying-posthog-data` skill when it is installed in your environment, and follow any relevant query examples. It is a built-in PostHog skill, not a team skill in the skills store, so do not fetch it with `skill-get`. When it is not installed, the `execute-sql` tool description carries the same core guidance.
-
#### Creating an insight with segmentation
<example>