:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): add the explain-chart tool and app (#119175)
Sam Pennington20be2f06a85d
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yamlindex 41526cb11f87..03e1e67c9e3a 100644--- a/products/product_analytics/mcp/tools.yaml+++ b/products/product_analytics/mcp/tools.yaml@@ -10,6 +10,17 @@ ui_apps:type: detailview_prop: datalink_prop: openLink+ explain-chart:+ type: custom+ app_name: PostHog Chart Walkthrough+ description: A trends chart with the moments that stand out highlighted, explained one chapter at a time.+ render_ui:+ component_import: ../components/ExplainChart+ view_component: ExplainChart+ view_prop: data+ data_type: ExplainChartData+ link_prop: openLink+ app_prop: apptools:elements-stats-retrieve:operation: elements_stats_retrievediff --git a/products/product_analytics/skills/investigate-metric/SKILL.md b/products/product_analytics/skills/investigate-metric/SKILL.mdindex 7a2e7130e7ab..9efd08ecd301 100644--- a/products/product_analytics/skills/investigate-metric/SKILL.md+++ b/products/product_analytics/skills/investigate-metric/SKILL.md@@ -3,16 +3,17 @@ name: investigate-metricdescription: >Diagnose why a product metric changed (dropped, spiked, or plateaued) byorchestrating breakdowns, actors, paths, lifecycle, retention, and annotations- queries. Use when the user reports an anomaly, asks "why did X change?", or- needs root-cause analysis for a trend, funnel, retention, stickiness, or- lifecycle metric.+ queries. Use when the user reports an anomaly, asks "why did X change?", asks+ to explain or walk them through a chart, or needs root-cause analysis for a+ trend, funnel, retention, stickiness, or lifecycle metric.---# Investigating a metric change-For "why did X change?" questions about a saved insight, dashboard tile, or pasted query.-Don't load this skill for plain "what is X?" questions — only when there's an observed-change to explain.+For "why did X change?" questions about a saved insight, dashboard tile, or pasted query,+and for "explain this chart" or "walk me through this" when the user names no change.+Don't load this skill for plain "what is X?" questions — only when there's a chart or an+observed change to explain.## Tools@@ -31,6 +32,7 @@ Targets PostHog MCP v2. Typed query tools accept the query body directly — pas| `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 |+| `posthog:explain-chart` | Walk the user through a trends chart (Step 5) |Plus the standard PostHog tools the playbooks reference by name (`feature-flag-get-all`,`experiment-list`, `annotations-list`, `query-error-tracking-issues-list`, `query-logs`,@@ -87,6 +89,11 @@ If the user's question spans multiple kinds, run the playbooks in sequence.Run the primary tool. Record baseline, current, delta (absolute and %), and the startof the anomaly window.+When the user asked you to explain a trends chart over time and named no change, find what+stands out first with [what-stands-out.md](./references/what-stands-out.md). Each moment it+finds becomes its own anomaly to run through the rest of the steps, most striking first.+For funnels, retention, paths and other kinds, use that kind's playbook to choose what to look into.+### 2.2 Variance checkWiden to 3–4× the user's interval (or use `compareFilter: {"compare": true}` on@@ -121,9 +128,39 @@ in the control = strong hypothesis; moved too = expand the investigation. Skip w## Step 5 — Write findings-Use the format below. Offer to save key charts via `posthog:insight-create`. If a-cause is found and no annotation marks it, offer `posthog:annotation-create`. See-[common-causes.md](./references/common-causes.md) for the cause taxonomy.+Show the findings as a walkthrough when the session can display one, and as a written report otherwise.++### The walkthrough++Use it for a `TrendsQuery` over time, not a box plot, 2D heatmap or scatter plot, when the+`posthog:render-ui` tool is available and its `tool_name` list includes `explain-chart`. It draws the chart with each moment highlighted and lets the+user step through them. Map the investigation onto it:++- **Anomaly** → one chapter per moment, with `start` and `end` copied exactly from the+ chart's `days`. The app works out each chapter's numbers from the chart, so leave them out+ of `summary`.+- **Likely cause** and **Confidence** → `cause`, `confidence` and `confidence_reason`.+- **Evidence** → `evidence`, each finding with the `query` that produced it, or a `url`+ for a commit or a deploy. Pass the `TrendsQuery` you ran where you have one: the+ walkthrough draws it as a chart, while any other query only becomes a link.+- A **headline** of one sentence with no numbers sums up the whole chart.+ Wrap each name behind a moment, such as the referrer of a spike or the country behind a rise, in `**double asterisks**` so the walkthrough highlights it.+ Do the same in each `cause`.++Call `posthog:explain-chart` first. It reports any chapter whose dates match no point on the+chart, so fix those dates and call it again. Then call `posthog:render-ui` with `tool_name`+`explain-chart` and the same input as `tool_input`.++Then reply in at most three short sentences: which chapter to look at first, one caveat+about the data if the walkthrough cannot show it, and one offer from below. The walkthrough+already holds the chart, the chapters, their causes and their evidence, so the reply has no+bullet points, no description of the chart and no list of the moments.++### The written report++Without the walkthrough, use the format below. Offer to save key charts via `posthog:insight-create`.+If a cause is found and no annotation marks it, offer `posthog:annotation-create`.+See [common-causes.md](./references/common-causes.md) for the cause taxonomy.```markdown# Investigation: <metric>diff --git a/products/product_analytics/skills/investigate-metric/references/what-stands-out.md b/products/product_analytics/skills/investigate-metric/references/what-stands-out.mdnew file mode 100644index 000000000000..8b24e3488fe6--- /dev/null+++ b/products/product_analytics/skills/investigate-metric/references/what-stands-out.md@@ -0,0 +1,29 @@+# Finding what stands out in a trend++For "explain this chart" when the user names no change.+Read the series yourself and pick the moments worth a chapter.+Work from the numbers in the query result, not from a picture of the chart.++## Before you look++- **Leave out a period that has not ended.** When the chart's range runs to today, the last point is still counting and reads low. Mention it, but do not judge it against complete points.+- **Use the median as the typical level.** One extreme point moves an average but not a median.+- **Sparse series.** When 30% or more of the points are zero, judge against the non-zero points only, and say how many points are not zero.+- **Cumulative charts.** A cumulative line only rises, so every split looks like a change of level. Run the same query as a line of each period's value and pick the moments from that, then use those dates for the chart you explain.++## Moments worth a chapter++Look for these, in this order of how much they usually matter:++1. **A lasting change of level.** Find the point where the median before and the median after differ most, with at least three complete points on each side. It is worth a chapter when the level after is 1.4 times the level before or more, or 0.7 times or less. Judge any peak against the level on its own side of the change. A change in the last one or two points is a peak, a low point or the latest point, and it is too early to say whether it lasts.+2. **Peaks.** A point well above the typical level: more than 1.8 times it, and clear of the normal spread. Include the neighbours that are still more than halfway up. A "peak" wider than about a fifth of the chart is a change of level, not a peak. Keep the two biggest.+3. **Empty stretches.** Two or more points in a row below a tenth of the typical level. This is usually tracking that stopped or an outage, not behavior. Check for a deploy or an SDK change before you explain it any other way.+4. **A single low point.** Below 40% of the typical level, and clear of the normal spread.+5. **A weekly rhythm.** On a daily chart with two weeks or more, compare the median weekend day with the median weekday. Outside 0.6 to 1.5 times, say so once, so the dips do not read as problems.+6. **The latest complete point.** Compare it with the level the chart is at now. With a weekly rhythm, compare it with the same kind of day.++Cap the story at about five chapters.+Order dated moments by date, and put the weekly rhythm and the latest point last.+A chart with nothing on this list is a finding too: say the level is steady, and stop.++[`compare_to_prior_periods.py`](../scripts/compare_to_prior_periods.py) checks whether a moment is normal variance for its day of the week or hour.diff --git a/services/mcp/CONTRIBUTING.md b/services/mcp/CONTRIBUTING.mdindex 5b8213915e4e..cca414b25438 100644--- a/services/mcp/CONTRIBUTING.md+++ b/services/mcp/CONTRIBUTING.md@@ -343,6 +343,7 @@ For apps that need fully custom logic (like `debug.tsx` or `query-results.tsx`):```A view that opens links also names `link_prop`, the prop that receives the host's link opener.+ A view that calls server tools names `app_prop`, the prop that receives the host app.2. **Create the entry point** manually at `src/ui-apps/apps/my-custom-app.tsx`.This file will NOT be overwritten by the generator.@@ -359,6 +360,8 @@ For apps that need fully custom logic (like `debug.tsx` or `query-results.tsx`):export default () => withUiApp('my-custom-app', { name: 'my-tool', schema, handler })```+ When the app is the whole answer, set `renderedNote` on the tool. `render-ui` appends it to its result, so the model knows what the app already shows and keeps its reply short.+## DeploymentThe MCP server ships as the `posthog-mcp` Docker image to PostHog's US and EU Kubernetes clusters:diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 11075a9d75b0..5b04172e9b1c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6354,6 +6354,22 @@},"feature_flag": "experiment-behavior-comparison"},+ "explain-chart": {+ "description": "Show the person a walkthrough of a trends chart: the chart with each moment that stands out highlighted, and a panel that steps through them one chapter at a time, with what happened, the likely cause and the evidence.\n\nCall it at the end of an investigation, after you have looked into the chart yourself (the investigate-metric skill describes how). Pass the saved insight's `insightId`, or the TrendsQuery you ran as `query`, plus a one-sentence `headline` and the chapters in reading order.\n\nThe app works out each chapter's numbers from the chart itself (the value, and how it compares with a typical point), so leave the chart's numbers out of your text. Numbers from your own follow-up queries belong in `evidence`, with the `query` that found them so the person can open it. Say how sure you are with `confidence`, and word a cause you could not confirm as a guess. Wrap each name that explains a moment (a referrer, a page, a country, a release) in **double asterisks** to highlight it, in the headline as well as in the chapters.\n\nTrends only, one series at a time. A chart that shows a total, such as a number, pie, table or map, is drawn as the line behind it. A box plot, 2D heatmap or scatter plot is refused. The response says which chapters' dates matched no point on the chart.\n\nA direct call checks the chapters against the chart and returns a short summary, and may show the person nothing. Show the walkthrough with `render-ui` where that tool is available.",+ "category": "Insights & analytics",+ "feature": "insights",+ "summary": "Walk the person through a trends chart, one highlighted moment at a time.",+ "title": "Show chart walkthrough",+ "required_scopes": ["insight:read", "query:read"],+ "api_operations": ["GET /api/projects/{project_id}/insights/{id}/", "POST /api/projects/{project_id}/query/"],+ "feature_flag": "investigate-insight",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"external-data-destinations-list": {"description": "List the places this project's warehouse sources can write synced rows to. The PostHog warehouse is one of them, and it is where a source writes when nothing else is configured.","category": "Warehouse sources",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 88fad536291e..13b62ab0c4e7 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -302,6 +302,22 @@},"feature_flag": "insight-data-checks"},+ "explain-chart": {+ "description": "Show the person a walkthrough of a trends chart: the chart with each moment that stands out highlighted, and a panel that steps through them one chapter at a time, with what happened, the likely cause and the evidence.\n\nCall it at the end of an investigation, after you have looked into the chart yourself (the investigate-metric skill describes how). Pass the saved insight's `insightId`, or the TrendsQuery you ran as `query`, plus a one-sentence `headline` and the chapters in reading order.\n\nThe app works out each chapter's numbers from the chart itself (the value, and how it compares with a typical point), so leave the chart's numbers out of your text. Numbers from your own follow-up queries belong in `evidence`, with the `query` that found them so the person can open it. Say how sure you are with `confidence`, and word a cause you could not confirm as a guess. Wrap each name that explains a moment (a referrer, a page, a country, a release) in **double asterisks** to highlight it, in the headline as well as in the chapters.\n\nTrends only, one series at a time. A chart that shows a total, such as a number, pie, table or map, is drawn as the line behind it. A box plot, 2D heatmap or scatter plot is refused. The response says which chapters' dates matched no point on the chart.\n\nA direct call checks the chapters against the chart and returns a short summary, and may show the person nothing. Show the walkthrough with `render-ui` where that tool is available.",+ "category": "Insights & analytics",+ "feature": "insights",+ "summary": "Walk the person through a trends chart, one highlighted moment at a time.",+ "title": "Show chart walkthrough",+ "required_scopes": ["insight:read", "query:read"],+ "api_operations": ["GET /api/projects/{project_id}/insights/{id}/", "POST /api/projects/{project_id}/query/"],+ "feature_flag": "investigate-insight",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"notebook-edit": {"description": "Edit part of a notebook's content by short_id.\n\nFor markdown notebooks, use `execute-sql` to read the current markdown from `system.notebooks.markdown`, then edit with `old_markdown` / `new_markdown`. These are plain markdown strings; do not copy or construct the nested `ph-markdown-notebook` JSON wrapper.\n\nFor legacy rich-text notebooks, inspect the JSON content from `system.notebooks.content`, then edit with `old_value` / `new_value` JSON subtree replacement. Matching is by content: the tool finds `old_value` anywhere in the notebook and swaps it for `new_value` in place.\n\nOn success, returns the updated notebook with the new content and bumped version. On a 409 or 410 error, the notebook has changed since you loaded it; reload the latest markdown or JSON content and re-apply your edit.\nIf you have browser access, check how the edited notebook renders.","category": "Notebooks",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 41cece7ad136..cfc25eab86c0 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -630,6 +630,123 @@},"description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. To add a screenshot, upload the image with media-image-upload-start and media-image-upload-complete with purpose \"experiment\", then pass the returned id here. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant."},+ "ExplainChartInputSchema": {+ "type": "object",+ "properties": {+ "insightId": {+ "description": "The saved insight to explain: its numeric `id` or 8-character `short_id`.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ }+ ]+ },+ "query": {+ "description": "A TrendsQuery to explain when the chart is not a saved insight. Pass this or `insightId`.",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "series": {+ "default": 0,+ "description": "Index of the series in the chart's results that the story follows. Defaults to the first one.",+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "headline": {+ "type": "string",+ "minLength": 1,+ "maxLength": 300,+ "description": "One sentence a person could read in place of the whole story. Name what stands out, with no numbers, and wrap each name behind a moment, such as the referrer of a spike or the country behind a rise, in **double asterisks**."+ },+ "chapters": {+ "minItems": 1,+ "maxItems": 8,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80,+ "description": "A short title, for example \"A spike on October 2\" or \"Lower since September 28\"."+ },+ "start": {+ "type": "string",+ "minLength": 1,+ "description": "The first point the chapter covers, copied from the chart's `days` (for example `2026-10-02`, or `2026-10-02 14:00:00` on an hourly chart)."+ },+ "end": {+ "description": "The last point the chapter covers, inclusive. Omit it when the chapter is about one point.",+ "type": "string",+ "minLength": 1+ },+ "summary": {+ "description": "What happened, in one or two sentences. Do not repeat the chart's own numbers: the app works them out from the chart and shows them above this.",+ "type": "string",+ "maxLength": 400+ },+ "cause": {+ "description": "The most likely cause, in one or two sentences. Say whether it is a real change in behavior or an artifact of the data. Wrap the name behind it, such as a referrer or a country, in **double asterisks**. Omit it when you found no cause.",+ "type": "string",+ "maxLength": 600+ },+ "confidence": {+ "description": "How sure you are of the cause. high: independent signals agree. medium: one signal, or a strong pattern without a cross-check. low: a guess.",+ "type": "string",+ "enum": ["high", "medium", "low"]+ },+ "confidence_reason": {+ "description": "Why you gave that confidence, in one sentence.",+ "type": "string",+ "maxLength": 200+ },+ "evidence": {+ "description": "What you checked, at most 6 findings.",+ "maxItems": 6,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "minLength": 1,+ "maxLength": 400,+ "description": "One finding in one sentence, with the numbers from the query that found it. Mark the name that matters with **double asterisks**."+ },+ "query": {+ "description": "The query that found this, as you ran it (for example a TrendsQuery with a breakdown). It becomes a link to that chart, and a TrendsQuery also draws as a chart in the walkthrough.",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "url": {+ "description": "A link to the source when it is not a query, for example a commit, a pull request or a deploy.",+ "type": "string",+ "format": "uri",+ "pattern": "^https:\\/\\/.*"+ }+ },+ "required": ["text"]+ }+ }+ },+ "required": ["title", "start"]+ },+ "description": "The moments that stand out, in the order to read them. At most 8."+ }+ },+ "required": ["headline", "chapters"]+ },"ExternalDataJobsAfterSchema": {"type": "string","description": "ISO timestamp — only return jobs created after this date (e.g. \"2025-01-01T00:00:00Z\")."diff --git a/services/mcp/scripts/generate-ui-apps.ts b/services/mcp/scripts/generate-ui-apps.tsindex efccf8975d8b..88218a10e847 100644--- a/services/mcp/scripts/generate-ui-apps.ts+++ b/services/mcp/scripts/generate-ui-apps.ts@@ -302,10 +302,10 @@ function generateDispatchModule(apps: DispatchApp[]): string {return ` '${app.appKey}': ({ data }) => <${view_component} ${view_prop}={data as ${data_type}} />,`}if (app.type === 'custom') {- const { data_type, view_component, view_prop, link_prop } = app.config.render_ui+ const { data_type, view_component, view_prop, link_prop, app_prop } = app.config.render_uiconst dataExpression = data_type ? `data as ${data_type}` : 'data'- const args = link_prop ? 'data, openLink' : 'data'- const extraProps = link_prop ? ` ${link_prop}={openLink}` : ''+ const args = ['data', ...(link_prop ? ['openLink'] : []), ...(app_prop ? ['app'] : [])].join(', ')+ const extraProps = `${link_prop ? ` ${link_prop}={openLink}` : ''}${app_prop ? ` ${app_prop}={app}` : ''}`return ` '${app.appKey}': ({ ${args} }) => <${view_component} ${view_prop}={${dataExpression}}${extraProps} />,`}const pascalName = kebabToPascal(app.appKey)diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.tsindex c4c85ce9a340..5cb4ed06e5a6 100644--- a/services/mcp/scripts/yaml-config-schema.ts+++ b/services/mcp/scripts/yaml-config-schema.ts@@ -483,6 +483,8 @@ const CustomUiAppSchema = zdata_type: z.string().optional(),/** Prop name that receives the host's link opener, for a view that opens links. */link_prop: z.string().optional(),+ /** Prop name that receives the host app, for a view that calls server tools. */+ app_prop: z.string().optional(),}).strict().optional(),@@ -533,6 +535,7 @@ export interface ResolvedCustomUiApp {view_prop: stringdata_type?: stringlink_prop?: string+ app_prop?: string}}diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.tsindex 4015578f6d4b..6899154723db 100644--- a/services/mcp/src/hono/tool-catalog.ts+++ b/services/mcp/src/hono/tool-catalog.ts@@ -20,6 +20,7 @@ interface PreBuiltTool {build: () => ToolBase<ZodObjectAny>meta: ToolBase<ZodObjectAny>['_meta']rawInputSchema: ToolBase<ZodObjectAny>['rawInputSchema']+ renderedNote?: ToolBase<ZodObjectAny>['renderedNote']definition: ToolDefinition | undefined}@@ -128,6 +129,7 @@ export class ToolCatalog {build: factory,meta: base._meta,rawInputSchema: base.rawInputSchema,+ renderedNote: base.renderedNote,definition: defs[name],})}@@ -223,6 +225,7 @@ export class ToolCatalog {handler: (context, params) => preBuilt.build().handler(context, params),...(preBuilt.rawInputSchema ? { rawInputSchema: preBuilt.rawInputSchema } : {}),...(preBuilt.meta ? { _meta: preBuilt.meta } : {}),+ ...(preBuilt.renderedNote ? { renderedNote: preBuilt.renderedNote } : {}),title: definition.title,description: definition.description,scopes: definition.required_scopes ?? [],diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.tsindex a8148ffeccfc..990203bd81cd 100644--- a/services/mcp/src/resources/ui-apps.generated.ts+++ b/services/mcp/src/resources/ui-apps.generated.ts@@ -12,6 +12,7 @@ export const ERROR_ISSUE_LIST_RESOURCE_URI = 'ui://posthog/error-issue-list.htmlexport const EXPERIMENT_RESOURCE_URI = 'ui://posthog/experiment.html'export const EXPERIMENT_LIST_RESOURCE_URI = 'ui://posthog/experiment-list.html'export const EXPERIMENT_RESULTS_RESOURCE_URI = 'ui://posthog/experiment-results.html'+export const EXPLAIN_CHART_RESOURCE_URI = 'ui://posthog/explain-chart.html'export const FEATURE_FLAG_RESOURCE_URI = 'ui://posthog/feature-flag.html'export const FEATURE_FLAG_LIST_RESOURCE_URI = 'ui://posthog/feature-flag-list.html'export const FEATURE_FLAG_TESTING_RESOURCE_URI = 'ui://posthog/feature-flag-testing.html'@@ -48,6 +49,7 @@ export type UiAppKey =| 'experiment'| 'experiment-list'| 'experiment-results'+ | 'explain-chart'| 'feature-flag'| 'feature-flag-list'| 'feature-flag-testing'@@ -84,6 +86,7 @@ export const URI_MAP: Record<UiAppKey, string> = {experiment: EXPERIMENT_RESOURCE_URI,'experiment-list': EXPERIMENT_LIST_RESOURCE_URI,'experiment-results': EXPERIMENT_RESULTS_RESOURCE_URI,+ 'explain-chart': EXPLAIN_CHART_RESOURCE_URI,'feature-flag': FEATURE_FLAG_RESOURCE_URI,'feature-flag-list': FEATURE_FLAG_LIST_RESOURCE_URI,'feature-flag-testing': FEATURE_FLAG_TESTING_RESOURCE_URI,@@ -124,6 +127,7 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = ['experiment','experiment-list','experiment-results',+ 'explain-chart','feature-flag','feature-flag-list','feature-flag-testing',@@ -224,6 +228,12 @@ export const UI_APPS: Array<{description: 'Experiment Results detail view',appDir: 'generated/experiment-results',},+ {+ name: 'PostHog Chart Walkthrough',+ uri: EXPLAIN_CHART_RESOURCE_URI,+ description: 'A trends chart with the moments that stand out highlighted, explained one chapter at a time.',+ appDir: 'explain-chart',+ },{name: 'PostHog Feature Flag',uri: FEATURE_FLAG_RESOURCE_URI,diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 568628cbb61b..61e62c5f0e0c 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -573,6 +573,108 @@ export const InsightQueryInputSchema = z.preprocess(}))+const ExplainChartEvidenceSchema = z.object({+ text: z+ .string()+ .min(1)+ .max(400)+ .describe(+ 'One finding in one sentence, with the numbers from the query that found it. Mark the name that matters with **double asterisks**.'+ ),+ query: z+ .record(z.string(), z.unknown())+ .optional()+ .describe(+ 'The query that found this, as you ran it (for example a TrendsQuery with a breakdown). It becomes a link to that chart, and a TrendsQuery also draws as a chart in the walkthrough.'+ ),+ url: z+ .string()+ .url()+ .startsWith('https://')+ .optional()+ .describe('A link to the source when it is not a query, for example a commit, a pull request or a deploy.'),+})++const ExplainChartChapterSchema = z.object({+ title: z+ .string()+ .min(1)+ .max(80)+ .describe('A short title, for example "A spike on October 2" or "Lower since September 28".'),+ start: z+ .string()+ .min(1)+ .describe(+ "The first point the chapter covers, copied from the chart's `days` (for example `2026-10-02`, or `2026-10-02 14:00:00` on an hourly chart)."+ ),+ end: z+ .string()+ .min(1)+ .optional()+ .describe('The last point the chapter covers, inclusive. Omit it when the chapter is about one point.'),+ summary: z+ .string()+ .max(400)+ .optional()+ .describe(+ "What happened, in one or two sentences. Do not repeat the chart's own numbers: the app works them out from the chart and shows them above this."+ ),+ cause: z+ .string()+ .max(600)+ .optional()+ .describe(+ 'The most likely cause, in one or two sentences. Say whether it is a real change in behavior or an artifact of the data. Wrap the name behind it, such as a referrer or a country, in **double asterisks**. Omit it when you found no cause.'+ ),+ confidence: z+ .enum(['high', 'medium', 'low'])+ .optional()+ .describe(+ 'How sure you are of the cause. high: independent signals agree. medium: one signal, or a strong pattern without a cross-check. low: a guess.'+ ),+ confidence_reason: z.string().max(200).optional().describe('Why you gave that confidence, in one sentence.'),+ evidence: z.array(ExplainChartEvidenceSchema).max(6).optional().describe('What you checked, at most 6 findings.'),+})++export const ExplainChartInputSchema = z.preprocess(+ normalizeParamAliases({ insightId: ['id', 'insight_id', 'short_id', 'shortId'] }),+ z+ .object({+ insightId: z+ .union([z.string(), z.number()])+ .optional()+ .describe('The saved insight to explain: its numeric `id` or 8-character `short_id`.'),+ query: z+ .record(z.string(), z.unknown())+ .optional()+ .describe('A TrendsQuery to explain when the chart is not a saved insight. Pass this or `insightId`.'),+ series: z+ .number()+ .int()+ .min(0)+ .optional()+ .default(0)+ .describe(+ "Index of the series in the chart's results that the story follows. Defaults to the first one."+ ),+ headline: z+ .string()+ .min(1)+ .max(300)+ .describe(+ 'One sentence a person could read in place of the whole story. Name what stands out, with no numbers, and wrap each name behind a moment, such as the referrer of a spike or the country behind a rise, in **double asterisks**.'+ ),+ chapters: z+ .array(ExplainChartChapterSchema)+ .min(1)+ .max(8)+ .describe('The moments that stand out, in the order to read them. At most 8.'),+ })+ .refine((params) => (params.insightId === undefined) !== (params.query === undefined), {+ message: 'Pass exactly one of `insightId` or `query`.',+ })+)+export const AIObservabilityGetCostsSchema = z.object({projectId: z.number()diff --git a/services/mcp/src/templates/render-ui-prompt.md b/services/mcp/src/templates/render-ui-prompt.mdindex 793cee496a45..2ff14e96bc02 100644--- a/services/mcp/src/templates/render-ui-prompt.md+++ b/services/mcp/src/templates/render-ui-prompt.md@@ -1,4 +1,4 @@-Render an interactive, explorable PostHog visualization for the user. Strongly prefer rendering whenever your answer centers on an analytics query, specific entity, or list that has a UI app — a trends or funnel result, experiment (or its results), survey (or its stats), cohort, action, error-tracking issue, session recording, trace, or workflow, plus the list view for most — so the user can see and verify it, not just read a text summary. Render in addition to your written summary, not instead of it, and not only when the user explicitly asks to "see" something.+Render an interactive, explorable PostHog visualization for the user. Strongly prefer rendering whenever your answer centers on an analytics query, specific entity, or list that has a UI app — a trends or funnel result, experiment (or its results), survey (or its stats), cohort, action, error-tracking issue, session recording, trace, or workflow, plus the list view for most — so the user can see and verify it, not just read a text summary. Render in addition to your written summary, not instead of it, and not only when the user explicitly asks to "see" something. The exception is an app that carries the whole answer: its render result says what your reply may still add, and nothing else goes in the reply.If the query result or harness explicitly says the user already sees an interactive view, keep your written conclusion and do not render the same result again. A UI resource on a query tool does not by itself establish that an exec call displayed the chart. Rendering is independent of query selection: keep typed runners for supported analytics, even when this separate presentation step is needed.diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex e8d64509b1ae..3d42da751afc 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -16,6 +16,7 @@ import featureFlagGetDefinitionByKey from './featureFlags/getDefinitionByKey'import submitFeedback from './feedback/submit'// Generated tools (from definitions/*.yaml)import { GENERATED_TOOL_MAP } from './generated'+import explainChart from './insights/explainChart'// Insightsimport queryInsight from './insights/query'import insightTrustCheck from './insights/trustCheck'@@ -100,6 +101,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// Insights'insight-query': queryInsight,'insight-trust-check': insightTrustCheck,+ 'explain-chart': explainChart,// Links (utility — canonical app URLs so the model never hand-builds/mis-slugs entity links)'generate-app-url': generateAppUrl,diff --git a/services/mcp/src/tools/insights/explainChart.ts b/services/mcp/src/tools/insights/explainChart.tsnew file mode 100644index 000000000000..25b68fa27539--- /dev/null+++ b/services/mcp/src/tools/insights/explainChart.ts@@ -0,0 +1,209 @@+import type { z } from 'zod'++import { wrapError } from '@/lib/errors'+import { withUiApp } from '@/resources/ui-apps'+import { ExplainChartInputSchema } from '@/schema/tool-inputs'+import { GENERATED_TOOLS } from '@/tools/generated/query-wrappers'+import { applyProjectTestAccountDefault } from '@/tools/query-wrapper-factory'+import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type ToolBase } from '@/tools/types'++import type {+ ExplainChartData,+ StoryChapter,+ StorySeriesResult,+ StoryTrendsQuery,+} from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'++import { analyzeQuery } from '../shared'+import { findStoryRange, lastBucketInProgress } from './storyRanges'++const schema = ExplainChartInputSchema++type Params = z.infer<typeof schema>++type Result = ExplainChartData & { [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: string }++const RENDERED_NOTE =+ 'The person sees the walkthrough rendered inline: the chart, every chapter, each cause and each piece of evidence. Do not write any of that again in any form, not as a recap, a bullet list or a summary of the moments. Your whole reply is at most three short sentences: which chapter to start with, one caveat the walkthrough cannot show if there is one, and one next step you offer. If the person says the walkthrough did not load, give the findings in text.'++// The markers sit on one value over time. These displays draw that as they are.+const TIME_SERIES_DISPLAYS = new Set([+ 'ActionsLineGraph',+ 'ActionsLineGraphCumulative',+ 'ActionsBar',+ 'ActionsUnstackedBar',+ 'ActionsAreaGraph',+ 'ActionsStackedBar',+])++// These show a total over the range, so the walkthrough draws the line behind it. Any other display is refused.+const TOTAL_DISPLAYS = new Set([+ 'Auto',+ 'BoldNumber',+ 'Metric',+ 'ActionsPie',+ 'ActionsDonut',+ 'ActionsProportionBar',+ 'ActionsBarValue',+ 'ActionsTable',+ 'WorldMap',+ 'CalendarHeatmap',+ 'SlopeGraph',+])++const NOT_TRENDS = 'This tool only explains trends charts. For other kinds, write the explanation in the chat instead.'+const NOT_OVER_TIME =+ 'This tool explains a trends chart that shows one value over time, and this chart does not. Write the explanation in the chat instead.'++// The walkthrough redraws evidence through `query-trends`, whose schema is narrower than a TrendsQuery's, so evidence+// it would refuse keeps its link and no chart.+const redrawSchema = GENERATED_TOOLS['query-trends']!().schema++interface StoryChart {+ query: StoryTrendsQuery+ insightName: string | null+ path: string+}++function asTrendsQuery(query: unknown): StoryTrendsQuery {+ const inner = analyzeQuery(query).innerQuery+ if (inner?.kind !== 'TrendsQuery') {+ throw new Error(NOT_TRENDS)+ }+ const trends = { ...inner } as StoryTrendsQuery+ const display = trends.trendsFilter?.display+ if (typeof display !== 'string' || TIME_SERIES_DISPLAYS.has(display)) {+ return trends+ }+ if (!TOTAL_DISPLAYS.has(display)) {+ throw new Error(NOT_OVER_TIME)+ }+ trends.trendsFilter = { ...trends.trendsFilter, display: 'ActionsLineGraph' }+ return trends+}++function newInsightPath(query: Record<string, unknown>): string {+ const kind = query.kind+ const node =+ kind === 'HogQLQuery'+ ? { kind: 'DataVisualizationNode', source: query }+ : typeof kind === 'string' && kind.endsWith('Node')+ ? query+ : { kind: 'InsightVizNode', source: query }+ return `/insights/new#q=${encodeURIComponent(JSON.stringify(node))}`+}++async function loadChart(context: Context, projectId: string, params: Params): Promise<StoryChart> {+ if (params.insightId === undefined) {+ const query = asTrendsQuery(params.query)+ await applyProjectTestAccountDefault(context, query)+ return { query, insightName: null, path: newInsightPath(query) }+ }+ const insight = await context.api.insights({ projectId }).get({ insightId: params.insightId })+ if (!insight.success) {+ throw wrapError(`Failed to get insight: ${insight.error.message}`, insight.error)+ }+ return {+ query: asTrendsQuery(insight.data.query),+ insightName: insight.data.name || insight.data.derived_name || null,+ path: `/insights/${insight.data.short_id}`,+ }+}++function warningMessages(warnings: unknown[]): string[] {+ return warnings.map((warning) =>+ typeof warning === 'string' ? warning : ((warning as { message?: string }).message ?? JSON.stringify(warning))+ )+}++function describeResult(+ chart: StoryChart,+ series: StorySeriesResult,+ chapters: Params['chapters'],+ missed: string[],+ warnings: unknown[]+): string {+ const name = chart.insightName ?? series.label ?? 'the chart'+ const lines = [`The walkthrough of "${name}" has ${chapters.length} chapters.`]+ if (warnings.length) {+ lines.push(`The query came with warnings the person should hear about: ${warningMessages(warnings).join(' ')}`)+ }+ if (missed.length) {+ lines.push(+ `No point on the chart matches the dates of ${missed.map((title) => `"${title}"`).join(', ')}, so ${+ missed.length === 1 ? 'that chapter shows' : 'those chapters show'+ } without a highlight. Use dates from the chart's \`days\` and call this tool again.`+ )+ }+ return lines.join(' ')+}++export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = async (+ context: Context,+ params: Params+) => {+ const projectId = await context.stateManager.getProjectId()+ const chart = await loadChart(context, projectId, params)++ const response = await context.api.query({ projectId }).runQuery({ query: chart.query })+ const results = (Array.isArray(response.results) ? response.results : []) as StorySeriesResult[]+ const series = results[params.series]+ if (!series?.data?.length) {+ throw new Error(+ results.length+ ? `The chart has ${results.length} series, so \`series\` must be below ${results.length}.`+ : 'The chart has no data to explain.'+ )+ }++ const baseUrl = context.api.getProjectBaseUrl(projectId)+ const interval = chart.query.interval ?? 'day'+ const { timezone, warnings = [] } = response as { timezone?: string; warnings?: unknown[] | null }+ const missed: string[] = []+ const chapters: StoryChapter[] = params.chapters.map((chapter) => {+ const range = findStoryRange(series.days ?? [], interval, chapter.start, chapter.end)+ if (!range) {+ missed.push(chapter.title)+ }+ return {+ title: chapter.title,+ range,+ summary: chapter.summary ?? null,+ cause: chapter.cause ?? null,+ confidence: chapter.confidence ?? null,+ confidenceReason: chapter.confidence_reason ?? null,+ evidence: (chapter.evidence ?? []).map((item) => ({+ text: item.text,+ url: item.query ? `${baseUrl}${newInsightPath(item.query)}` : (item.url ?? null),+ query: item.query && redrawSchema.safeParse(item.query).success ? item.query : null,+ })),+ }+ })++ return {+ query: chart.query,+ results,+ seriesIndex: params.series,+ insightName: chart.insightName,+ lastPointInProgress: lastBucketInProgress(series.days ?? [], interval, timezone),+ ...(warnings?.length ? { warnings } : {}),+ headline: params.headline,+ chapters,+ _posthogUrl: `${baseUrl}${chart.path}`,+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: describeResult(+ chart,+ series,+ params.chapters,+ missed,+ warnings ?? []+ ),+ }+}++export default (): ToolBase<typeof schema, Result> =>+ withUiApp('explain-chart', {+ name: 'explain-chart',+ schema,+ renderedNote: RENDERED_NOTE,+ handler: explainChartHandler,+ })diff --git a/services/mcp/src/tools/insights/storyRanges.ts b/services/mcp/src/tools/insights/storyRanges.tsnew file mode 100644index 000000000000..98b3842eac75--- /dev/null+++ b/services/mcp/src/tools/insights/storyRanges.ts@@ -0,0 +1,136 @@+const UNIT_MS: Record<string, number> = {+ second: 1_000,+ minute: 60_000,+ hour: 3_600_000,+ day: 86_400_000,+ week: 7 * 86_400_000,+}++// Agents copy dates in several shapes: `2026-10-02`, `2026-10-02 14:00:00`, `2026-10-02T14:00:00Z`.+function pointKey(value: string): string {+ return value+ .trim()+ .replace('T', ' ')+ .replace(/(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/, '')+}++// A day matches every hour in it, and an hour matches the day it falls on.+function sameMoment(key: string, date: string): boolean {+ const length = Math.min(key.length, date.length)+ return key.slice(0, length) === date.slice(0, length)+}++function lastIndexWhere(keys: string[], test: (key: string) => boolean): number {+ for (let index = keys.length - 1; index >= 0; index--) {+ if (test(keys[index]!)) {+ return index+ }+ }+ return -1+}++/** The point's wall-clock time as if it were UTC. Labels carry no zone, so this keeps their calendar fields intact. */+function naiveMs(key: string): number | null {+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(key)+ if (!match) {+ return null+ }+ const [, year, month, day, hour, minute, second] = match+ return Date.UTC(+ Number(year),+ Number(month) - 1,+ Number(day),+ Number(hour ?? 0),+ Number(minute ?? 0),+ Number(second ?? 0)+ )+}++/** When the bucket that starts at `key` ends, on the same naive clock. */+function bucketEndMs(key: string, interval: string): number | null {+ const start = naiveMs(key)+ if (start === null) {+ return null+ }+ const date = new Date(start)+ if (interval === 'month') {+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1)+ }+ if (interval === 'quarter') {+ return Date.UTC(date.getUTCFullYear(), Math.floor(date.getUTCMonth() / 3) * 3 + 3, 1)+ }+ if (interval === 'year') {+ return Date.UTC(date.getUTCFullYear() + 1, 0, 1)+ }+ return start + (UNIT_MS[interval] ?? UNIT_MS.day!)+}++const CALENDAR_INTERVALS = new Set(['week', 'month', 'quarter', 'year'])++function startIndex(keys: string[], date: string, interval: string): number | null {+ const exact = keys.findIndex((key) => sameMoment(key, date))+ if (exact !== -1) {+ return exact+ }+ if (date < keys[0]!) {+ return 0+ }+ if (!CALENDAR_INTERVALS.has(interval)) {+ return null+ }+ // On a weekly or longer chart, a date falls in the bucket that starts before it.+ const containing = lastIndexWhere(keys, (key) => key < date)+ const end = bucketEndMs(keys[containing]!, interval)+ const dateMs = naiveMs(date)+ const isPastLastBucket = containing === keys.length - 1 && (end === null || dateMs === null || dateMs >= end)+ return isPastLastBucket ? null : containing+}++function endIndex(keys: string[], date: string): number | null {+ const exact = lastIndexWhere(keys, (key) => sameMoment(key, date))+ if (exact !== -1) {+ return exact+ }+ const containing = lastIndexWhere(keys, (key) => key < date)+ return containing === -1 ? null : containing+}++/** The inclusive range of points that a chapter's dates cover, or null when they cover none of the chart. */+export function findStoryRange(days: string[], interval: string, start: string, end?: string): [number, number] | null {+ if (!days.length) {+ return null+ }+ const keys = days.map(pointKey)+ const first = startIndex(keys, pointKey(start), interval)+ const last = endIndex(keys, pointKey(end ?? start))+ if (first === null || last === null || last < first) {+ return null+ }+ return [first, last]+}++function zoneOffsetMs(timezone: string, utcMs: number): number {+ try {+ const name = new Intl.DateTimeFormat('en-US', { timeZone: timezone, timeZoneName: 'longOffset' })+ .formatToParts(new Date(utcMs))+ .find((part) => part.type === 'timeZoneName')?.value+ const match = /GMT([+-])(\d{2}):?(\d{2})?/.exec(name ?? '')+ if (!match) {+ return 0+ }+ return (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3] ?? 0)) * 60_000+ } catch {+ return 0+ }+}++export function lastBucketInProgress(days: string[], interval: string, timezone = 'UTC', now = Date.now()): boolean {+ const last = days[days.length - 1]+ const end = last === undefined ? null : bucketEndMs(pointKey(last), interval)+ if (end === null) {+ return false+ }+ // The offset belongs to the instant the bucket ends, which a second lookup finds across a daylight-saving change.+ const guess = end - zoneOffsetMs(timezone, end)+ return end - zoneOffsetMs(timezone, guess) > now+}diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex b33ccffb2015..cd7baaa7a5fa 100644--- a/services/mcp/src/tools/query-wrapper-factory.ts+++ b/services/mcp/src/tools/query-wrapper-factory.ts@@ -100,6 +100,19 @@ function withoutTestAccountFilterDefault<T extends ZodObjectAny>(schema: T): T {}) as unknown as T}+/** Fills an omitted `filterTestAccounts` from the project's default, the way the UI does for a new insight. */+export async function applyProjectTestAccountDefault(context: Context, query: Record<string, unknown>): Promise<void> {+ if (query[TEST_ACCOUNT_FILTER_FIELD] !== undefined) {+ return+ }+ const project = await context.stateManager.getCachedOrFetchProject().catch(() => undefined)+ // Only inject `true`: when the project default is unchecked the field+ // stays omitted and the backend's own `false` default applies.+ if (project?.test_account_filters_default_checked) {+ query[TEST_ACCOUNT_FILTER_FIELD] = true+ }+}+/*** Kea Router decodes paths before route matching, and scenes decode captured parameters again.* Double encoding keeps opaque values within the route matcher character set through both steps.@@ -183,13 +196,8 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC...queryParams,kind: config.kind,}- if (hasTestAccountFilterField(schema) && query[TEST_ACCOUNT_FILTER_FIELD] === undefined) {- const project = await context.stateManager.getCachedOrFetchProject().catch(() => undefined)- // Only inject `true`: when the project default is unchecked the field- // stays omitted and the backend's own `false` default applies.- if (project?.test_account_filters_default_checked) {- query[TEST_ACCOUNT_FILTER_FIELD] = true- }+ if (hasTestAccountFilterField(schema)) {+ await applyProjectTestAccountDefault(context, query)}const baseUrl = context.api.getProjectBaseUrl(projectId)const effectiveOutputFormat = callerOutputFormat ?? config.outputFormatdiff --git a/services/mcp/src/tools/render-ui.ts b/services/mcp/src/tools/render-ui.tsindex c66ce7027aa0..e8fa8c435ff3 100644--- a/services/mcp/src/tools/render-ui.ts+++ b/services/mcp/src/tools/render-ui.ts@@ -111,7 +111,14 @@ export function createRenderUiTool(const distinctId = await context.getDistinctId()const payload: ToolResultPayload = {- content: [{ type: 'text', text: `Rendering the ${tool.name} visualization for the user.` }],+ content: [+ {+ type: 'text',+ text: [`Rendering the ${tool.name} visualization for the user.`, tool.renderedNote]+ .filter(Boolean)+ .join(' '),+ },+ ],structuredContent: {tool_name: tool.name,tool_input: toolInput,diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.tsindex b02fd8dd8fdf..fcfbe9b4bf13 100644--- a/services/mcp/src/tools/types.ts+++ b/services/mcp/src/tools/types.ts@@ -177,6 +177,8 @@ export type Tool<TSchema extends z.ZodType = z.ZodType, TResult = unknown> = {readOnlyHint: boolean}_meta?: ToolMeta+ /** Appended to the `render-ui` result so the model knows what the rendered app already shows. */+ renderedNote?: string}export type ToolBase<TSchema extends z.ZodType = z.ZodType, TResult = unknown> = Omit<diff --git a/services/mcp/src/ui-apps/apps/explain-chart.tsx b/services/mcp/src/ui-apps/apps/explain-chart.tsxnew file mode 100644index 000000000000..abd8f81cb59c--- /dev/null+++ b/services/mcp/src/ui-apps/apps/explain-chart.tsx@@ -0,0 +1,19 @@+import '../styles/tailwind.css'++import { createRoot } from 'react-dom/client'++import { AppWrapper } from '../components/AppWrapper'+import { ExplainChart, type ExplainChartData } from '../components/ExplainChart'++function ExplainChartApp(): JSX.Element {+ return (+ <AppWrapper<ExplainChartData> appName="PostHog Chart Walkthrough">+ {({ data, openLink, app }) => <ExplainChart data={data!} openLink={openLink} app={app} />}+ </AppWrapper>+ )+}++const container = document.getElementById('root')+if (container) {+ createRoot(container).render(<ExplainChartApp />)+}diff --git a/services/mcp/src/ui-apps/components/ExplainChart.tsx b/services/mcp/src/ui-apps/components/ExplainChart.tsxnew file mode 100644index 000000000000..ddc7f17cd212--- /dev/null+++ b/services/mcp/src/ui-apps/components/ExplainChart.tsx@@ -0,0 +1,85 @@+import type { App } from '@modelcontextprotocol/ext-apps'+import { type ReactElement, useEffect, useMemo } from 'react'++import { Card, CardContent } from '@posthog/quill'+import { buildYTickFormatter } from '@posthog/quill-charts'++import { trendsFilterToYFormatterConfig } from 'products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat'+import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'+import { ExplainChartView } from 'products/product_analytics/mcp/apps/explainChart/ExplainChartView'++import { capture } from '../analytics/posthog'+import { useEvidenceCharts } from '../hooks/useEvidenceCharts'+import { TrendsVisualizer } from './TrendsVisualizer'+import type { TrendsQuery, TrendsResult } from './types'++// The render-ui dispatch imports the data type from this module.+export type { ExplainChartData }++const CHART_CLASS_NAME = 'h-[260px] @3xl/story:h-[400px]'++export interface ExplainChartProps {+ data: ExplainChartData+ openLink: (url: string) => void+ /** The host app, which runs each piece of evidence's query so the walkthrough can draw it. */+ app?: App | null+}++export function ExplainChart({ data, openLink, app = null }: ExplainChartProps): ReactElement {+ const query = data.query as unknown as TrendsQuery+ const evidenceCharts = useEvidenceCharts(app, CHART_CLASS_NAME)++ useEffect(() => {+ capture('mcp_ui_app_explain_chart_viewed', {+ chapter_count: data.chapters.length,+ unmatched_chapter_count: data.chapters.filter((chapter) => !chapter.range).length,+ })+ }, [data])++ // A number in a sentence reads better in full, so the chart's axis format is only used when it adds a unit.+ const formatValue = useMemo(() => {+ const {+ aggregationAxisFormat: format,+ aggregationAxisPrefix,+ aggregationAxisPostfix,+ } = query.trendsFilter ?? {}+ return (format && format !== 'numeric') || aggregationAxisPrefix || aggregationAxisPostfix+ ? buildYTickFormatter(trendsFilterToYFormatterConfig(query.trendsFilter, false))+ : undefined+ }, [query])++ return (+ <Card>+ <CardContent>+ <ExplainChartView+ // The host updates `data` in place, so key on the story to start each new one at its summary.+ key={`${JSON.stringify(data.query)}:${data.headline}`}+ data={data}+ title={data.insightName ?? 'Trends'}+ renderChart={(overlay) => (+ <TrendsVisualizer+ query={query}+ results={data.results as TrendsResult}+ title={data.insightName ?? 'Trends'}+ overlay={overlay}+ showControls={false}+ chartClassName={CHART_CLASS_NAME}+ showTitle={false}+ />+ )}+ openLink={openLink}+ formatValue={formatValue}+ evidenceCharts={evidenceCharts}+ onPageChange={({ index, fromIndex, source }) =>+ capture('mcp_ui_app_explain_chart_page_viewed', {+ page_index: index,+ from_page_index: fromIndex,+ page_count: data.chapters.length + 1,+ source,+ })+ }+ />+ </CardContent>+ </Card>+ )+}diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsxindex bd6faba2a8d0..7ed5ecefab30 100644--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx@@ -29,7 +29,7 @@ import {import { captureInsightDisplayChanged } from '../analytics/posthog'import { ChartHeader } from './ChartHeader'import { BigNumber, Select } from './charts'-import { colorAt, useMcpChartTheme } from './charts/theme'+import { colorAt, fadedColorAt, useMcpChartTheme } from './charts/theme'import { ChartSettings } from './ChartSettings'import {type ChartType,@@ -57,6 +57,8 @@ const SLOPE_TYPE_OPTION = { value: 'slope' as const, label: 'Slope' }const TOOLTIP_CONFIG = { pinnable: true, placement: 'cursor' as const }+const LEGEND_CONFIG = { show: true, position: 'bottom' } as const+// DefaultTooltip shows the raw x label; format it like the axis.const renderDateTooltip = (ctx: TooltipContext): ReactElement => (<DefaultTooltip {...ctx} label={formatTooltipDate(ctx.label)} />@@ -85,6 +87,8 @@ export function TrendsVisualizer({showControls = true,chartClassName = 'h-[400px]',showTitle = true,+ showLegend = false,+ highlightedSeries,}: TrendsVisualizerProps): ReactElement {const displayType = getDisplayType(query)const [chartType, setChartType] = useState<ChartType>(defaultChartType(displayType))@@ -193,6 +197,8 @@ export function TrendsVisualizer({}const chartTypeOptions = slopeAvailable ? [...CHART_TYPE_OPTIONS, SLOPE_TYPE_OPTION] : CHART_TYPE_OPTIONS+ const seriesColor = (index: number): string =>+ highlightedSeries?.length && !highlightedSeries.includes(index) ? fadedColorAt(index) : colorAt(index)// Area auto-stacks, so derived overlays would draw against the stacked totals — disable them.const derivedSeriesDisabled = effectiveType === 'area'const isPercentStackView = chartConfig.percentStack && supportsPercentStack(effectiveType)@@ -222,7 +228,7 @@ export function TrendsVisualizer({}if (isBarFamily(effectiveType)) {const { series, config } = buildTrendsBarChartModel(trendResults, {- getColor: (_, index) => colorAt(index),+ getColor: (_, index) => seriesColor(index),labels,trendsFilter: effectiveTrendsFilter,isPercentStackView,@@ -236,7 +242,7 @@ export function TrendsVisualizer({series={series}labels={labels}theme={theme}- config={config}+ config={showLegend ? { ...config, legend: LEGEND_CONFIG } : config}tooltip={renderDateTooltip}>{overlay}@@ -245,7 +251,7 @@ export function TrendsVisualizer({}const series = buildTrendsSeries(trendResults, {isArea: effectiveType === 'area',- getColor: (_, index) => colorAt(index),+ getColor: (_, index) => seriesColor(index),})const config = buildTrendsLineTimeSeriesConfig({results: trendResults,@@ -265,7 +271,7 @@ export function TrendsVisualizer({series={series}labels={labels}theme={theme}- config={config}+ config={showLegend ? { ...config, legend: LEGEND_CONFIG } : config}tooltip={renderDateTooltip}>{overlay}diff --git a/services/mcp/src/ui-apps/components/charts/theme.ts b/services/mcp/src/ui-apps/components/charts/theme.tsindex e416b52a3fd7..fd354a9f6452 100644--- a/services/mcp/src/ui-apps/components/charts/theme.ts+++ b/services/mcp/src/ui-apps/components/charts/theme.ts@@ -30,6 +30,9 @@ export const CHART_COLORS = [// Picks a palette color by index, wrapping when there are more series than colors.export const colorAt = (index: number): string => CHART_COLORS[index % CHART_COLORS.length]!+// The palette's hex with a quarter opacity, for a series pushed into the background.+export const fadedColorAt = (index: number): string => `${colorAt(index)}40`+// Single brand blue for every funnel step's converted bar — the bar height already encodes// conversion, so distinct per-step colors would only add noise.export const FUNNEL_COLOR = '#1d4aff'diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.tsindex e7b2f5d1e334..42a1fbb6c989 100644--- a/services/mcp/src/ui-apps/components/types.ts+++ b/services/mcp/src/ui-apps/components/types.ts@@ -103,6 +103,7 @@ export interface TrendsResultItem {count?: numberaggregated_value?: numbercompare_label?: string+ breakdown_value?: string | number | (string | number)[]/** Slope graph only: the last bucket is the current, still-accumulating period (set by the* backend SlopeGraphTrendsQueryRunner) so the slope dashes the provisional end like the insight. */incomplete_end?: boolean@@ -228,6 +229,9 @@ export interface TrendsVisualizerProps {showControls?: booleanchartClassName?: stringshowTitle?: boolean | 'axis'+ showLegend?: boolean+ /** Indexes of the series a line or bar chart draws in full colour, fading the rest. */+ highlightedSeries?: number[]}export interface FunnelVisualizerProps {diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsxindex ea1692786b4c..02bc7513aea2 100644--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx@@ -62,6 +62,7 @@ import {import type { UiAppKey } from '../../resources/ui-apps.generated'import { Component } from '../components/Component'+import { ExplainChart, type ExplainChartData } from '../components/ExplainChart'export interface RenderDispatchProps {data: unknown@@ -429,6 +430,9 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchProexperiment: ({ data }) => <ExperimentView experiment={data as ExperimentData} />,'experiment-list': ({ data, app }) => <ExperimentListContent data={data as ExperimentListData} app={app} />,'experiment-results': ({ data }) => <ExperimentResultsView data={data as ExperimentResultsData} />,+ 'explain-chart': ({ data, openLink, app }) => (+ <ExplainChart data={data as ExplainChartData} openLink={openLink} app={app} />+ ),'feature-flag': ({ data }) => <FeatureFlagView flag={data as FeatureFlagData} />,'feature-flag-list': ({ data, app }) => <FeatureFlagListContent data={data as FeatureFlagListData} app={app} />,'feature-flag-testing': ({ data }) => <FeatureFlagTestingView flag={data as FeatureFlagTestingData} />,diff --git a/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsx b/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsxnew file mode 100644index 000000000000..bb453900f596--- /dev/null+++ b/services/mcp/src/ui-apps/hooks/useEvidenceCharts.tsx@@ -0,0 +1,129 @@+import type { App } from '@modelcontextprotocol/ext-apps'+import { useCallback, useMemo, useRef, useState } from 'react'++import { Button, Text } from '@posthog/quill'++import type { StoryEvidenceCharts } from 'products/product_analytics/mcp/apps/explainChart/ExplainChartView'+import { isSeriesNamedIn } from 'products/product_analytics/mcp/apps/explainChart/storyNamedSeries'++import { capture } from '../analytics/posthog'+import { loadRenderUiData } from '../apps/render-ui-data'+import { AppLoadingState } from '../components/AppLoadingState'+import { TrendsVisualizer } from '../components/TrendsVisualizer'+import type { TrendsQuery, TrendsResult, TrendsResultItem } from '../components/types'+import { getSeriesLabel } from '../components/utils'++type EvidenceChart =+ | { status: 'loading' }+ | { status: 'error' }+ | { status: 'ready'; query: TrendsQuery; results: TrendsResult }++function seriesNames(item: TrendsResultItem, index: number): string[] {+ return [getSeriesLabel(item, index), ...[item.breakdown_value ?? []].flat().map(String)]+}++function isTrendsQuery(query: Record<string, unknown>): boolean {+ return query.kind === 'TrendsQuery' || (query.kind === undefined && Array.isArray(query.series))+}++export function useEvidenceCharts(app: App | null, chartClassName: string): StoryEvidenceCharts | undefined {+ const [charts, setCharts] = useState<Record<string, EvidenceChart>>({})+ const requested = useRef(new Set<string>())++ const load = useCallback(+ (query: Record<string, unknown>): void => {+ const key = JSON.stringify(query)+ if (!app || requested.current.has(key)) {+ return+ }+ requested.current.add(key)+ setCharts((current) => ({ ...current, [key]: { status: 'loading' } }))+ const settle = (chart: EvidenceChart): void => {+ if (chart.status === 'error') {+ // A later click on "Show chart" tries again.+ requested.current.delete(key)+ }+ setCharts((current) => ({ ...current, [key]: chart }))+ }+ loadRenderUiData(app, 'query-trends', query, 'query-results').then(+ (result) => {+ const payload = result.structuredContent as+ | { query?: TrendsQuery; results?: TrendsResult }+ | undefined+ settle(+ !result.isError && payload?.results?.length+ ? {+ status: 'ready',+ query: payload.query ?? (query as unknown as TrendsQuery),+ results: payload.results,+ }+ : { status: 'error' }+ )+ },+ () => settle({ status: 'error' })+ )+ },+ [app]+ )++ const prefetch = useCallback(+ (queries: Record<string, unknown>[]): void => queries.filter(isTrendsQuery).forEach(load),+ [load]+ )++ return useMemo(() => {+ if (!app) {+ return undefined+ }+ return {+ canShow: isTrendsQuery,+ prefetch,+ onShow: (query) => {+ capture('mcp_ui_app_explain_chart_evidence_chart_shown', {+ was_loaded: charts[JSON.stringify(query)]?.status === 'ready',+ })+ load(query)+ },+ render: (query, text) => {+ const chart = charts[JSON.stringify(query)]+ if (chart?.status === 'ready') {+ return (+ <TrendsVisualizer+ key={JSON.stringify(query)}+ query={chart.query}+ results={chart.results}+ highlightedSeries={chart.results.flatMap((item, index) =>+ isSeriesNamedIn(seriesNames(item, index), text) ? [index] : []+ )}+ showControls={false}+ showTitle={false}+ showLegend={chart.results.length > 1}+ chartClassName={chartClassName}+ />+ )+ }+ return (+ <div className={`flex items-center justify-center ${chartClassName}`}>+ {chart?.status === 'error' ? (+ <div className="flex max-w-xs flex-col items-center gap-2 text-center">+ <Text size="sm" variant="muted">+ Couldn't load this chart. Try again, or use Open in PostHog.+ </Text>+ <Button+ variant="outline"+ size="xs"+ onClick={() => load(query)}+ data-attr="explain-chart-evidence-retry"+ >+ Try again+ </Button>+ </div>+ ) : (+ <AppLoadingState />+ )}+ </div>+ )+ },+ }+ }, [app, chartClassName, charts, load, prefetch])+}diff --git a/services/mcp/tests/unit/explain-chart.test.ts b/services/mcp/tests/unit/explain-chart.test.tsnew file mode 100644index 000000000000..e6062c0f29c6--- /dev/null+++ b/services/mcp/tests/unit/explain-chart.test.ts@@ -0,0 +1,221 @@+import { describe, expect, it, vi } from 'vitest'++import { explainChartHandler } from '@/tools/insights/explainChart'+import { findStoryRange, lastBucketInProgress } from '@/tools/insights/storyRanges'+import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'++const DAYS = ['2026-10-01', '2026-10-02', '2026-10-03', '2026-10-04', '2026-10-05']+const HOURS = ['2026-10-01 22:00:00', '2026-10-01 23:00:00', '2026-10-02 00:00:00', '2026-10-02 01:00:00']+const WEEKS = ['2026-09-21', '2026-09-28', '2026-10-05']+const MONTHS = ['2025-12-01', '2026-01-01', '2026-02-01']+const QUARTERS = ['2025-10-01', '2026-01-01', '2026-04-01']+const YEARS = ['2024-01-01', '2025-01-01', '2026-01-01']++function createContext(query: Record<string, unknown>, response: Record<string, unknown> = {}): Context {+ return {+ api: {+ insights: vi.fn().mockReturnValue({+ get: vi.fn().mockResolvedValue({+ success: true,+ data: { id: 7, short_id: 'abc12345', name: 'Sign-ups', query },+ }),+ }),+ query: vi.fn().mockReturnValue({+ runQuery: vi.fn().mockResolvedValue({+ results: [{ label: 'signed_up', data: [5, 50, 6, 5, 4], days: DAYS }],+ ...response,+ }),+ }),+ getProjectBaseUrl: vi.fn().mockReturnValue('https://us.posthog.com/project/1'),+ },+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },+ } as unknown as Context+}++describe('explain-chart', () => {+ it.each([+ ['a day on a daily chart', DAYS, 'day', '2026-10-02', undefined, [1, 1]],+ ['a stretch on a daily chart', DAYS, 'day', '2026-10-02', '2026-10-04', [1, 3]],+ ['a timestamp with a zone on a daily chart', DAYS, 'day', '2026-10-02T00:00:00Z', undefined, [1, 1]],+ ['a day on an hourly chart covers its hours', HOURS, 'hour', '2026-10-02', undefined, [2, 3]],+ ['a date mid-week on a weekly chart', WEEKS, 'week', '2026-10-01', undefined, [1, 1]],+ ['a stretch that starts before the chart', DAYS, 'day', '2026-09-20', '2026-10-02', [0, 1]],+ ['a day after a daily chart ends', DAYS, 'day', '2026-10-09', undefined, null],+ ['a date after the last weekly bucket', WEEKS, 'week', '2026-10-20', undefined, null],+ ['the last day of a short final month', MONTHS, 'month', '2026-02-28', undefined, [2, 2]],+ ['a date after a short final month', MONTHS, 'month', '2026-03-01', undefined, null],+ ['a date mid-quarter on a quarterly chart', QUARTERS, 'quarter', '2026-02-15', undefined, [1, 1]],+ ['a date mid-year on a yearly chart', YEARS, 'year', '2025-06-01', undefined, [1, 1]],+ ] as const)('finds the points for %s', (_, days, interval, start, end, expected) => {+ expect(findStoryRange([...days], interval, start, end)).toEqual(expected)+ })++ it('shows the chapters and tells the agent which dates matched no point', async () => {+ const context = createContext({ kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } })++ const result = await explainChartHandler(context, {+ insightId: 'abc12345',+ series: 0,+ headline: 'One day stands out.',+ chapters: [+ { title: 'A spike on October 2', start: '2026-10-02' },+ { title: 'A gap in November', start: '2026-11-01' },+ ],+ })++ expect(result.chapters.map((chapter) => chapter.range)).toEqual([[1, 1], null])+ expect(result._posthogUrl).toBe('https://us.posthog.com/project/1/insights/abc12345')+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toContain('"A gap in November"')+ })++ it.each([['a funnel', { kind: 'FunnelsQuery', series: [] }, 'only explains trends charts']])(+ 'refuses %s',+ async (_, source, message) => {+ const context = createContext({ kind: 'InsightVizNode', source })++ await expect(+ explainChartHandler(context, {+ insightId: 'abc12345',+ series: 0,+ headline: 'Conversion fell.',+ chapters: [{ title: 'A drop', start: '2026-10-02' }],+ })+ ).rejects.toThrow(message)+ }+ )++ it.each([+ ...[+ 'ActionsLineGraph',+ 'ActionsLineGraphCumulative',+ 'ActionsBar',+ 'ActionsUnstackedBar',+ 'ActionsAreaGraph',+ 'ActionsStackedBar',+ ].map((display) => [display, display] as const),+ ...[+ 'Auto',+ 'BoldNumber',+ 'Metric',+ 'ActionsPie',+ 'ActionsDonut',+ 'ActionsProportionBar',+ 'ActionsBarValue',+ 'ActionsTable',+ 'WorldMap',+ 'CalendarHeatmap',+ 'SlopeGraph',+ ].map((display) => [display, 'ActionsLineGraph'] as const),+ ...['BoxPlot', 'TwoDimensionalHeatmap', 'ScatterPlot', 'SomeFutureDisplay'].map(+ (display) => [display, null] as const+ ),+ ])('handles a %s chart', async (display, drawnAs) => {+ const context = createContext({+ kind: 'InsightVizNode',+ source: { kind: 'TrendsQuery', series: [], trendsFilter: { display } },+ })+ const call = explainChartHandler(context, {+ insightId: 'abc12345',+ series: 0,+ headline: 'One day stands out.',+ chapters: [{ title: 'A spike on October 2', start: '2026-10-02' }],+ })++ if (drawnAs === null) {+ await expect(call).rejects.toThrow('one value over time')+ return+ }+ await call+ expect(context.api.query({ projectId: '1' }).runQuery).toHaveBeenCalledWith({+ query: expect.objectContaining({ trendsFilter: { display: drawnAs } }),+ })+ })++ it('keeps a chart only for evidence that query-trends can draw again', async () => {+ const series = [{ kind: 'EventsNode', event: 'signed_up' }]+ const drawable = {+ kind: 'TrendsQuery',+ series,+ breakdownFilter: { breakdowns: [{ property: '$browser', type: 'event' }] },+ }+ const linkOnly = {+ kind: 'TrendsQuery',+ series,+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ }+ const context = createContext({ kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } })++ const result = await explainChartHandler(context, {+ insightId: 'abc12345',+ series: 0,+ headline: 'One day stands out.',+ chapters: [+ {+ title: 'A spike on October 2',+ start: '2026-10-02',+ evidence: [+ { text: 'Chrome sent most of it.', query: drawable },+ { text: 'Safari stayed flat.', query: linkOnly },+ ],+ },+ ],+ })++ expect(result.chapters[0]!.evidence.map((item) => [item.query !== null, item.url !== null])).toEqual([+ [true, true],+ [false, true],+ ])+ })++ it.each([+ ['a day that is still running', ['2026-10-17', '2026-10-18'], 'day', 'UTC', '2026-10-18T10:00:00Z', true],+ ['a day that has ended', ['2026-10-16', '2026-10-17'], 'day', 'UTC', '2026-10-18T10:00:00Z', false],+ [+ 'a day still running west of Greenwich',+ ['2026-10-17'],+ 'day',+ 'America/Los_Angeles',+ '2026-10-18T03:00:00Z',+ true,+ ],+ ['a month that is still running', ['2026-09-01', '2026-10-01'], 'month', 'UTC', '2026-10-18T10:00:00Z', true],+ [+ 'a quarter that is still running',+ ['2026-07-01', '2026-10-01'],+ 'quarter',+ 'UTC',+ '2026-10-23T10:00:00Z',+ true,+ ],+ [+ 'a day still running on the night the clocks change',+ ['2026-09-26'],+ 'day',+ 'Pacific/Auckland',+ '2026-09-26T11:30:00Z',+ true,+ ],+ ] as const)('knows whether the last point is complete for %s', (_, days, interval, timezone, now, expected) => {+ expect(lastBucketInProgress([...days], interval, timezone, Date.parse(now))).toBe(expected)+ })++ it('draws a slope or number chart as a line chart and passes the query warnings on', async () => {+ const context = createContext(+ { kind: 'TrendsQuery', series: [], trendsFilter: { display: 'SlopeGraph' } },+ { warnings: [{ type: 'stale', message: 'Warehouse data is 3 days old.' }] }+ )++ const result = await explainChartHandler(context, {+ insightId: 'abc12345',+ series: 0,+ headline: 'One day stands out.',+ chapters: [{ title: 'A spike on October 2', start: '2026-10-02' }],+ })++ expect(context.api.query({ projectId: '1' }).runQuery).toHaveBeenCalledWith({+ query: expect.objectContaining({ trendsFilter: { display: 'ActionsLineGraph' } }),+ })+ expect(result.warnings).toEqual([{ type: 'stale', message: 'Warehouse data is 3 days old.' }])+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toContain('Warehouse data is 3 days old.')+ })+})diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 5bb6a49beadc..0ef8e9e3a530 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1115,6 +1115,7 @@ describe('Tool Filtering - Feature Flags', () => {'anomalies-search','workflows-email-domain-agent-setup','feature-flag-rules-v2-mcp',+ 'investigate-insight',]expect(allFlags).toEqual(expect.arrayContaining(branchFlags))// The flags branches add are asserted on the line above and held out of the list anddiff --git a/services/mcp/tests/unit/ui-apps.test.ts b/services/mcp/tests/unit/ui-apps.test.tsindex ada3d865531f..64199e1868bb 100644--- a/services/mcp/tests/unit/ui-apps.test.ts+++ b/services/mcp/tests/unit/ui-apps.test.ts@@ -280,11 +280,12 @@ describe('ui-apps', () => {app_name: 'Chart Walkthrough',description: 'A walkthrough of a chart',render_ui: {- component_import: '../components/InsightStory',- view_component: 'InsightStory',+ component_import: '../components/ExplainChart',+ view_component: 'ExplainChart',view_prop: 'data',- data_type: 'InsightStoryData',+ data_type: 'ExplainChartData',link_prop: 'openLink',+ app_prop: 'app',},})if (!storyConfig.render_ui) {@@ -307,7 +308,7 @@ describe('ui-apps', () => {config: { ...queryResultsConfig, render_ui: queryResultsConfig.render_ui },},{- appKey: 'insight-story',+ appKey: 'explain-chart',type: 'custom',config: { ...storyConfig, render_ui: storyConfig.render_ui },},@@ -326,7 +327,7 @@ describe('ui-apps', () => {expect(code).toContain("import { Component } from '../components/Component'")expect(code).toContain("'query-results': ({ data }) => <Component data={data} />")expect(code).toContain(- "'insight-story': ({ data, openLink }) => <InsightStory data={data as InsightStoryData} openLink={openLink} />"+ "'explain-chart': ({ data, openLink, app }) => <ExplainChart data={data as ExplainChartData} openLink={openLink} app={app} />")expect(code).toContain("'survey-list': ({ data, app }) => <SurveyListContent data={data as SurveyListData} app={app} />"