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(insights): open a chart explanation from a link (#126365)

Sam Pennington6bfc1d674db2
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx
index 9769bebea89c..1da9d71ad172 100644
--- a/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx
@@ -12,13 +12,19 @@ import type { InsightLogicProps } from '~/types'
import { explainChartLogic } from './explainChartLogic'
export function ExplainChartButton({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element | null {
- const { explainAvailable, storyVisible, investigating, consentRequested, explainDisabledReason } = useValues(
- explainChartLogic(insightProps)
- )
+ const {
+ storyAvailable,
+ explainAvailable,
+ story,
+ storyVisible,
+ investigating,
+ consentRequested,
+ explainDisabledReason,
+ } = useValues(explainChartLogic(insightProps))
const { explainClicked, approveConsent, dismissConsent } = useActions(explainChartLogic(insightProps))
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
- if (!explainAvailable) {
+ if (!explainAvailable && !(storyAvailable && story)) {
return null
}
const label = investigating ? 'Investigating…' : 'Explain this chart'
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartByline.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartByline.tsx
new file mode 100644
index 000000000000..af6173bc6d62
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartByline.tsx
@@ -0,0 +1,19 @@
+import { TZLabel } from 'lib/components/TZLabel'
+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+
+import type { StoryAuthor } from './explainChartLogic'
+
+export function ExplainChartByline({ author }: { author: StoryAuthor }): JSX.Element {
+ return (
+ <div className="flex items-center gap-1.5 px-2 pt-2 text-xs text-secondary">
+ <span>Explained</span>
+ {author.createdBy && (
+ <>
+ <span>by</span>
+ <ProfilePicture user={author.createdBy} showName size="sm" />
+ </>
+ )}
+ <TZLabel time={author.createdAt} />
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
index 92205d3226ad..7e852d0ad72e 100644
--- a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
+++ b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
@@ -5,6 +5,8 @@ import type { ReactNode } from 'react'
import { LemonBanner } from '@posthog/lemon-ui'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
+
import type { InsightLogicProps } from '~/types'
import {
@@ -12,12 +14,13 @@ import {
type StoryEvidenceCharts,
} from 'products/product_analytics/mcp/apps/explainChart/ExplainChartView'
+import { ExplainChartByline } from './ExplainChartByline'
import { ExplainChartEvidenceChart } from './ExplainChartEvidenceChart'
import { ExplainChartFollowUp } from './ExplainChartFollowUp'
import { explainChartLogic } from './explainChartLogic'
const EVIDENCE_CHARTS: StoryEvidenceCharts = {
- canShow: (item) => !!item.chart || !!item.query,
+ canShow: (item) => !!item.chart || !!item.queryTool,
prefetch: () => {},
render: (item) => <ExplainChartEvidenceChart item={item} />,
onShow: () => posthog.capture('explain chart evidence chart shown'),
@@ -29,51 +32,70 @@ export interface InsightExplainChartProps {
}
export function InsightExplainChart({ insightProps, renderChart }: InsightExplainChartProps): JSX.Element {
- const { explainAvailable, story, storyShown, storyVisible, storyOutdated, storySeriesKey, formatValue } = useValues(
- explainChartLogic(insightProps)
- )
+ const {
+ storyAvailable,
+ explainAvailable,
+ story,
+ chartStory,
+ storyShown,
+ storyVisible,
+ storyOutdated,
+ storySeriesKey,
+ storyAuthor,
+ formatValue,
+ } = useValues(explainChartLogic(insightProps))
const { askFollowUp } = useActions(explainChartLogic(insightProps))
- if (explainAvailable && storyShown && storyOutdated) {
+ if (storyAvailable && storyShown && storyOutdated) {
return (
<>
<LemonBanner type="info" className="m-2">
- The explanation is hidden because your changes affect the chart's data. Undo them to see it again,
- or save and explain this version.
+ {explainAvailable
+ ? "The explanation is hidden because your changes affect the chart's data. Undo them to see it again, or save and explain this version."
+ : "The explanation is hidden because your changes affect the chart's data. Undo them to see it again."}
</LemonBanner>
{renderChart()}
</>
)
}
- if (!explainAvailable || !story || !storyVisible) {
+ if (!storyAvailable || !story || !chartStory || !storyVisible) {
return <>{renderChart()}</>
}
return (
- <div data-quill>
- <ExplainChartView
- key={story.headline}
- data={story}
- renderChart={(overlay) => <div data-not-quill>{renderChart(overlay)}</div>}
- openLink={(url) => window.open(url, '_blank', 'noopener')}
- openLinkLabel={
- <>
- Open
- <ExternalLink className="size-3" />
- </>
- }
- formatValue={formatValue}
- evidenceCharts={EVIDENCE_CHARTS}
- seriesKey={storySeriesKey ?? undefined}
- chapterAction={(page, step) => <ExplainChartFollowUp onClick={() => askFollowUp(page, step)} />}
- onPageChange={({ index, fromIndex, source }) =>
- posthog.capture('explain chart page viewed', {
- page_index: index,
- from_page_index: fromIndex,
- page_count: story.chapters.length + 1,
- source,
- })
- }
- />
- </div>
+ <>
+ {storyAuthor && <ExplainChartByline author={storyAuthor} />}
+ <div data-quill>
+ <ExplainChartView
+ key={story.headline}
+ data={chartStory}
+ renderChart={(overlay) => <div data-not-quill>{renderChart(overlay)}</div>}
+ openLink={(url) =>
+ window.open(url.startsWith('/') ? addProjectIdIfMissing(url) : url, '_blank', 'noopener')
+ }
+ openLinkLabel={
+ <>
+ Open
+ <ExternalLink className="size-3" />
+ </>
+ }
+ formatValue={formatValue}
+ evidenceCharts={EVIDENCE_CHARTS}
+ seriesKey={storySeriesKey ?? undefined}
+ chapterAction={
+ explainAvailable
+ ? (page, step) => <ExplainChartFollowUp onClick={() => askFollowUp(page, step)} />
+ : undefined
+ }
+ onPageChange={({ index, fromIndex, source }) =>
+ posthog.capture('explain chart page viewed', {
+ page_index: index,
+ from_page_index: fromIndex,
+ page_count: story.chapters.length + 1,
+ source,
+ })
+ }
+ />
+ </div>
+ </>
)
}
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
index a24908de076c..fdaf861e9af7 100644
--- a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
@@ -1,12 +1,16 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import type { LogicWrapper } from 'kea'
+import { urlToAction } from 'kea-router'
+import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { formatAggregationAxisValue } from 'lib/insights/aggregationAxisFormat'
import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import type { insightLogicValues } from 'scenes/insights/insightLogic'
@@ -23,9 +27,10 @@ import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'
import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { compareQuery } from '~/queries/nodes/InsightViz/queryUtils'
-import type { TrendsFilter } from '~/queries/schema/schema-general'
+import { isInsightVizNode } from '~/queries/schema/node-guards'
+import type { InsightVizNode, TrendsFilter } from '~/queries/schema/schema-general'
import { ChartDisplayType, SidePanelTab } from '~/types'
-import type { InsightLogicProps } from '~/types'
+import type { InsightLogicProps, TrendResult } from '~/types'
import {
getToolOutputRecord,
@@ -33,14 +38,18 @@ import {
runStreamLogic,
toolStreamEventsLogic,
} from 'products/posthog_ai/frontend/api/logics'
+import { insightsExplanationsRetrieve } from 'products/product_analytics/frontend/generated/api'
+import type { ChartExplanationAuthorApi } from 'products/product_analytics/frontend/generated/api.schemas'
import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'
import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'
import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import { insightPageShowsStory } from 'products/product_analytics/mcp/apps/explainChart/storyDisplays'
import type { StoryPage } from 'products/product_analytics/mcp/apps/explainChart/storyPages'
+import { followedSeriesIndex } from 'products/product_analytics/mcp/apps/explainChart/storySeries'
import type { CurrencyCode, Node } from '../../../../../frontend/src/queries/schema/schema-general'
import type { InsightModel } from '../../../../../frontend/src/types'
-import { explainChartStoryFor, followUpContextFor } from './explainChartStory'
+import { explainChartStoryFor, followUpContextFor, storyOnChart, withEvidenceLinks } from './explainChartStory'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface explainChartLogicValues {
@@ -52,18 +61,26 @@ export interface explainChartLogicValues {
effectivePhaiView: PhaiViewMode // maxGlobalLogic
baseCurrency: CurrencyCode // teamLogic
display: ChartDisplayType | null | undefined // trendsDataLogic
+ incompletenessOffsetFromEnd: number // trendsDataLogic
indexedResults: IndexedTrendResult[] // trendsDataLogic
isTrends: boolean // trendsDataLogic
+ results: TrendResult[] // trendsDataLogic
trendsFilter: TrendsFilter | null | undefined // trendsDataLogic
+ chartStory: ExplainChartData | null
consentRequested: boolean
explainAvailable: boolean
explainDisabledReason: string | null
followUpContext: AttachedContextItem | null
+ followedChartIndex: number | null
formatValue: (value: number) => string
+ insightId: number | null
investigating: boolean
investigationPrompt: string
investigationStreamKey: string | null
+ linkedExplanationId: string | null
story: ExplainChartData | null
+ storyAuthor: StoryAuthor | null
+ storyAvailable: boolean
storyOutdated: boolean
storyQuery: Node | null
storySeriesKey: string | null
@@ -124,11 +141,16 @@ export interface explainChartLogicActions {
investigationEnded: () => {
value: true
}
+ loadLinkedExplanation: () => {
+ value: true
+ }
receiveStory: (
story: ExplainChartData,
- query: Node | null
+ query: Node | null,
+ source?: StorySource
) => {
query: Node<Record<string, any>> | null
+ source: StorySource
story: ExplainChartData
}
requestConsent: () => {
@@ -140,6 +162,12 @@ export interface explainChartLogicActions {
setInvestigationStream: (streamKey: string) => {
streamKey: string
}
+ setLinkedExplanationId: (explanationId: string | null) => {
+ explanationId: string | null
+ }
+ setStoryAuthor: (author: StoryAuthor) => {
+ author: StoryAuthor
+ }
showStory: () => {
value: true
}
@@ -152,13 +180,14 @@ export interface explainChartLogicActions {
export interface explainChartLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
- explainAvailable: (
+ insightId: (insight: Partial<InsightModel<Node<Record<string, any>>>>) => number | null
+ storyAvailable: (
featureFlags: FeatureFlagsSet,
- effectivePhaiView: PhaiViewMode,
isTrends: boolean,
display: ChartDisplayType | null | undefined,
insight: Partial<InsightModel<Node<Record<string, any>>>>
) => boolean
+ explainAvailable: (storyAvailable: boolean, effectivePhaiView: PhaiViewMode) => boolean
unsavedDataChanges: (
savedInsight: Partial<InsightModel<Node<Record<string, any>>>>,
query: Node<Record<string, any>> | null
@@ -175,7 +204,14 @@ export interface explainChartLogicMeta {
unsavedDataChanges: boolean
) => string | null
investigationPrompt: (insight: Partial<InsightModel<Node<Record<string, any>>>>) => string
- storySeriesKey: (story: ExplainChartData | null, indexedResults: IndexedTrendResult[]) => string | null
+ followedChartIndex: (story: ExplainChartData | null, results: TrendResult[]) => number | null
+ chartStory: (
+ story: ExplainChartData | null,
+ results: TrendResult[],
+ followedChartIndex: number | null,
+ incompletenessOffsetFromEnd: number
+ ) => ExplainChartData | null
+ storySeriesKey: (followedChartIndex: number | null, indexedResults: IndexedTrendResult[]) => string | null
formatValue: (
trendsFilter: TrendsFilter | null | undefined,
baseCurrency: CurrencyCode
@@ -209,7 +245,7 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
teamLogic,
['baseCurrency'],
trendsDataLogic(props),
- ['display', 'indexedResults', 'isTrends', 'trendsFilter'],
+ ['display', 'indexedResults', 'isTrends', 'trendsFilter', 'results', 'incompletenessOffsetFromEnd'],
],
actions: [
sidePanelStateLogic,
@@ -233,7 +269,14 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
output: Record<string, unknown> | null
) => ({ toolCallId, input, output }),
setInvestigationStream: (streamKey: string) => ({ streamKey }),
- receiveStory: (story: ExplainChartData, query: Node | null) => ({ story, query }),
+ receiveStory: (story: ExplainChartData, query: Node | null, source: StorySource = 'agent') => ({
+ story,
+ query,
+ source,
+ }),
+ setLinkedExplanationId: (explanationId: string | null) => ({ explanationId }),
+ loadLinkedExplanation: true,
+ setStoryAuthor: (author: StoryAuthor) => ({ author }),
showStory: true,
hideStory: true,
forgetStory: true,
@@ -279,6 +322,20 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
forgetStory: () => null,
},
],
+ linkedExplanationId: [
+ null as string | null,
+ {
+ setLinkedExplanationId: (_, { explanationId }) => explanationId,
+ },
+ ],
+ storyAuthor: [
+ null as StoryAuthor | null,
+ {
+ setStoryAuthor: (_, { author }) => author,
+ receiveStory: () => null,
+ forgetStory: () => null,
+ },
+ ],
followUpContext: [
null as AttachedContextItem | null,
{
@@ -299,23 +356,27 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
],
}),
selectors(({ props }) => ({
- explainAvailable: [
- (s) => [s.featureFlags, s.effectivePhaiView, s.isTrends, s.display, s.insight],
+ insightId: [(s) => [s.insight], (insight: insightLogicValues['insight']): number | null => insight.id ?? null],
+ storyAvailable: [
+ (s) => [s.featureFlags, s.isTrends, s.display, s.insight],
(
featureFlags: FeatureFlagsSet,
- effectivePhaiView: PhaiViewMode,
isTrends: boolean,
display: ChartDisplayType | null | undefined,
insight: insightLogicValues['insight']
): boolean =>
!!featureFlags[FEATURE_FLAGS.EXPLAIN_CHART] &&
- effectivePhaiView === 'new' &&
isTrends &&
- isOverTime(display) &&
+ insightPageShowsStory(display) &&
!!insight.short_id &&
!props.filtersOverride &&
!props.variablesOverride,
],
+ explainAvailable: [
+ (s) => [s.storyAvailable, s.effectivePhaiView],
+ (storyAvailable: boolean, effectivePhaiView: PhaiViewMode): boolean =>
+ storyAvailable && effectivePhaiView === 'new',
+ ],
unsavedDataChanges: [
(s) => [s.savedInsight, s.query],
(savedInsight: insightLogicValues['savedInsight'], query: Node | null): boolean =>
@@ -342,14 +403,29 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
return `Explain why the insight ${insight.short_id} looks the way it does. I'm on the insight page, which opens your explain-chart result beside the chart as soon as the tool returns, so skip render-ui. In the chat, reply with one sentence naming the moment to read first, by its number and title. Leave the other findings to the explanation, and don't offer follow-up actions.`
},
],
+ followedChartIndex: [
+ (s) => [s.story, s.results],
+ (story: ExplainChartData | null, results: TrendResult[]): number | null =>
+ story && followedSeriesIndex(story, results),
+ ],
+ chartStory: [
+ (s) => [s.story, s.results, s.followedChartIndex, s.incompletenessOffsetFromEnd],
+ (
+ story: ExplainChartData | null,
+ results: TrendResult[],
+ followedChartIndex: number | null,
+ incompletenessOffsetFromEnd: number
+ ): ExplainChartData | null =>
+ story && storyOnChart(story, results, followedChartIndex, incompletenessOffsetFromEnd < 0),
+ ],
storySeriesKey: [
- (s) => [s.story, s.indexedResults],
- (story: ExplainChartData | null, indexedResults: IndexedTrendResult[]): string | null => {
- if (!story) {
+ (s) => [s.followedChartIndex, s.indexedResults],
+ (followedChartIndex: number | null, indexedResults: IndexedTrendResult[]): string | null => {
+ if (followedChartIndex === null) {
return null
}
- const rendered = indexedResults.find((result) => result.seriesIndex === story.seriesIndex)
- return String(rendered?.id ?? story.seriesIndex)
+ const rendered = indexedResults.find((result) => result.seriesIndex === followedChartIndex)
+ return String(rendered?.id ?? followedChartIndex)
},
],
formatValue: [
@@ -360,6 +436,52 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
],
})),
listeners(({ actions, values, cache }) => ({
+ setLinkedExplanationId: () => actions.loadLinkedExplanation(),
+ loadLinkedExplanation: async () => {
+ const explanationId = values.linkedExplanationId
+ const insightId = values.insightId
+ if (
+ !explanationId ||
+ !insightId ||
+ !values.storyAvailable ||
+ cache.linkedExplanationIdLoaded === explanationId
+ ) {
+ return
+ }
+ cache.linkedExplanationIdLoaded = explanationId
+ try {
+ const explanation = await insightsExplanationsRetrieve(
+ String(getCurrentTeamId()),
+ insightId,
+ explanationId
+ )
+ if (cache.disposables.isDisposed || values.linkedExplanationId !== explanationId) {
+ return
+ }
+ if (explanation.data.shape !== 'time_series') {
+ lemonToast.error(
+ 'This chart explanation needs a newer version of PostHog. Refresh the page to see it.'
+ )
+ return
+ }
+ actions.receiveStory(
+ withEvidenceLinks(explanation.data as ExplainChartData),
+ explainedQuery(values.savedInsight.query, explanation.data.query),
+ 'link'
+ )
+ actions.setStoryAuthor({ createdBy: explanation.created_by ?? null, createdAt: explanation.created_at })
+ } catch {
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ if (cache.linkedExplanationIdLoaded === explanationId) {
+ cache.linkedExplanationIdLoaded = null
+ }
+ if (values.linkedExplanationId === explanationId) {
+ lemonToast.error("Couldn't load this chart explanation. Ask your agent to explain the chart again.")
+ }
+ }
+ },
explainClicked: () => {
if (values.explainDisabledReason) {
return
@@ -450,8 +572,8 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
actions.setFollowUpContext(followUpContextFor(values.insight, page, step))
actions.openSidePanel(SidePanelTab.Max)
},
- receiveStory: ({ story }) => {
- posthog.capture('explain chart story shown', { chapters: story.chapters.length })
+ receiveStory: ({ story, source }) => {
+ posthog.capture('explain chart story shown', { chapters: story.chapters.length, source })
},
saveInsightSuccess: () => {
if (values.storyOutdated) {
@@ -459,20 +581,34 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
}
},
})),
+ subscriptions(({ actions }) => ({
+ insightId: () => actions.loadLinkedExplanation(),
+ storyAvailable: () => actions.loadLinkedExplanation(),
+ })),
+ urlToAction(({ actions, props }) => ({
+ '/insights/:shortId': ({ shortId }, { explanation }) => {
+ if (shortId === props.dashboardItemId) {
+ actions.setLinkedExplanationId(typeof explanation === 'string' ? explanation : null)
+ }
+ },
+ })),
])
-const EXPLAINABLE_DISPLAYS: ChartDisplayType[] = [
- ChartDisplayType.ActionsLineGraph,
- ChartDisplayType.ActionsBar,
- ChartDisplayType.ActionsUnstackedBar,
- ChartDisplayType.ActionsAreaGraph,
- ChartDisplayType.ActionsStackedBar,
-]
+function explainedQuery(savedQuery: Node | null | undefined, explainedSource: Record<string, unknown>): Node | null {
+ if (!savedQuery || !isInsightVizNode(savedQuery)) {
+ return savedQuery ?? null
+ }
+ const explained: InsightVizNode = { ...savedQuery, source: explainedSource as unknown as InsightVizNode['source'] }
+ return explained
+}
function dataDiffers(a: Node | null | undefined, b: Node | null | undefined): boolean {
return !!a && !!b && !compareQuery(a, b, { ignoreVisualizationOnlyChanges: true })
}
-function isOverTime(display: ChartDisplayType | null | undefined): boolean {
- return !display || EXPLAINABLE_DISPLAYS.includes(display)
+type StorySource = 'agent' | 'link'
+
+export interface StoryAuthor {
+ createdBy: ChartExplanationAuthorApi | null
+ createdAt: string
}
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts b/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts
index 656df1e3d5f7..5c2ddc1692a8 100644
--- a/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts
@@ -1,9 +1,13 @@
import type { insightLogicValues } from 'scenes/insights/insightLogic'
-import { explainChartStoryFor } from './explainChartStory'
+import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import { followedSeriesIndex } from 'products/product_analytics/mcp/apps/explainChart/storySeries'
+
+import { explainChartStoryFor, storyOnChart, withEvidenceLinks } from './explainChartStory'
const INSIGHT = { id: 42, short_id: 'aBc12345' } as insightLogicValues['insight']
const STORY = {
+ shape: 'time_series',
query: { kind: 'TrendsQuery' },
results: [{ label: 'Pageviews', data: [1, 2, 3], days: ['2026-10-01', '2026-10-02', '2026-10-03'] }],
seriesIndex: 0,
@@ -13,14 +17,118 @@ const STORY = {
chapters: [],
}
-describe('explainChartStoryFor', () => {
+describe('explainChartStory', () => {
test.each([
['the short id', { insightId: 'aBc12345' }, STORY, STORY],
['the numeric id under an alias', { id: 42 }, STORY, STORY],
['another insight', { insightId: 'zzz99999' }, STORY, null],
['an unsaved query', { query: { kind: 'TrendsQuery' } }, STORY, null],
['a result that is not a story', { insightId: 'aBc12345' }, { headline: 'A peak' }, null],
+ [
+ 'a story from a server that predates shapes',
+ { insightId: 'aBc12345' },
+ { ...STORY, shape: undefined },
+ STORY,
+ ],
+ [
+ 'a story of a shape this page cannot draw',
+ { insightId: 'aBc12345' },
+ { ...STORY, shape: 'funnel_steps' },
+ null,
+ ],
])('takes a story for %s only when it explains this insight', (_, input, output, expected) => {
expect(explainChartStoryFor(INSIGHT, input, output)).toEqual(expected)
})
+
+ test.each([
+ [
+ 'the chart moved on a day',
+ [{ label: 'Pageviews', days: ['2026-10-02', '2026-10-03', '2026-10-04'] }],
+ 0,
+ [
+ [0, 0],
+ [1, 1],
+ ],
+ ],
+ [
+ 'the chart moved past a chapter',
+ [{ label: 'Pageviews', days: ['2026-10-03', '2026-10-04', '2026-10-05'] }],
+ 0,
+ [null, [0, 0]],
+ ],
+ [
+ 'the chart is unchanged',
+ [{ label: 'Pageviews', days: ['2026-10-01', '2026-10-02', '2026-10-03'] }],
+ 0,
+ [
+ [1, 1],
+ [2, 2],
+ ],
+ ],
+ [
+ 'another series overtook the followed one',
+ [
+ { label: 'Signups', days: ['2026-10-01', '2026-10-02', '2026-10-03'] },
+ { label: 'Pageviews', days: ['2026-10-01', '2026-10-02', '2026-10-03'] },
+ ],
+ 1,
+ [
+ [1, 1],
+ [2, 2],
+ ],
+ ],
+ [
+ 'the followed series is gone',
+ [{ label: 'Signups', days: ['2026-10-01', '2026-10-02', '2026-10-03'] }],
+ 0,
+ [null, null],
+ ],
+ ])('keeps each chapter on its saved date when %s', (_, chart, expectedIndex, expected) => {
+ const story = {
+ ...STORY,
+ chapters: [
+ { title: 'A peak', range: [1, 1] },
+ { title: 'A dip', range: [2, 2] },
+ ],
+ } as unknown as ExplainChartData
+
+ const shown = storyOnChart(story, chart, followedSeriesIndex(story, chart), false)
+
+ expect(shown.seriesIndex).toBe(expectedIndex)
+ expect(shown.chapters.map((chapter) => chapter.range)).toEqual(expected)
+ })
+
+ it('links saved evidence to its query, its insight or its GitHub change', () => {
+ const story = {
+ ...STORY,
+ chapters: [
+ {
+ title: 'A peak',
+ range: [1, 1],
+ summary: null,
+ cause: null,
+ confidence: null,
+ confidenceReason: null,
+ evidence: [
+ {
+ text: 'From one referrer.',
+ query: { kind: 'TrendsQuery', series: [] },
+ url: 'https://us.posthog.com/project/1/insights/new',
+ },
+ { text: 'The signup funnel shows it.', insightShortId: 'xyz98765' },
+ { text: 'Shipped in a release.', url: 'https://github.com/example/app/pull/1' },
+ { text: 'Seen in the logs.' },
+ ],
+ },
+ ],
+ } as unknown as ExplainChartData
+
+ const [withQuery, withInsight, withLink, withNothing] = withEvidenceLinks(story).chapters[0].evidence
+
+ expect(withQuery.url).toMatch(/^\/insights\/new/)
+ expect(decodeURIComponent(withQuery.url ?? '')).toContain('"kind":"InsightVizNode"')
+ expect(withInsight.url).toBe('/insights/xyz98765')
+ expect(withLink.url).toBe('https://github.com/example/app/pull/1')
+ expect(withNothing.url).toBeNull()
+ })
})
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts b/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts
index 4f54d9566b66..255bb4b4cc50 100644
--- a/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts
@@ -1,8 +1,15 @@
import type { insightLogicValues } from 'scenes/insights/insightLogic'
+import { urls } from 'scenes/urls'
import type { AttachedContextItem } from '~/layout/ai/attachedContext'
+import type { Node } from '~/queries/schema/schema-general'
+import type { InsightShortId } from '~/types'
-import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import type {
+ ExplainChartData,
+ StorySeriesResult,
+} from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import { storyEvidenceNode } from 'products/product_analytics/mcp/apps/explainChart/storyEvidenceNode'
import type { StoryPage } from 'products/product_analytics/mcp/apps/explainChart/storyPages'
const INSIGHT_ID_KEYS = ['insightId', 'insight_id', 'id', 'short_id', 'shortId']
@@ -17,7 +24,56 @@ export function explainChartStoryFor(
if (requested === undefined || !insightIds.includes(String(requested))) {
return null
}
- return isExplainChartData(output) ? output : null
+ return isExplainChartData(output) ? { ...output, shape: 'time_series' } : null
+}
+
+export function withEvidenceLinks(story: ExplainChartData): ExplainChartData {
+ return {
+ ...story,
+ chapters: story.chapters.map((chapter) => ({
+ ...chapter,
+ evidence: chapter.evidence.map((item) => ({
+ ...item,
+ url: item.query
+ ? evidenceInsightUrl(item.query)
+ : item.insightShortId
+ ? urls.insightView(item.insightShortId as InsightShortId)
+ : (item.url ?? null),
+ })),
+ })),
+ }
+}
+
+function evidenceInsightUrl(query: Record<string, unknown>): string {
+ return urls.insightNew({ query: storyEvidenceNode(query) as unknown as Node })
+}
+
+export function storyOnChart(
+ story: ExplainChartData,
+ results: StorySeriesResult[],
+ chartIndex: number | null,
+ lastPointInProgress: boolean
+): ExplainChartData {
+ if (!results.length) {
+ return story
+ }
+ const chartDays = chartIndex === null ? undefined : results[chartIndex]?.days
+ if (chartIndex === null || !chartDays) {
+ return { ...story, chapters: story.chapters.map((chapter) => ({ ...chapter, range: null })) }
+ }
+ const savedDays = story.results[story.seriesIndex]?.days ?? []
+ const dayIndex = new Map(chartDays.map((day, index) => [day, index]))
+ return {
+ ...story,
+ results,
+ seriesIndex: chartIndex,
+ lastPointInProgress: lastPointInProgress && results[chartIndex].compare_label !== 'previous',
+ chapters: story.chapters.map((chapter) => {
+ const start = chapter.range ? dayIndex.get(savedDays[chapter.range[0]]) : undefined
+ const end = chapter.range ? dayIndex.get(savedDays[chapter.range[1]]) : undefined
+ return { ...chapter, range: start !== undefined && end !== undefined ? [start, end] : null }
+ }),
+ }
}
export function followUpContextFor(
@@ -44,6 +100,7 @@ function isExplainChartData(
): output is ExplainChartData & Record<string, unknown> {
return (
!!output &&
+ (output.shape === undefined || output.shape === 'time_series') &&
typeof output.headline === 'string' &&
Array.isArray(output.chapters) &&
Array.isArray(output.results) &&
diff --git a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsx b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsx
index 35a16d1bd60f..3cb156f5a025 100644
--- a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsx
+++ b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsx
@@ -31,6 +31,7 @@ const BY_REFERRER: Series[] = [
]
const story: ExplainChartData = {
+ shape: 'time_series',
query: { kind: 'TrendsQuery', interval: 'day', series: [{ kind: 'EventsNode', event: 'signed_up' }] },
results: [{ label: 'signed_up', data: VALUES, days: DAYS }],
seriesIndex: 0,
diff --git a/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts b/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts
index 2206e88e4a5c..7a0c2d592fb9 100644
--- a/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts
+++ b/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts
@@ -14,6 +14,7 @@ export interface StoryEvidence {
text: string
url: string | null
query?: Record<string, unknown> | null
+ insightShortId?: string | null
queryTool?: string | null
chart?: StoryEvidenceChartData | null
}
@@ -33,6 +34,7 @@ export interface StorySeriesResult {
label?: string
data?: number[]
days?: string[]
+ compare_label?: 'current' | 'previous' | null
}
export interface StoryTrendsQuery {
@@ -43,7 +45,11 @@ export interface StoryTrendsQuery {
[key: string]: unknown
}
+// What the explanation walks through, whichever insight drew it: a funnel over time is a time series too.
+export type ExplainChartShape = 'time_series'
+
export interface ExplainChartData {
+ shape: ExplainChartShape
query: StoryTrendsQuery
results: StorySeriesResult[]
seriesIndex: number
diff --git a/products/product_analytics/mcp/apps/explainChart/storyDisplays.ts b/products/product_analytics/mcp/apps/explainChart/storyDisplays.ts
new file mode 100644
index 000000000000..3dd5dc09c428
--- /dev/null
+++ b/products/product_analytics/mcp/apps/explainChart/storyDisplays.ts
@@ -0,0 +1,11 @@
+const INSIGHT_PAGE_DISPLAYS = new Set<unknown>([
+ 'ActionsLineGraph',
+ 'ActionsBar',
+ 'ActionsUnstackedBar',
+ 'ActionsAreaGraph',
+ 'ActionsStackedBar',
+])
+
+export function insightPageShowsStory(display: unknown): boolean {
+ return display === undefined || display === null || INSIGHT_PAGE_DISPLAYS.has(display)
+}
diff --git a/products/product_analytics/mcp/apps/explainChart/storyEvidenceNode.ts b/products/product_analytics/mcp/apps/explainChart/storyEvidenceNode.ts
new file mode 100644
index 000000000000..0437e4e53802
--- /dev/null
+++ b/products/product_analytics/mcp/apps/explainChart/storyEvidenceNode.ts
@@ -0,0 +1,7 @@
+export function storyEvidenceNode(query: Record<string, unknown>): Record<string, unknown> {
+ const kind = typeof query.kind === 'string' ? query.kind : 'TrendsQuery'
+ if (kind === 'HogQLQuery') {
+ return { kind: 'DataVisualizationNode', source: query }
+ }
+ return kind.endsWith('Node') ? query : { kind: 'InsightVizNode', source: { ...query, kind } }
+}
diff --git a/products/product_analytics/mcp/apps/explainChart/storySeries.ts b/products/product_analytics/mcp/apps/explainChart/storySeries.ts
new file mode 100644
index 000000000000..57c42edc9818
--- /dev/null
+++ b/products/product_analytics/mcp/apps/explainChart/storySeries.ts
@@ -0,0 +1,20 @@
+import type { ExplainChartData, StorySeriesResult } from './explainChartTypes'
+
+export const STORY_SERIES_LABEL_MAX_LENGTH = 400
+
+export function storySeriesLabel(label: string | undefined): string | undefined {
+ return label?.slice(0, STORY_SERIES_LABEL_MAX_LENGTH)
+}
+
+// Breakdown series are sorted by volume, so the saved index can point at another series by the time a link is opened.
+export function followedSeriesIndex(story: ExplainChartData, results: StorySeriesResult[]): number | null {
+ const label = story.results[story.seriesIndex]?.label
+ if (label === undefined) {
+ return results[story.seriesIndex] ? story.seriesIndex : null
+ }
+ const matches = results.flatMap((result, index) => (storySeriesLabel(result.label) === label ? [index] : []))
+ if (matches.length === 1) {
+ return matches[0] ?? null
+ }
+ return matches.includes(story.seriesIndex) ? story.seriesIndex : null
+}
diff --git a/products/product_analytics/skills/investigate-metric/SKILL.md b/products/product_analytics/skills/investigate-metric/SKILL.md
index 869266ff74aa..0f2908f04bc1 100644
--- a/products/product_analytics/skills/investigate-metric/SKILL.md
+++ b/products/product_analytics/skills/investigate-metric/SKILL.md
@@ -163,8 +163,8 @@ Map the investigation onto it:
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. The chart explanation runs each query and draws it: an insight
+- **Evidence** → `evidence`, each finding with the `query` that produced it, the
+ `insightShortId` of a saved insight, or a `url` to a GitHub pull request or commit. No other links are accepted. The chart explanation runs each query and draws it: an insight
query with its insight chart, and a `HogQLQuery` from its rows. Shape the SQL for the chart,
with the x-axis column first, then optionally one text column to break down by, then the numbers.
Prefer a series over time to a before-and-after comparison, so the user sees when the change happened.
@@ -179,7 +179,8 @@ Call `posthog:explain-chart` first. It reports any chapter whose dates match no
chart, so fix those dates and call it again.
When its response says the user already sees the result, the chart explanation is on screen, and you are done.
Otherwise call `posthog:render-ui` with `tool_name` `explain-chart` and the same input as `tool_input`.
-When the call fails because the tool does not exist, or `render-ui` does not exist either, the user sees nothing, so write the written report instead.
+When `render-ui` does not exist, call `posthog:explain-chart-save` with the same arguments and give the user the link it returns, which opens the chart explanation in PostHog.
+When the call fails because the tool does not exist, or neither `render-ui` nor a link is available, the user sees nothing, so write the written report instead.
Then reply briefly.
Say which chapter to look at first, then add only what the chart explanation cannot hold, such as a caveat about the data, a linked fix or a decision that is still open.
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d8cea4678872..824c271e2055 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6430,7 +6430,7 @@
"feature_flag": "experiment-behavior-comparison"
},
"explain-chart": {
- "description": "Show the person why a trends chart changed: the chart with each moment that stands out highlighted, such as a drop, a spike or a rise, and a panel that steps through them one chapter at a time, with what happened, the likely cause and the evidence.\n\nUse it to answer \"why did this metric drop, spike or change?\" about one value over time, when the person gives you a saved insight, a dashboard tile or a screenshot of a chart, or only names the metric. Read this schema when the investigation starts, and call the tool before your final reply, after you have looked into the chart yourself (the investigate-metric skill describes how). Pass the saved insight's `insightId`. When there is no saved insight, run the metric with `query-trends` and pass that TrendsQuery as `query`, also when you investigated with SQL. Add 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. Where the host draws apps from `exec`, as Claude Code does, the call also shows the explanation and the response says so. Otherwise it returns only a short summary: show the explanation with `render-ui` where that tool exists, and write the findings in the chat where it does not.",
+ "description": "Show the person why a trends chart changed: the chart with each moment that stands out highlighted, such as a drop, a spike or a rise, and a panel that steps through them one chapter at a time, with what happened, the likely cause and the evidence.\n\nUse it to answer \"why did this metric drop, spike or change?\" about one value over time, when the person gives you a saved insight, a dashboard tile or a screenshot of a chart, or only names the metric. Read this schema when the investigation starts, and call the tool before your final reply, after you have looked into the chart yourself (the investigate-metric skill describes how). Pass the saved insight's `insightId`. When there is no saved insight, run the metric with `query-trends` and pass that TrendsQuery as `query`, also when you investigated with SQL. Add 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. Where the host draws apps from `exec`, as Claude Code does, the call also shows the explanation and the response says so. Otherwise it returns only a short summary: show the explanation with `render-ui` where that tool exists. Where it does not, call `explain-chart-save` with the same arguments for a link that opens the explanation in PostHog, and write the findings in the chat only when there is no link.",
"category": "Insights & analytics",
"feature": "insights",
"summary": "Explain why a trends chart dropped, spiked or changed, one highlighted moment at a time.",
@@ -6445,6 +6445,27 @@
"readOnlyHint": true
}
},
+ "explain-chart-save": {
+ "description": "Save a chart explanation and get a link that opens it beside the chart in PostHog.\n\nCall it only where the person cannot see the `explain-chart` result rendered inline: the host draws no apps from `exec` and there is no `render-ui`. Pass the same arguments as your `explain-chart` call. It saves only a saved trends insight drawn as a line or bar chart. For any other chart it saves nothing and says so, so give the findings in text.\n\nTo fix the explanation, such as its chapter dates, call it again with the `explanationId` it returned, so the same link shows the fix.",
+ "category": "Insights & analytics",
+ "feature": "insights",
+ "summary": "Save a chart explanation and get a link that opens it in PostHog.",
+ "title": "Save chart explanation",
+ "required_scopes": ["insight:read", "query:read", "insight:write"],
+ "api_operations": [
+ "GET /api/projects/{project_id}/insights/{id}/",
+ "POST /api/projects/{project_id}/query/",
+ "POST /api/projects/{project_id}/insights/{insight_id}/explanations/",
+ "PUT /api/projects/{project_id}/insights/{insight_id}/explanations/{id}/"
+ ],
+ "feature_flag": "investigate-insight",
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"external-data-destinations-add-sources": {
"description": "Attach up to 50 existing sources to a destination. Each source's tables then also sync there, except tables with their own destination override: they keep the override and ignore this link. Before attaching, check the destination's status with external-data-destinations-retrieve: do not attach to a failing or paused destination until the user fixed it. Then call external-data-sources-destinations-retrieve for each source. When destination_ids holds only the PostHog warehouse destination (is_posthog_warehouse in external-data-destinations-list), the source may write there by default and would stop updating its PostHog tables after this call. If the user wants to keep them and no destination in external-data-destinations-list is paused, first call external-data-sources-destinations-update with that same list: it makes the warehouse an explicit link. If a destination is paused, tell the user instead. When destination_ids is empty, tell the user the PostHog tables stop updating. Call external-data-schemas-destinations-retrieve for each of the source's tables and tell the user which have inherits_from_source false: those will not reach this destination. Sources already attached, or already at the destination limit, come back in skipped with a reason. An attached source sends only rows from its next syncs, so the destination holds no history until those tables are resynced. Set resync=true to start a full resync of every enabled table now, including tables with an override that will not reach this destination. Tell the user first: a resync re-reads every row and bills every destination the source writes to.",
"category": "Warehouse destinations",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 64e932a74bc7..5ca6804685f5 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -302,7 +302,7 @@
"feature_flag": "insight-data-checks"
},
"explain-chart": {
- "description": "Show the person why a trends chart changed: the chart with each moment that stands out highlighted, such as a drop, a spike or a rise, and a panel that steps through them one chapter at a time, with what happened, the likely cause and the evidence.\n\nUse it to answer \"why did this metric drop, spike or change?\" about one value over time, when the person gives you a saved insight, a dashboard tile or a screenshot of a chart, or only names the metric. Read this schema when the investigation starts, and call the tool before your final reply, after you have looked into the chart yourself (the investigate-metric skill describes how). Pass the saved insight's `insightId`. When there is no saved insight, run the metric with `query-trends` and pass that TrendsQuery as `query`, also when you investigated with SQL. Add 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. Where the host draws apps from `exec`, as Claude Code does, the call also shows the explanation and the response says so. Otherwise it returns only a short summary: show the explanation with `render-ui` where that tool exists, and write the findings in the chat where it does not.",
+ "description": "Show the person why a trends chart changed: the chart with each moment that stands out highlighted, such as a drop, a spike or a rise, and a panel that steps through them one chapter at a time, with what happened, the likely cause and the evidence.\n\nUse it to answer \"why did this metric drop, spike or change?\" about one value over time, when the person gives you a saved insight, a dashboard tile or a screenshot of a chart, or only names the metric. Read this schema when the investigation starts, and call the tool before your final reply, after you have looked into the chart yourself (the investigate-metric skill describes how). Pass the saved insight's `insightId`. When there is no saved insight, run the metric with `query-trends` and pass that TrendsQuery as `query`, also when you investigated with SQL. Add 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. Where the host draws apps from `exec`, as Claude Code does, the call also shows the explanation and the response says so. Otherwise it returns only a short summary: show the explanation with `render-ui` where that tool exists. Where it does not, call `explain-chart-save` with the same arguments for a link that opens the explanation in PostHog, and write the findings in the chat only when there is no link.",
"category": "Insights & analytics",
"feature": "insights",
"summary": "Explain why a trends chart dropped, spiked or changed, one highlighted moment at a time.",
@@ -317,6 +317,27 @@
"readOnlyHint": true
}
},
+ "explain-chart-save": {
+ "description": "Save a chart explanation and get a link that opens it beside the chart in PostHog.\n\nCall it only where the person cannot see the `explain-chart` result rendered inline: the host draws no apps from `exec` and there is no `render-ui`. Pass the same arguments as your `explain-chart` call. It saves only a saved trends insight drawn as a line or bar chart. For any other chart it saves nothing and says so, so give the findings in text.\n\nTo fix the explanation, such as its chapter dates, call it again with the `explanationId` it returned, so the same link shows the fix.",
+ "category": "Insights & analytics",
+ "feature": "insights",
+ "summary": "Save a chart explanation and get a link that opens it in PostHog.",
+ "title": "Save chart explanation",
+ "required_scopes": ["insight:read", "query:read", "insight:write"],
+ "api_operations": [
+ "GET /api/projects/{project_id}/insights/{id}/",
+ "POST /api/projects/{project_id}/query/",
+ "POST /api/projects/{project_id}/insights/{insight_id}/explanations/",
+ "PUT /api/projects/{project_id}/insights/{insight_id}/explanations/{id}/"
+ ],
+ "feature_flag": "investigate-insight",
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"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.json
index 51c28a4558c4..978bfc960c97 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -789,11 +789,15 @@
},
"additionalProperties": {}
},
+ "insightShortId": {
+ "description": "The `short_id` of a saved insight that shows this. The explanation links to it.",
+ "type": "string",
+ "pattern": "^[A-Za-z0-9]{8}$"
+ },
"url": {
- "description": "A link to the source when it is not a query, for example a commit, a pull request or a deploy.",
+ "description": "A link to the GitHub pull request or commit behind this, when it is not a query or a saved insight. No other links are accepted.",
"type": "string",
- "format": "uri",
- "pattern": "^https:\\/\\/.*"
+ "pattern": "^https:\\/\\/github\\.com\\/[A-Za-z0-9-]+\\/[A-Za-z0-9._-]+\\/(pull\\/\\d+|commit\\/[0-9a-fA-F]{7,40})\\/?$"
}
},
"required": ["text"]
@@ -807,6 +811,133 @@
},
"required": ["headline", "chapters"]
},
+ "ExplainChartSaveInputSchema": {
+ "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. The explanation runs it again and draws the result beside the finding. An insight query (`TrendsQuery`, `FunnelsQuery`, `RetentionQuery`, `StickinessQuery`, `PathsQuery` or `LifecycleQuery`) draws with its insight chart. A `HogQLQuery` draws from its rows: select the x-axis column first (a time bucket or a label), then either the numbers to draw, or one text column to break down by followed by one number. Order by the x-axis column. SQL returns 100 rows unless it sets a `LIMIT`.",
+ "type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
+ "additionalProperties": {}
+ },
+ "insightShortId": {
+ "description": "The `short_id` of a saved insight that shows this. The explanation links to it.",
+ "type": "string",
+ "pattern": "^[A-Za-z0-9]{8}$"
+ },
+ "url": {
+ "description": "A link to the GitHub pull request or commit behind this, when it is not a query or a saved insight. No other links are accepted.",
+ "type": "string",
+ "pattern": "^https:\\/\\/github\\.com\\/[A-Za-z0-9-]+\\/[A-Za-z0-9._-]+\\/(pull\\/\\d+|commit\\/[0-9a-fA-F]{7,40})\\/?$"
+ }
+ },
+ "required": ["text"]
+ }
+ }
+ },
+ "required": ["title", "start"]
+ },
+ "description": "The moments that stand out, in the order to read them. At most 8."
+ },
+ "explanationId": {
+ "description": "The id an earlier `explain-chart-save` call on this chart returned, when you are fixing that explanation. Its link then shows the fix. Omit it for a new explanation.",
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
+ }
+ },
+ "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/src/api/client.ts b/services/mcp/src/api/client.ts
index 3783f214b469..527996d9a71e 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -1391,6 +1391,34 @@ export class ApiClient {
}
},
+ saveExplanation: async ({
+ insightId,
+ data,
+ }: {
+ insightId: number
+ data: Record<string, unknown>
+ }): Promise<Result<Schemas.ChartExplanation>> => {
+ return this.fetchJson<Schemas.ChartExplanation>(
+ `${this.baseUrl}/api/projects/${projectId}/insights/${insightId}/explanations/`,
+ { method: 'POST', body: JSON.stringify({ data }) }
+ )
+ },
+
+ updateExplanation: async ({
+ insightId,
+ explanationId,
+ data,
+ }: {
+ insightId: number
+ explanationId: string
+ data: Record<string, unknown>
+ }): Promise<Result<Schemas.ChartExplanation>> => {
+ return this.fetchJson<Schemas.ChartExplanation>(
+ `${this.baseUrl}/api/projects/${projectId}/insights/${insightId}/explanations/${encodeURIComponent(explanationId)}/`,
+ { method: 'PUT', body: JSON.stringify({ data }) }
+ )
+ },
+
create: async ({ data }: { data: Record<string, any> }): Promise<Result<Schemas.Insight>> => {
return this.fetchJson<Schemas.Insight>(`${this.baseUrl}/api/projects/${projectId}/insights/`, {
method: 'POST',
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index d38ab1213351..1f6ecf678e46 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -238,7 +238,15 @@ export class InstructionsFormatter {
private artifactSections(ctx: InstructionsContext): string[] {
return [
ANALYSIS_ARTIFACTS,
- ...(ctx.tools?.some(({ name }) => name === 'explain-chart') ? [EXPLAIN_CHART] : []),
+ ...(ctx.tools?.some(({ name }) => name === 'explain-chart')
+ ? [
+ formatPrompt(EXPLAIN_CHART, {
+ explain_chart_link_line: ctx.tools.some(({ name }) => name === 'explain-chart-save')
+ ? 'Where the conversation cannot show the chart explanation, call `explain-chart-save` with the same arguments and give the person the link it returns, which opens it beside the chart in PostHog.'
+ : '',
+ }),
+ ]
+ : []),
...(ctx.notebookCellsEnabled ? [formatPrompt(NOTEBOOK_SQL, notebookSqlVars(ctx)), NOTEBOOK_PYTHON] : []),
...(ctx.notebookRunEnabled ? [NOTEBOOK_RUN] : []),
]
diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.ts
index b08f261182d4..4a3e3d2569d8 100644
--- a/services/mcp/src/lib/instructions.ts
+++ b/services/mcp/src/lib/instructions.ts
@@ -238,6 +238,7 @@ export class ToolDomainExtractor {
'restore',
'resume',
'revoke',
+ 'save',
'ship',
'show',
'start',
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index adf4b5d8b2dc..cb3f25e0f3f7 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -587,12 +587,18 @@ const ExplainChartEvidenceSchema = z.object({
.describe(
'The query that found this, as you ran it. The explanation runs it again and draws the result beside the finding. An insight query (`TrendsQuery`, `FunnelsQuery`, `RetentionQuery`, `StickinessQuery`, `PathsQuery` or `LifecycleQuery`) draws with its insight chart. A `HogQLQuery` draws from its rows: select the x-axis column first (a time bucket or a label), then either the numbers to draw, or one text column to break down by followed by one number. Order by the x-axis column. SQL returns 100 rows unless it sets a `LIMIT`.'
),
+ insightShortId: z
+ .string()
+ .regex(/^[A-Za-z0-9]{8}$/)
+ .optional()
+ .describe('The `short_id` of a saved insight that shows this. The explanation links to it.'),
url: z
.string()
- .url()
- .startsWith('https://')
+ .regex(/^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9._-]+\/(pull\/\d+|commit\/[0-9a-fA-F]{7,40})\/?$/)
.optional()
- .describe('A link to the source when it is not a query, for example a commit, a pull request or a deploy.'),
+ .describe(
+ 'A link to the GitHub pull request or commit behind this, when it is not a query or a saved insight. No other links are accepted.'
+ ),
})
const ExplainChartChapterSchema = z.object({
@@ -636,43 +642,63 @@ const ExplainChartChapterSchema = z.object({
evidence: z.array(ExplainChartEvidenceSchema).max(6).optional().describe('What you checked, at most 6 findings.'),
})
+const explainChartFields = {
+ 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.'),
+}
+
+const onlyOneChart = {
+ check: (params: { insightId?: unknown; query?: unknown }): boolean =>
+ (params.insightId === undefined) !== (params.query === undefined),
+ message: 'Pass exactly one of `insightId` or `query`.',
+}
+
+const explainChartAliases = normalizeParamAliases({ insightId: ['id', 'insight_id', 'short_id', 'shortId'] })
+
export const ExplainChartInputSchema = z.preprocess(
- normalizeParamAliases({ insightId: ['id', 'insight_id', 'short_id', 'shortId'] }),
+ explainChartAliases,
+ z.object(explainChartFields).refine(onlyOneChart.check, { message: onlyOneChart.message })
+)
+
+export const ExplainChartSaveInputSchema = z.preprocess(
+ explainChartAliases,
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
+ ...explainChartFields,
+ explanationId: z
.string()
- .min(1)
- .max(300)
+ .uuid()
+ .optional()
.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**.'
+ 'The id an earlier `explain-chart-save` call on this chart returned, when you are fixing that explanation. Its link then shows the fix. Omit it for a new explanation.'
),
- 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`.',
})
+ .refine(onlyOneChart.check, { message: onlyOneChart.message })
)
export const AIObservabilityGetCostsSchema = z.object({
diff --git a/services/mcp/src/templates/sections/explain-chart.md b/services/mcp/src/templates/sections/explain-chart.md
index 27466c7f2c6f..45df9c7cf065 100644
--- a/services/mcp/src/templates/sections/explain-chart.md
+++ b/services/mcp/src/templates/sections/explain-chart.md
@@ -3,6 +3,7 @@
When the person asks why a metric changed over time, for example why it dropped, spiked or rose, load the `posthog:investigate-metric` skill and follow it.
This applies to a saved insight or a dashboard tile by link or ID, to a screenshot of a chart, and to a metric the person only names, such as "why did signups drop last week?".
Its answer is the chart explanation from `explain-chart` in the conversation, not a notebook: for that question, this replaces the notebook default above.
+{explain_chart_link_line}
Write a notebook as well only when the person asks for one to keep.
- Read the schema of `explain-chart` when you start, and make the chart explanation the last step of your plan. Call it before you write your final reply.
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 3b3aba214a53..40a94ab453b0 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -17,6 +17,7 @@ import submitFeedback from './feedback/submit'
// Generated tools (from definitions/*.yaml)
import { GENERATED_TOOL_MAP } from './generated'
import explainChart from './insights/explainChart'
+import explainChartSave from './insights/explainChartSave'
// Insights
import queryInsight from './insights/query'
import insightTrustCheck from './insights/trustCheck'
@@ -104,6 +105,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
'insight-query': queryInsight,
'insight-trust-check': insightTrustCheck,
'explain-chart': explainChart,
+ 'explain-chart-save': explainChartSave,
// 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.ts
index 418c1c1c8fb0..3c25c3cbe1f0 100644
--- a/services/mcp/src/tools/insights/explainChart.ts
+++ b/services/mcp/src/tools/insights/explainChart.ts
@@ -15,13 +15,15 @@ import type {
StoryTrendsQuery,
} from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
import { sqlEvidenceChart } from 'products/product_analytics/mcp/apps/explainChart/sqlEvidenceChart'
+import { insightPageShowsStory } from 'products/product_analytics/mcp/apps/explainChart/storyDisplays'
+import { storyEvidenceNode } from 'products/product_analytics/mcp/apps/explainChart/storyEvidenceNode'
import { analyzeQuery } from '../shared'
import { findStoryRange, lastBucketInProgress } from './storyRanges'
const schema = ExplainChartInputSchema
-type Params = z.infer<typeof schema>
+export type Params = z.infer<typeof schema>
type Result = ExplainChartData & { [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: string }
@@ -137,8 +139,9 @@ function sqlProblems(chapters: Params['chapters'], sqlEvidence: Map<string, SqlE
)
}
-interface StoryChart {
+export interface StoryChart {
query: StoryTrendsQuery
+ linkableInsightId: number | null
insightName: string | null
path: string
}
@@ -161,21 +164,14 @@ function asTrendsQuery(query: unknown): StoryTrendsQuery {
}
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))}`
+ return `/insights/new#q=${encodeURIComponent(JSON.stringify(storyEvidenceNode(query)))}`
}
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) }
+ return { query, linkableInsightId: null, insightName: null, path: newInsightPath(query) }
}
const insight = await context.api.insights({ projectId }).get({ insightId: params.insightId })
if (!insight.success) {
@@ -183,6 +179,11 @@ async function loadChart(context: Context, projectId: string, params: Params): P
}
return {
query: asTrendsQuery(insight.data.query),
+ linkableInsightId: insightPageShowsStory(
+ (analyzeQuery(insight.data.query).innerQuery as StoryTrendsQuery | undefined)?.trendsFilter?.display
+ )
+ ? insight.data.id
+ : null,
insightName: insight.data.name || insight.data.derived_name || null,
path: `/insights/${insight.data.short_id}`,
}
@@ -194,16 +195,15 @@ function warningMessages(warnings: unknown[]): string[] {
)
}
-function describeResult(
- chart: StoryChart,
- series: StorySeriesResult,
- chapters: Params['chapters'],
- missed: string[],
- warnings: unknown[],
- evidenceProblems: string[]
-): string {
+function describeResult(built: BuiltExplanation, chapterCount: number): string {
+ const { chart, series, missed, warnings, evidenceProblems } = built
const name = chart.insightName ?? series.label ?? 'the chart'
- const lines = [`The explanation of "${name}" has ${chapters.length} chapters.`]
+ const lines = [`The explanation of "${name}" has ${chapterCount} chapters.`]
+ if (chart.linkableInsightId !== null) {
+ lines.push(
+ 'Where the person cannot see it rendered inline, call explain-chart-save with the same arguments for a link that opens it beside the chart in PostHog.'
+ )
+ }
if (warnings.length) {
lines.push(`The query came with warnings the person should hear about: ${warningMessages(warnings).join(' ')}`)
}
@@ -218,10 +218,18 @@ function describeResult(
return lines.join(' ')
}
-export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = async (
- context: Context,
- params: Params
-) => {
+export interface BuiltExplanation {
+ projectId: string
+ baseUrl: string
+ chart: StoryChart
+ series: StorySeriesResult
+ data: ExplainChartData
+ missed: string[]
+ warnings: unknown[]
+ evidenceProblems: string[]
+}
+
+export async function buildExplanation(context: Context, params: Params): Promise<BuiltExplanation> {
const projectId = await context.stateManager.getProjectId()
const chart = await loadChart(context, projectId, params)
@@ -258,8 +266,13 @@ export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = a
const sql = isSqlQuery(item.query) ? sqlEvidence.get(JSON.stringify(item.query)) : undefined
return {
text: item.text,
- url: item.query ? `${baseUrl}${newInsightPath(item.query)}` : (item.url ?? null),
- query: queryTool ? item.query : null,
+ url: item.query
+ ? `${baseUrl}${newInsightPath(item.query)}`
+ : item.insightShortId
+ ? `${baseUrl}/insights/${item.insightShortId}`
+ : (item.url ?? null),
+ query: item.query ?? null,
+ insightShortId: item.insightShortId ?? null,
queryTool,
chart: sql && 'chart' in sql ? sql.chart : null,
}
@@ -267,7 +280,8 @@ export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = a
}
})
- return {
+ const data: ExplainChartData = {
+ shape: 'time_series',
query: chart.query,
results,
seriesIndex: params.series,
@@ -276,15 +290,28 @@ export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = a
...(warnings?.length ? { warnings } : {}),
headline: params.headline,
chapters,
- _posthogUrl: `${baseUrl}${chart.path}`,
- [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: describeResult(
- chart,
- series,
- params.chapters,
- missed,
- warnings ?? [],
- sqlProblems(params.chapters, sqlEvidence)
- ),
+ }
+ return {
+ projectId,
+ baseUrl,
+ chart,
+ series,
+ data,
+ missed,
+ warnings: warnings ?? [],
+ evidenceProblems: sqlProblems(params.chapters, sqlEvidence),
+ }
+}
+
+export const explainChartHandler: ToolBase<typeof schema, Result>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const built = await buildExplanation(context, params)
+ return {
+ ...built.data,
+ _posthogUrl: `${built.baseUrl}${built.chart.path}`,
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: describeResult(built, params.chapters.length),
}
}
diff --git a/services/mcp/src/tools/insights/explainChartSave.ts b/services/mcp/src/tools/insights/explainChartSave.ts
new file mode 100644
index 000000000000..f0203d223de7
--- /dev/null
+++ b/services/mcp/src/tools/insights/explainChartSave.ts
@@ -0,0 +1,95 @@
+import type { z } from 'zod'
+
+import { PostHogApiError } from '@/lib/errors'
+import { ExplainChartSaveInputSchema } from '@/schema/tool-inputs'
+import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type ToolBase } from '@/tools/types'
+
+import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import { storySeriesLabel } from 'products/product_analytics/mcp/apps/explainChart/storySeries'
+
+import { buildExplanation } from './explainChart'
+
+const schema = ExplainChartSaveInputSchema
+
+type Params = z.infer<typeof schema>
+
+type Result = {
+ explanationId: string | null
+ _posthogUrl?: string
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: string
+}
+
+const NOT_LINKABLE =
+ 'This chart has no saved insight that shows the explanation beside it, so there is no link. Give the findings in text.'
+
+// The page builds PostHog links from the query or insight id, so only GitHub links are stored.
+function storedExplanation(data: ExplainChartData): ExplainChartData {
+ return {
+ ...data,
+ results: data.results.map((result, index) =>
+ index === data.seriesIndex
+ ? { ...result, label: storySeriesLabel(result.label) }
+ : { label: storySeriesLabel(result.label) }
+ ),
+ chapters: data.chapters.map((chapter) => ({
+ ...chapter,
+ evidence: chapter.evidence.map((item) =>
+ item.query || item.insightShortId ? { ...item, url: null } : item
+ ),
+ })),
+ }
+}
+
+function isNotFound(error: unknown): boolean {
+ return error instanceof PostHogApiError && error.status === 404
+}
+
+function notSaved(reason: string): Result {
+ return {
+ explanationId: null,
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: `The explanation was not saved, so there is no link to it. Give the findings in text and tell the person why: ${reason}`,
+ }
+}
+
+export const explainChartSaveHandler: ToolBase<typeof schema, Result>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const { projectId, baseUrl, chart, data } = await buildExplanation(context, params)
+ if (chart.linkableInsightId === null) {
+ return { explanationId: null, [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: NOT_LINKABLE }
+ }
+ const insightId = chart.linkableInsightId
+ const insights = context.api.insights({ projectId })
+ const stored = storedExplanation(data)
+ try {
+ const updated = params.explanationId
+ ? await insights.updateExplanation({ insightId, explanationId: params.explanationId, data: stored })
+ : null
+ // An id from another chart or another person is not found, so that fix becomes a new explanation.
+ const saved =
+ updated && (updated.success || !isNotFound(updated.error))
+ ? updated
+ : await insights.saveExplanation({ insightId, data: stored })
+ if (!saved.success) {
+ return notSaved(saved.error.message)
+ }
+ const url = `${baseUrl}${chart.path}?explanation=${saved.data.id}`
+ return {
+ explanationId: saved.data.id,
+ _posthogUrl: url,
+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: [
+ `Give the person this link, which opens the explanation beside the chart in PostHog: ${url}`,
+ `To fix this explanation, call explain-chart-save again with explanationId "${saved.data.id}", so the link shows the fix.`,
+ ].join(' '),
+ }
+ } catch (error) {
+ return notSaved(error instanceof Error ? error.message : String(error))
+ }
+}
+
+export default (): ToolBase<typeof schema, Result> => ({
+ name: 'explain-chart-save',
+ schema,
+ handler: explainChartSaveHandler,
+})
diff --git a/services/mcp/tests/unit/explain-chart.test.ts b/services/mcp/tests/unit/explain-chart.test.ts
index b5be39dae35a..97523caa9805 100644
--- a/services/mcp/tests/unit/explain-chart.test.ts
+++ b/services/mcp/tests/unit/explain-chart.test.ts
@@ -1,9 +1,14 @@
import { describe, expect, it, vi } from 'vitest'
+import { PostHogApiError } from '@/lib/errors'
+import { ExplainChartInputSchema } from '@/schema/tool-inputs'
import { explainChartHandler } from '@/tools/insights/explainChart'
+import { explainChartSaveHandler } from '@/tools/insights/explainChartSave'
import { findStoryRange, lastBucketInProgress } from '@/tools/insights/storyRanges'
import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'
+import { insightPageShowsStory } from 'products/product_analytics/mcp/apps/explainChart/storyDisplays'
+
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']
@@ -11,7 +16,16 @@ 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 {
+function apiError(status: number): PostHogApiError {
+ return new PostHogApiError({ status, statusText: '', body: '', url: '', method: 'PUT' })
+}
+
+function createContext(
+ query: Record<string, unknown>,
+ response: Record<string, unknown> = {},
+ saved: unknown = { success: true, data: { id: 'e1' } },
+ updated: unknown = { success: false, error: apiError(404) }
+): Context {
return {
api: {
insights: vi.fn().mockReturnValue({
@@ -19,6 +33,8 @@ function createContext(query: Record<string, unknown>, response: Record<string,
success: true,
data: { id: 7, short_id: 'abc12345', name: 'Sign-ups', query },
}),
+ saveExplanation: vi.fn().mockResolvedValue(saved),
+ updateExplanation: vi.fn().mockResolvedValue(updated),
}),
query: vi.fn().mockReturnValue({
runQuery: vi.fn().mockResolvedValue({
@@ -50,7 +66,7 @@ describe('explain-chart', () => {
expect(findStoryRange([...days], interval, start, end)).toEqual(expected)
})
- it('shows the chapters and tells the agent which dates matched no point', async () => {
+ it('shows the chapters, tells the agent which dates matched no point, and saves nothing', async () => {
const context = createContext({ kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } })
const result = await explainChartHandler(context, {
@@ -66,6 +82,104 @@ describe('explain-chart', () => {
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"')
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toContain('explain-chart-save')
+ const { saveExplanation, updateExplanation } = vi.mocked(context.api.insights).mock.results[0]!.value
+ expect(saveExplanation).not.toHaveBeenCalled()
+ expect(updateExplanation).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [
+ 'the explanation it saved',
+ { success: true, data: { id: 'e1' } },
+ { success: true, data: { id: 'e2' } },
+ 'e1',
+ ],
+ [
+ 'an id it cannot update',
+ { success: false, error: apiError(404) },
+ { success: true, data: { id: 'e2' } },
+ 'e2',
+ ],
+ [
+ 'an explanation the server failed to update',
+ { success: false, error: apiError(500) },
+ { success: true, data: { id: 'e2' } },
+ null,
+ ],
+ [
+ 'an id it cannot update while saving is throttled',
+ { success: false, error: apiError(404) },
+ { success: false, error: new Error('Throttled') },
+ null,
+ ],
+ ])('keeps the link when the agent fixes %s', async (_, updated, saved, id) => {
+ const context = createContext(
+ { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } },
+ {},
+ saved,
+ updated
+ )
+
+ const result = await explainChartSaveHandler(context, {
+ insightId: 'abc12345',
+ series: 0,
+ headline: 'One day stands out.',
+ chapters: [{ title: 'A spike on October 2', start: '2026-10-02' }],
+ explanationId: '0190a3a4-0000-7000-8000-000000000001',
+ })
+
+ expect(result.explanationId).toBe(id)
+ expect(result._posthogUrl).toBe(
+ id ? `https://us.posthog.com/project/1/insights/abc12345?explanation=${id}` : undefined
+ )
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY].includes(`explanationId "${id}"`)).toBe(!!id)
+ })
+
+ it('links evidence to its query, insight or GitHub change, and saves no PostHog links', async () => {
+ const context = createContext({ kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } })
+ const github = 'https://github.com/example/app/pull/12'
+ const args = {
+ insightId: 'abc12345',
+ series: 0,
+ headline: 'One day stands out.',
+ chapters: [
+ {
+ title: 'A spike on October 2',
+ start: '2026-10-02',
+ evidence: [
+ { text: 'From one referrer.', query: { kind: 'TrendsQuery', series: [] } },
+ { text: 'The signup funnel shows it.', insightShortId: 'xyz98765' },
+ { text: 'A release went out.', url: github },
+ ],
+ },
+ ],
+ }
+
+ const result = await explainChartHandler(context, args)
+
+ const shown = result.chapters[0]!.evidence.map((item) => item.url)
+ expect(shown[0]).toContain('/project/1/insights/new')
+ expect(shown.slice(1)).toEqual(['https://us.posthog.com/project/1/insights/xyz98765', github])
+ await explainChartSaveHandler(context, args)
+ const { saveExplanation } = vi.mocked(context.api.insights).mock.results[0]!.value
+ const stored = saveExplanation.mock.calls[0][0].data.chapters[0].evidence.map(
+ (item: { url: string | null }) => item.url
+ )
+ expect(stored).toEqual([null, null, github])
+ })
+
+ it.each([
+ ['a site other than GitHub', 'https://hackmycomputer.example/pull/1'],
+ ['a GitHub file', 'https://github.com/example/app/raw/main/setup.exe'],
+ ])('refuses evidence that links to %s', (_, url) => {
+ const parsed = ExplainChartInputSchema.safeParse({
+ insightId: 'abc12345',
+ headline: 'One day stands out.',
+ chapters: [{ title: 'A spike', start: '2026-10-02', evidence: [{ text: 'A release.', url }] }],
+ })
+
+ expect(parsed.success).toBe(false)
})
it.each([['a funnel', { kind: 'FunnelsQuery', series: [] }, 'only explains trends charts']])(
@@ -125,10 +239,13 @@ describe('explain-chart', () => {
await expect(call).rejects.toThrow('one value over time')
return
}
- await call
+ const result = await call
expect(context.api.query({ projectId: '1' }).runQuery).toHaveBeenCalledWith({
query: expect.objectContaining({ trendsFilter: { display: drawnAs } }),
})
+ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY].includes('explain-chart-save')).toBe(
+ insightPageShowsStory(display)
+ )
})
it('draws each piece of evidence from the query behind it', async () => {
diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.ts
index aa04ad442d84..f045685783dd 100644
--- a/services/mcp/tests/unit/instructions.test.ts
+++ b/services/mcp/tests/unit/instructions.test.ts
@@ -153,6 +153,7 @@ describe('buildToolDomainsBlock', () => {
'restore',
'resume',
'revoke',
+ 'save',
'ship',
'show',
'start',