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.

feat(mcp): steer agents to the right trends display type (#109035)

Sam Pennington98b74ba1a0a6
diff --git a/ee/hogai/chat_agent/trends/prompts.py b/ee/hogai/chat_agent/trends/prompts.py
index 93bae736917b..41315f14e029 100644
--- a/ee/hogai/chat_agent/trends/prompts.py
+++ b/ee/hogai/chat_agent/trends/prompts.py
@@ -18,7 +18,7 @@ For trends queries, use an appropriate ChartDisplayType for the output. For exam
- if the plan indicates cumulative dynamics across time, use `ActionsLineGraphCumulative`.
- if the plan can be answered with a single number, use `BoldNumber`.
- if the plan requests a table, use `ActionsTable`.
-- if the data is categorical, use `ActionsBar`.
+- if the plan compares categories or breakdown values as totals, use `ActionsBarValue`. `ActionsBar` is a time series with one bar per interval, not one bar per category.
- if the data is easy to understand in a pie chart, use `ActionsPie`.
- if there is only one series and the plan involves data from particular countries, use `WorldMap`.
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 22a282afe789..4df36b0df693 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -5561,7 +5561,7 @@
},
"display": {
"default": "ActionsLineGraph",
- "description": "Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison (\"how many X in the last 30 days\", \"what's our conversion rate this month\", \"how does this month compare to last\"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data. `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.",
+ "description": "Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart with one bar per interval and breakdown values stacked in each bar. Do not use it to compare breakdown values or series as totals. Use `ActionsBarValue` for that. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison (\"how many X in the last 30 days\", \"what's our conversion rate this month\", \"how does this month compare to last\"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart with one bar per breakdown value or series; good for categorical data such as \"top pages\" or \"failures by reason\". `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.",
"enum": [
"Auto",
"ActionsLineGraph",
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index b00974e51c05..cfc2c5742488 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -488,12 +488,12 @@ export interface AssistantTrendsFilter {
/**
* Visualization type. Available values:
* `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time.
- * `ActionsBar` - time-series bar chart.
+ * `ActionsBar` - time-series bar chart with one bar per interval and breakdown values stacked in each bar. Do not use it to compare breakdown values or series as totals. Use `ActionsBarValue` for that.
* `ActionsAreaGraph` - time-series area chart.
* `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics.
* `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison ("how many X in the last 30 days", "what's our conversion rate this month", "how does this month compare to last"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown.
* `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series.
- * `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data.
+ * `ActionsBarValue` - total value (NOT time-series) bar chart with one bar per breakdown value or series; good for categorical data such as "top pages" or "failures by reason".
* `ActionsPie` - total value pie chart; good for visualizing proportions.
* `ActionsTable` - total value table; good when using breakdown to list users or other entities.
* `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.
diff --git a/posthog/schema.py b/posthog/schema.py
index 3f4772cf9328..a1885933dfa6 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -4672,27 +4672,31 @@ class AssistantTrendsFilter(BaseModel):
description=(
"Visualization type. Available values: `ActionsLineGraph` - time-series"
" line chart; most common option, as it shows change over time."
- " `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series"
- " area chart. `ActionsLineGraphCumulative` - cumulative time-series line"
- " chart; good for cumulative metrics. `Metric` - single large number with a"
- " change pill and a sparkline. Use for a period summary or an explicit"
- ' current-versus-previous-period comparison ("how many X in the last 30'
- ' days", "what\'s our conversion rate this month", "how does this month'
- ' compare to last"). Do not use for a question about change over time, a'
- " cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect"
- " each interval. Set `compareFilter.compare` to `true` to compare the"
- " current period with the previous period. Without it, the pill compares"
- " the first interval with the last interval. Configure the display with the"
- " `metric*` fields below. Single series, no breakdown. `BoldNumber` -"
- " single large number with no change or sparkline. Use instead of `Metric`"
- " only when a trend is meaningless, such as an all-time total or a fixed"
- " ratio. You CANNOT use this with breakdown or if the insight has more than"
- " one series. `ActionsBarValue` - total value (NOT time-series) bar chart;"
- " good for categorical data. `ActionsPie` - total value pie chart; good for"
- " visualizing proportions. `ActionsTable` - total value table; good when"
- " using breakdown to list users or other entities. `WorldMap` - total value"
- " world map; use when breaking down by country name using property"
- " `$geoip_country_name`, and only then."
+ " `ActionsBar` - time-series bar chart with one bar per interval and"
+ " breakdown values stacked in each bar. Do not use it to compare breakdown"
+ " values or series as totals. Use `ActionsBarValue` for that."
+ " `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative`"
+ " - cumulative time-series line chart; good for cumulative metrics."
+ " `Metric` - single large number with a change pill and a sparkline. Use"
+ " for a period summary or an explicit current-versus-previous-period"
+ ' comparison ("how many X in the last 30 days", "what\'s our conversion'
+ ' rate this month", "how does this month compare to last"). Do not use for'
+ " a question about change over time, a cadence, or a pattern. Use"
+ " `ActionsLineGraph` so the person can inspect each interval. Set"
+ " `compareFilter.compare` to `true` to compare the current period with the"
+ " previous period. Without it, the pill compares the first interval with"
+ " the last interval. Configure the display with the `metric*` fields below."
+ " Single series, no breakdown. `BoldNumber` - single large number with no"
+ " change or sparkline. Use instead of `Metric` only when a trend is"
+ " meaningless, such as an all-time total or a fixed ratio. You CANNOT use"
+ " this with breakdown or if the insight has more than one series."
+ " `ActionsBarValue` - total value (NOT time-series) bar chart with one bar"
+ ' per breakdown value or series; good for categorical data such as "top'
+ ' pages" or "failures by reason". `ActionsPie` - total value pie chart;'
+ " good for visualizing proportions. `ActionsTable` - total value table;"
+ " good when using breakdown to list users or other entities. `WorldMap` -"
+ " total value world map; use when breaking down by country name using"
+ " property `$geoip_country_name`, and only then."
),
)
formulaNodes: list[TrendsFormulaNode] | None = Field(
diff --git a/products/posthog_ai/eval_harness/test/test_visualization_choice_scorers.py b/products/posthog_ai/eval_harness/test/test_visualization_choice_scorers.py
index 4af54abb0db4..87a33af9225a 100644
--- a/products/posthog_ai/eval_harness/test/test_visualization_choice_scorers.py
+++ b/products/posthog_ai/eval_harness/test/test_visualization_choice_scorers.py
@@ -40,6 +40,20 @@ def _funnel_call(
return ("mcp__posthog__query-funnel", query, "ok")
+def _saved_call(display: str, wrapped: bool = True, status: str = "completed") -> tuple:
+ source = {"kind": "TrendsQuery", **_trends_call(display, "file_type", ["uploaded_file"])[1]}
+ query = {"kind": "InsightVizNode", "source": source} if wrapped else source
+ return ("mcp__posthog__insight-create", {"name": "Uploads by file type", "query": query}, "ok", status)
+
+
+UPLOADS_BY_FILE_TYPE = {
+ "tool": "query-trends",
+ "display": ["ActionsBarValue"],
+ "breakdown": "file_type",
+ "events": ["uploaded_file"],
+}
+
+
def _sql_call(status: str = "completed") -> tuple:
return ("mcp__posthog__execute-sql", {"query": "SELECT 1"}, "1", status)
@@ -79,6 +93,36 @@ PAGEVIEWS_BY_BROWSER = {
0.0,
["funnel_viz"],
),
+ ([_saved_call("ActionsBarValue")], UPLOADS_BY_FILE_TYPE, 1.0, []),
+ ([_saved_call("ActionsBarValue", wrapped=False)], UPLOADS_BY_FILE_TYPE, 1.0, []),
+ (
+ [_trends_call("ActionsBarValue", "file_type", ["uploaded_file"]), _saved_call("ActionsBar")],
+ UPLOADS_BY_FILE_TYPE,
+ 0.0,
+ ["display"],
+ ),
+ (
+ [
+ _trends_call("ActionsBarValue", "file_type", ["uploaded_file"]),
+ _saved_call("ActionsBar", status="failed"),
+ ],
+ UPLOADS_BY_FILE_TYPE,
+ 1.0,
+ [],
+ ),
+ (
+ [
+ _trends_call("ActionsBarValue", "file_type", ["uploaded_file"]),
+ (
+ "mcp__posthog__insight-create",
+ {"name": "Uploads", "query": {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery"}}},
+ "ok",
+ ),
+ ],
+ UPLOADS_BY_FILE_TYPE,
+ 0.0,
+ ["tool"],
+ ),
([_sql_call()], PAGEVIEWS_BY_BROWSER, 0.0, ["tool"]),
([_trends_call("ActionsLineGraph", "$browser"), _sql_call()], {"tool": "execute-sql"}, 0.0, ["tool"]),
(
diff --git a/products/posthog_ai/evals/product_analytics/eval_visualization_choice.py b/products/posthog_ai/evals/product_analytics/eval_visualization_choice.py
index eb4fb1d0d2eb..b9b670559824 100644
--- a/products/posthog_ai/evals/product_analytics/eval_visualization_choice.py
+++ b/products/posthog_ai/evals/product_analytics/eval_visualization_choice.py
@@ -1,10 +1,12 @@
"""Does the sandboxed agent pick the preferred chart type for a question?
-Two preferences the tool descriptions steer toward: a single number over a period
-gets the ``Metric`` display rather than ``BoldNumber``, and a question about how
+Preferences the tool descriptions steer toward: a single number over a period
+gets the ``Metric`` display rather than ``BoldNumber``, a question about how
conversion changes over time gets a funnel with ``funnelVizType: trends`` rather
-than ``steps``. ``InsightShape`` checks the answer query's tool, display,
-comparison, funnel view, and events.
+than ``steps``, and totals per category get ``ActionsBarValue`` rather than the
+time-series ``ActionsBar``. ``InsightShape`` checks the answer query's tool, display,
+comparison, funnel view, and events. ``eval_saved_insight_display`` checks the
+same choices on the query the agent saves with ``insight-create``.
To run:
flox activate -- bash -c "set -a; source .env; set +a; hogli evals eval_visualization_choice --max-sandboxes 1"
@@ -17,9 +19,12 @@ from typing import Any
from products.posthog_ai.eval_harness.base import SandboxedPublicEval
from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
-from products.posthog_ai.eval_harness.scorers import NoToolCall
+from products.posthog_ai.eval_harness.scorers import NoToolCall, RequiredToolCall
from products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLS, InsightShape
+TIME_SERIES_DISPLAYS = ["ActionsLineGraph", "ActionsBar", "ActionsAreaGraph", "ActionsUnstackedBar"]
+CATEGORY_TOTAL_DISPLAYS = ["ActionsBarValue", "ActionsPie", "ActionsTable"]
+
def _case(name: str, prompt: str, **shape: Any) -> SandboxedEvalCase:
return SandboxedEvalCase(name=name, prompt=prompt, expected={"insight_shape": shape})
@@ -50,6 +55,30 @@ async def eval_visualization_choice(ctx: EvalContext) -> None:
display="ActionsLineGraph",
events=["signed_up"],
),
+ _case(
+ "totals_uploads_by_file_type",
+ "Which file types do people upload the most? Compare the totals for the last 30 days.",
+ tool="query-trends",
+ display=CATEGORY_TOTAL_DISPLAYS,
+ breakdown="file_type",
+ events=["uploaded_file"],
+ ),
+ _case(
+ "bar_chart_upgrades_by_new_plan",
+ "Show me a bar chart of plan upgrades by new plan over the last 90 days.",
+ tool="query-trends",
+ display="ActionsBarValue",
+ breakdown="new_plan",
+ events=["upgraded_plan"],
+ ),
+ _case(
+ "trend_uploads_by_file_type_weekly",
+ "How have weekly uploads changed over the last 8 weeks for each file type?",
+ tool="query-trends",
+ display=TIME_SERIES_DISPLAYS,
+ breakdown="file_type",
+ events=["uploaded_file"],
+ ),
_case(
"funnel_steps_signup_to_upload",
"What's the conversion rate from signing up to uploading a first file?",
@@ -82,3 +111,47 @@ async def eval_visualization_choice(ctx: EvalContext) -> None:
],
ctx=ctx,
)
+
+
+async def eval_saved_insight_display(ctx: EvalContext) -> None:
+ cases = [
+ _case(
+ "saved_totals_uploads_by_file_type",
+ "Save an insight that compares how many files of each file type were uploaded in the last 30 days.",
+ tool="query-trends",
+ display=CATEGORY_TOTAL_DISPLAYS,
+ breakdown="file_type",
+ events=["uploaded_file"],
+ ),
+ _case(
+ "saved_bar_chart_upgrades_by_new_plan",
+ "Save a bar chart of plan upgrades by new plan for the last 90 days.",
+ tool="query-trends",
+ display="ActionsBarValue",
+ breakdown="new_plan",
+ events=["upgraded_plan"],
+ ),
+ _case(
+ "saved_trend_uploads_by_file_type_weekly",
+ "Save an insight of weekly uploads for each file type over the last 8 weeks.",
+ tool="query-trends",
+ display=TIME_SERIES_DISPLAYS,
+ breakdown="file_type",
+ events=["uploaded_file"],
+ ),
+ _case(
+ "saved_metric_signups_vs_previous",
+ "Save an insight with the number of signups in the last 30 days compared with the 30 days before.",
+ tool="query-trends",
+ display="Metric",
+ compare=True,
+ events=["signed_up"],
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-saved-insight-display-cli",
+ cases=cases,
+ scorers=[RequiredToolCall(["insight-create"], name="saved_insight"), InsightShape()],
+ ctx=ctx,
+ )
diff --git a/products/posthog_ai/evals/product_analytics/scorers.py b/products/posthog_ai/evals/product_analytics/scorers.py
index 97498fb03732..e19b3615f64c 100644
--- a/products/posthog_ai/evals/product_analytics/scorers.py
+++ b/products/posthog_ai/evals/product_analytics/scorers.py
@@ -316,7 +316,7 @@ Material aspects (must align in spirit, not necessarily byte-for-byte):
5. **Formulas** (``trendsFilter.formulaNodes``): must be semantically equivalent. ``A/B`` and ``B/A * 100`` are NOT equivalent — direction matters. ``A/B`` and ``A/B`` is fine even if one writes ``A / B``.
6. **Date range**: relative windows (``-14d``, ``-30d``, ``-1y``) are acceptable when equivalent to the expected window. Absolute dates must match the same month/year. Default ``-30d`` is acceptable when the prompt has no time component.
7. **Interval**: ``day`` / ``week`` / ``month`` / ``hour`` — must match the prompt's implied granularity. ``day`` is the default and acceptable when not specified.
-8. **Display type** (``trendsFilter.display``): only material when the prompt clearly calls for a specific display, OR when the expected sets a non-default like ``BoldNumber`` (single-value answer) or ``ActionsBar`` (categorical comparison) and that nature is intrinsic to the prompt. ``ActionsLineGraph`` is the default — do not penalize the actual for omitting it.
+8. **Display type** (``trendsFilter.display``): only material when the prompt clearly calls for a specific display, OR when the expected sets a non-default like ``BoldNumber`` (single-value answer) or ``ActionsBarValue`` (totals per category) and that nature is intrinsic to the prompt. ``ActionsLineGraph`` is the default — do not penalize the actual for omitting it.
Ignore (do NOT penalize, even when the expected sets them):
- ``filterTestAccounts``, ``samplingFactor``, ``showLegend``, ``showValuesOnSeries``, ``smoothingIntervals``, ``compareFilter``, ``kind`` defaults, presence/absence of optional containers when their effective content matches.
@@ -713,6 +713,18 @@ TYPED_QUERY_TOOLS = frozenset(
)
SERIES_QUERY_TOOLS = frozenset({QUERY_TRENDS_TOOL_NAME, QUERY_FUNNEL_TOOL_NAME})
+_QUERY_TOOL_BY_KIND = {
+ "TrendsQuery": QUERY_TRENDS_TOOL_NAME,
+ "FunnelsQuery": QUERY_FUNNEL_TOOL_NAME,
+ "RetentionQuery": QUERY_RETENTION_TOOL_NAME,
+ "PathsQuery": "query-paths",
+ "StickinessQuery": "query-stickiness",
+ "LifecycleQuery": "query-lifecycle",
+ "WebStatsTableQuery": "query-web-stats",
+ "WebOverviewQuery": "query-web-overview",
+ "HogQLQuery": "execute-sql",
+}
+
_ANSWER_TOOL_SCHEMAS: dict[str, type[BaseModel]] = {
QUERY_TRENDS_TOOL_NAME: AssistantTrendsQuery,
QUERY_FUNNEL_TOOL_NAME: AssistantFunnelsQuery,
@@ -723,7 +735,9 @@ _ANSWER_TOOL_SCHEMAS: dict[str, type[BaseModel]] = {
class InsightShape(Scorer):
"""Binary: did the agent's answer query have the expected skeleton?
- The most recent successful typed query is the answer query. A later SQL call is
+ When the agent saved an insight, the most recent saved query is the answer query, and
+ it is checked as the query tool for its kind, such as ``query-trends`` or ``execute-sql``.
+ Otherwise the most recent successful typed query is the answer query. A later SQL call is
ignored because the desktop agent can rerun a typed query as SQL to render it.
When no typed query ran, the most recent non-discovery SQL call is the answer.
@@ -753,29 +767,35 @@ class InsightShape(Scorer):
parser = parser_for(output)
if parser is None:
return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})
+ calls = parser.get_tool_calls()
+ saved = [answer for answer in map(_saved_query, calls) if answer]
successful = [
call
- for call in parser.get_tool_calls()
+ for call in calls
if not call.is_error
and (call.name in TYPED_QUERY_TOOLS or call.name == "execute-sql")
and not is_schema_discovery_call(call)
]
- if not successful:
+ if saved:
+ tool_name, raw_query = saved[-1]
+ elif successful:
+ typed = [call for call in successful if call.name in TYPED_QUERY_TOOLS]
+ answer = typed[-1] if typed else successful[-1]
+ tool_name, raw_query = answer.name, answer.input if isinstance(answer.input, dict) else {}
+ else:
return Score(name=self._name(), score=0.0, metadata={"reason": "Agent never ran an insight tool"})
- typed = [call for call in successful if call.name in TYPED_QUERY_TOOLS]
- answer = typed[-1] if typed else successful[-1]
- query = _query_of(answer)
+ query = _query_of(tool_name, raw_query)
actual: dict[str, Any] = {
- "tool": answer.name,
- "display": _actual_display(query, answer.name),
- "compare": _actual_compare(query, answer.name),
- "funnel_viz": _actual_funnel_viz(query, answer.name),
+ "tool": tool_name,
+ "display": _actual_display(query, tool_name),
+ "compare": _actual_compare(query, tool_name),
+ "funnel_viz": _actual_funnel_viz(query, tool_name),
"breakdown": _actual_breakdown(query),
"event_sequence": _actual_events(query),
}
actual["events"] = sorted(actual["event_sequence"], key=str)
- checked = shape if answer.name in SERIES_QUERY_TOOLS else {"tool": shape.get("tool")}
+ checked = shape if tool_name in SERIES_QUERY_TOOLS else {"tool": shape.get("tool")}
mismatches = {
key: actual.get(key)
for key, expected_value in checked.items()
@@ -788,9 +808,20 @@ class InsightShape(Scorer):
)
-def _query_of(call: ToolCall) -> dict[str, Any]:
- raw = call.input if isinstance(call.input, dict) else {}
- schema = _ANSWER_TOOL_SCHEMAS.get(call.name)
+def _saved_query(call: ToolCall) -> tuple[str, dict[str, Any]] | None:
+ if call.is_error or call.name not in ("insight-create", "insight-update") or not isinstance(call.input, dict):
+ return None
+ query = call.input.get("query")
+ if isinstance(query, dict) and query.get("kind") in ("InsightVizNode", "DataVisualizationNode"):
+ query = query.get("source")
+ if not isinstance(query, dict):
+ return None
+ kind = str(query.get("kind"))
+ return _QUERY_TOOL_BY_KIND.get(kind, kind), query
+
+
+def _query_of(tool_name: str, raw: dict[str, Any]) -> dict[str, Any]:
+ schema = _ANSWER_TOOL_SCHEMAS.get(tool_name)
if schema is None:
return raw
cleaned = {k: v for k, v in raw.items() if k in schema.model_fields}
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index 527a1f3c6ce5..144977085afc 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -109,7 +109,56 @@ tools:
A bare query is accepted too. `{ "kind": "TrendsQuery", ... }` and `{ "kind": "HogQLQuery", ... }` are each
wrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.
- agent_note:
+
+
+ Choose the TrendsQuery `trendsFilter.display` from the question the insight answers:
+
+ - Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.
+
+ - Compare breakdown values or series as totals ("top pages", "failures by reason"): `ActionsBarValue`, or
+ `ActionsPie` for the share of a whole with a few values.
+
+ - One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare:
+ true` for a comparison, or `BoldNumber` when a trend has no meaning.
+
+ - Many breakdown rows that a person reads rather than compares: `ActionsTable`.
+
+ - Totals per country from a `$geoip_country_name` breakdown: `WorldMap`.
+
+
+ In a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked
+ in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per
+ X-axis value.
+ agent_note: >
+ When you tell the user about this insight, name the display you chose and one or two other displays that
+ also fit this query, in one short sentence, and offer to change it. If the user agrees, change it with
+ insight-update. Suggest only displays that the insight kind supports and that fit the question:
+
+
+ - Trends (`trendsFilter.display`): for change over time `ActionsLineGraph`, `ActionsAreaGraph`, `ActionsBar`
+ or `ActionsUnstackedBar`; for totals per breakdown value or series `ActionsBarValue`, `ActionsPie` or
+ `ActionsTable`; for one number `Metric` or `BoldNumber`, never with a breakdown or more than one series;
+ `WorldMap` only for a `$geoip_country_name` breakdown.
+
+ - Funnels (`funnelsFilter.funnelVizType`): `steps` for drop-off per step, `trends` for conversion over time,
+ or `time_to_convert` for how long users take.
+
+ - Retention (`retentionFilter.display`): `ActionsLineGraph` or `ActionsBar`.
+
+ - Stickiness (`stickinessFilter.display`): `ActionsLineGraph`, `ActionsBar` or `ActionsAreaGraph`.
+
+ - Lifecycle: stacked or side-by-side bars (`lifecycleFilter.stacked`).
+
+ - SQL (`DataVisualizationNode` `display`): only displays that fit the columns the query returns.
+
+ - Paths: suggest nothing.
+
+
+ Use the chart names a person sees, such as "bar chart per category" or "line chart", not enum values or tool
+ names. If the user named the chart they want, do not suggest others. If you create several insights in this
+ task, give one short list of alternatives at the end, not one per insight.
+
+
After creating a Trends, SQL (HogQL), Funnels or Metrics insight, call insight-query with the returned
short_id, read the current value, and offer an alert when the metric is one someone would act on if it moved
sharply (signups, active users, revenue, conversion rate, error or failure counts, latency). Name an actual
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 29eaefecacf7..943e18a1d617 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6880,7 +6880,7 @@
}
},
"insight-create": {
- "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.",
+ "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_name` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value.",
"category": "Product analytics",
"feature": "product_analytics",
"summary": "Create insight",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 52e984ea91a5..e717754d579e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -7077,7 +7077,7 @@
}
},
"insight-create": {
- "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.",
+ "description": "Create a new saved insight from a name and query definition. Test queries with query-trends / query-funnel /\nquery-retention / query-paths / query-stickiness / query-lifecycle first to confirm the shape, then save.\nReturns insight metadata only — after creating, call the insight-query tool with the returned `short_id` if\nyou want to see the computed results.\n\nPut the insight definition in `query.source`, under the wrapper node that matches it. Use\n`InsightVizNode` for a product analytics query and `DataVisualizationNode` for a SQL one:\n\n```json\n{ \"name\": \"Example\", \"query\": { \"kind\": \"DataVisualizationNode\", \"source\": { \"kind\": \"HogQLQuery\", \"query\": \"SELECT 1\" } } }\n```\n\nA bare query is accepted too. `{ \"kind\": \"TrendsQuery\", ... }` and `{ \"kind\": \"HogQLQuery\", ... }` are each\nwrapped for you, so a query you just ran through one of the `query-*` tools can be passed straight through.\n\nChoose the TrendsQuery `trendsFilter.display` from the question the insight answers:\n- Change over time: `ActionsLineGraph` (default), `ActionsAreaGraph`, or `ActionsBar`.\n- Compare breakdown values or series as totals (\"top pages\", \"failures by reason\"): `ActionsBarValue`, or `ActionsPie` for the share of a whole with a few values.\n- One number for the period, or this period against the previous one: `Metric` with `compareFilter.compare: true` for a comparison, or `BoldNumber` when a trend has no meaning.\n- Many breakdown rows that a person reads rather than compares: `ActionsTable`.\n- Totals per country from a `$geoip_country_name` breakdown: `WorldMap`.\n\nIn a TrendsQuery, `ActionsBar` is a time series with one bar per interval and the breakdown values stacked in each bar. It is not one bar per category. In a SQL `DataVisualizationNode`, `ActionsBar` is one bar per X-axis value.",
"category": "Product analytics",
"feature": "product_analytics",
"summary": "Create insight",
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index 1a53e374f58c..a8f04e81a340 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -315,7 +315,7 @@ const insightCreate = (): ToolBase<
]) as typeof result
return withAgentNote(
await withPostHogUrl(context, filtered, `/insights/${filtered.short_id}`),
- 'After creating a Trends, SQL (HogQL), Funnels or Metrics insight, call insight-query with the returned short_id, read the current value, and offer an alert when the metric is one someone would act on if it moved sharply (signups, active users, revenue, conversion rate, error or failure counts, latency). Name an actual number, never a placeholder such as X, for example "want me to alert you when daily signups drop below 400?". A count sitting at zero, such as errors or failures, is a strong case, so offer an upper bound of 1. Offer nothing when the insight returned no rows. When no absolute number fits and the insight supports it, offer a relative-change alert on a sudden increase or decrease. Skip metrics nobody acts on, such as raw pageview or event-volume counts, and skip high-cardinality breakdowns. Judge the metric, not the request. A newly created insight, or one the user just asked to see, is not throwaway for that reason. If the user already declined an alert in this conversation, do not offer again. If alert-create is unavailable, say nothing about alerts. Wait for the user to accept before creating an alert.'
+ 'When you tell the user about this insight, name the display you chose and one or two other displays that also fit this query, in one short sentence, and offer to change it. If the user agrees, change it with insight-update. Suggest only displays that the insight kind supports and that fit the question:\n\n- Trends (`trendsFilter.display`): for change over time `ActionsLineGraph`, `ActionsAreaGraph`, `ActionsBar` or `ActionsUnstackedBar`; for totals per breakdown value or series `ActionsBarValue`, `ActionsPie` or `ActionsTable`; for one number `Metric` or `BoldNumber`, never with a breakdown or more than one series; `WorldMap` only for a `$geoip_country_name` breakdown.\n- Funnels (`funnelsFilter.funnelVizType`): `steps` for drop-off per step, `trends` for conversion over time, or `time_to_convert` for how long users take.\n- Retention (`retentionFilter.display`): `ActionsLineGraph` or `ActionsBar`.\n- Stickiness (`stickinessFilter.display`): `ActionsLineGraph`, `ActionsBar` or `ActionsAreaGraph`.\n- Lifecycle: stacked or side-by-side bars (`lifecycleFilter.stacked`).\n- SQL (`DataVisualizationNode` `display`): only displays that fit the columns the query returns.\n- Paths: suggest nothing.\n\nUse the chart names a person sees, such as "bar chart per category" or "line chart", not enum values or tool names. If the user named the chart they want, do not suggest others. If you create several insights in this task, give one short list of alternatives at the end, not one per insight.\n\nAfter creating a Trends, SQL (HogQL), Funnels or Metrics insight, call insight-query with the returned short_id, read the current value, and offer an alert when the metric is one someone would act on if it moved sharply (signups, active users, revenue, conversion rate, error or failure counts, latency). Name an actual number, never a placeholder such as X, for example "want me to alert you when daily signups drop below 400?". A count sitting at zero, such as errors or failures, is a strong case, so offer an upper bound of 1. Offer nothing when the insight returned no rows. When no absolute number fits and the insight supports it, offer a relative-change alert on a sudden increase or decrease. Skip metrics nobody acts on, such as raw pageview or event-volume counts, and skip high-cardinality breakdowns. Judge the metric, not the request. A newly created insight, or one the user just asked to see, is not throwaway for that reason. If the user already declined an alert in this conversation, do not offer again. If alert-create is unavailable, say nothing about alerts. Wait for the user to accept before creating an alert.\n'
)
},
})
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index a20575c23c42..c5c5c1b42da7 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -658,7 +658,7 @@ const AssistantTrendsFilter = z.object({
'ScatterPlot',
])
.describe(
- 'Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison ("how many X in the last 30 days", "what\'s our conversion rate this month", "how does this month compare to last"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data. `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.'
+ 'Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart with one bar per interval and breakdown values stacked in each bar. Do not use it to compare breakdown values or series as totals. Use `ActionsBarValue` for that. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison ("how many X in the last 30 days", "what\'s our conversion rate this month", "how does this month compare to last"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart with one bar per breakdown value or series; good for categorical data such as "top pages" or "failures by reason". `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.'
)
.default('ActionsLineGraph')
.optional(),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
index 965f0b7d8663..780d62400b9d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
@@ -4342,7 +4342,7 @@
},
"display": {
"default": "ActionsLineGraph",
- "description": "Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison (\"how many X in the last 30 days\", \"what's our conversion rate this month\", \"how does this month compare to last\"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data. `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.",
+ "description": "Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart with one bar per interval and breakdown values stacked in each bar. Do not use it to compare breakdown values or series as totals. Use `ActionsBarValue` for that. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison (\"how many X in the last 30 days\", \"what's our conversion rate this month\", \"how does this month compare to last\"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart with one bar per breakdown value or series; good for categorical data such as \"top pages\" or \"failures by reason\". `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.",
"enum": [
"Auto",
"ActionsLineGraph",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
index 024556884d32..8c364559f493 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
@@ -4160,7 +4160,7 @@
},
"display": {
"default": "ActionsLineGraph",
- "description": "Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison (\"how many X in the last 30 days\", \"what's our conversion rate this month\", \"how does this month compare to last\"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data. `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.",
+ "description": "Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart with one bar per interval and breakdown values stacked in each bar. Do not use it to compare breakdown values or series as totals. Use `ActionsBarValue` for that. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `Metric` - single large number with a change pill and a sparkline. Use for a period summary or an explicit current-versus-previous-period comparison (\"how many X in the last 30 days\", \"what's our conversion rate this month\", \"how does this month compare to last\"). Do not use for a question about change over time, a cadence, or a pattern. Use `ActionsLineGraph` so the person can inspect each interval. Set `compareFilter.compare` to `true` to compare the current period with the previous period. Without it, the pill compares the first interval with the last interval. Configure the display with the `metric*` fields below. Single series, no breakdown. `BoldNumber` - single large number with no change or sparkline. Use instead of `Metric` only when a trend is meaningless, such as an all-time total or a fixed ratio. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart with one bar per breakdown value or series; good for categorical data such as \"top pages\" or \"failures by reason\". `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.",
"enum": [
"Auto",
"ActionsLineGraph",